String Pattern Matching Naive in DSA Python - Time & Space Complexity
We want to understand how long it takes to find a pattern inside a text using a simple method.
How does the time needed grow when the text or pattern gets bigger?
Analyze the time complexity of the following code snippet.
def naive_pattern_search(text: str, pattern: str) -> int:
n = len(text)
m = len(pattern)
for i in range(n - m + 1):
j = 0
while j < m and text[i + j] == pattern[j]:
j += 1
if j == m:
return i
return -1
This code checks every possible place in the text to see if the pattern matches starting there.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing characters of the pattern with the text one by one.
- How many times: For each position in the text (up to n - m + 1), it may compare up to m characters.
As the text and pattern get longer, the number of comparisons grows roughly by multiplying their lengths.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (text), 3 (pattern) | About 8 * 3 = 24 comparisons |
| 100 (text), 5 (pattern) | About 96 * 5 = 480 comparisons |
| 1000 (text), 10 (pattern) | About 991 * 10 = 9,910 comparisons |
Pattern observation: Doubling the text or pattern length roughly doubles the work, so the total work grows like the product of their sizes.
Time Complexity: O(n * m)
This means the time needed grows proportionally to the length of the text times the length of the pattern.
[X] Wrong: "The search always takes time proportional to the text length only."
[OK] Correct: Because for each position in the text, the pattern characters are also checked one by one, so pattern length matters too.
Understanding this simple search helps build intuition for more advanced methods and shows you can analyze nested loops clearly.
"What if we stopped searching after the first mismatch instead of checking all characters? How would the time complexity change?"
Practice
Solution
Step 1: Understand naive matching approach
The naive algorithm tries to match the pattern starting at every position in the text.Step 2: Compare with other methods
Other methods use hashing or preprocessing, but naive does not.Final Answer:
Check every possible position in the text to see if the pattern matches -> Option DQuick Check:
Naive = Check all positions [OK]
- Thinking naive uses hashing
- Assuming pattern is preprocessed
- Believing text is sorted before matching
Solution
Step 1: Identify correct loop variables and indexing
We loop over pattern length with j, compare text[i+j] with pattern[j].Step 2: Check each option's indexing
for j in range(len(pattern)): if text[i+j] != pattern[j]: break correctly uses text[i+j] and pattern[j]. Others mix indices or variables incorrectly.Final Answer:
for j in range(len(pattern)): if text[i+j] != pattern[j]: break -> Option AQuick Check:
Correct indexing = for j in range(len(pattern)): if text[i+j] != pattern[j]: break [OK]
- Swapping text and pattern indices
- Using wrong loop variable
- Mixing i and j incorrectly
text = "abracadabra"
pattern = "cada"
positions = []
for i in range(len(text) - len(pattern) + 1):
match = True
for j in range(len(pattern)):
if text[i+j] != pattern[j]:
match = False
break
if match:
positions.append(i)
print(positions)Solution
Step 1: Check substring positions in text
Pattern 'cada' length is 4. Check text from index 0 to 7 (11-4).Step 2: Find matching index
At index 4: text[4:8] = 'cada' matches pattern exactly.Final Answer:
[4] -> Option CQuick Check:
Match at index 4 only [OK]
- Off-by-one error in range
- Misreading substring indices
- Appending wrong index on match
text = "hellohello"
pattern = "llo"
positions = []
for i in range(len(text) - len(pattern)):
match = True
for j in range(len(pattern)):
if text[i+j] != pattern[j]:
match = False
break
if match:
positions.append(i)
print(positions)Solution
Step 1: Analyze outer loop range
Outer loop uses range(len(text) - len(pattern)) which excludes last valid start index.Step 2: Correct range to include last position
It should be range(len(text) - len(pattern) + 1) to check all positions.Final Answer:
The range in outer loop misses last possible position -> Option BQuick Check:
Loop range off by one [OK]
- Using range without +1
- Confusing inner loop indices
- Not resetting match flag properly
Solution
Step 1: Understand overlapping matches
Overlapping means matches can start before previous match ends.Step 2: Modify iteration after match
Instead of skipping ahead by pattern length, move only one step forward to catch overlaps.Final Answer:
After finding a match at index i, continue checking from i+1 instead of i+len(pattern) -> Option AQuick Check:
Move one step after match for overlaps [OK]
- Skipping too far after match
- Using hashing unnecessarily
- Reversing strings without reason
Ready to prove it?
Pass the test and this pattern moves unknown
