Substring Search Patterns in DSA Python - Time & Space Complexity
We want to understand how long it takes to find a smaller string inside a bigger string.
How does the time needed grow when the strings get longer?
Analyze the time complexity of the following code snippet.
def substring_search(text: str, pattern: str) -> int:
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:
return i
return -1
This code looks for the first place where the pattern appears inside the text.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each character of the pattern against the text.
- How many times: For each possible start in the text, it checks up to the length of the pattern.
As the text and pattern get longer, the number of checks grows roughly by multiplying their lengths.
| Input Size (text length n) | Approx. Operations |
|---|---|
| 10 (pattern length m = 3) | About 8 * 3 = 24 checks |
| 100 (pattern length m = 5) | About 96 * 5 = 480 checks |
| 1000 (pattern length m = 10) | About 991 * 10 = 9,910 checks |
Pattern observation: The work grows roughly by n times m, so doubling text or pattern length roughly doubles the work.
Time Complexity: O(n * m)
This means the time needed grows proportionally to the product of the text length and the pattern length.
[X] Wrong: "The search always takes time proportional to the text length only."
[OK] Correct: Because for each position in the text, we may need to check every character of the pattern, so pattern length matters too.
Understanding this helps you explain why simple substring search can be slow and why smarter methods exist.
"What if we used a smarter algorithm like KMP? How would the time complexity change?"
Practice
in operator check when used like 'abc' in 'abcdef' in Python?Solution
Step 1: Understand the
Theinoperator for stringsinoperator checks if the left string is found anywhere inside the right string.Step 2: Apply to given strings
Since 'abc' is at the start of 'abcdef', it is found inside it.Final Answer:
If the substring 'abc' exists anywhere inside the string 'abcdef' -> Option AQuick Check:
'abc' in 'abcdef' = True [OK]
- Thinking 'in' only checks start of string
- Confusing 'in' with equality
- Assuming 'in' checks only end of string
'cat' in string s = 'concatenate' using Python?Solution
Step 1: Recall Python string method for substring index
Python strings have a method calledfind()to locate substring index.Step 2: Check method usage
The correct syntax iss.find('cat'). Other options are invalid in Python.Final Answer:
s.find('cat') -> Option CQuick Check:
Usestring.find(substring)syntax [OK]
string.find(substring) to get index [OK]- Using non-Python syntax like indexOf
- Calling find as a standalone function
- Confusing method name or order of arguments
text = 'abracadabra'
pos = text.find('ra')
print(pos)Solution
Step 1: Understand
Thefind()method behaviorfind()method returns the lowest index where the substring is found or -1 if not found.Step 2: Locate substring 'ra' in 'abracadabra'
The substring 'ra' first appears starting at index 1 (abracadabra).Final Answer:
1 -> Option BQuick Check:
First 'ra' at index 1 [OK]
- Assuming find() returns all occurrences
- Confusing index with count
- Mistaking find() return -1 for found substring
'dog' is in string s:s = 'hotdog'
if s.contains('dog'):
print('Found')
else:
print('Not Found')Solution
Step 1: Check string method availability in Python
Python strings do not have acontains()method; membership is checked within.Step 2: Correct way to check substring presence
Use'dog' in sinstead ofs.contains('dog').Final Answer:
The methodcontainsdoes not exist for strings in Python -> Option AQuick Check:
Useinoperator, notcontains()[OK]
in for substring check, not contains() [OK]- Using Java-like contains() method in Python
- Misspelling substring or variable
- Assuming print syntax is wrong
s = 'banana', which code snippet correctly finds all starting indices of substring 'ana' in s?Solution
Step 1: Understand substring search for all occurrences
To find all starting indices, check each position if substring matches.Step 2: Analyze each option
indices = [i for i in range(len(s)) if s[i:i+3] == 'ana'] uses slicing and compares substring at each index correctly. indices = [s.find('ana')] finds only first occurrence. indices = [i for i in range(len(s)) if s.find('ana') == i] incorrectly compares find() result to index. indices = [i for i in range(len(s)) if 'ana' in s[i]] incorrectly checks membership of substring in single character.Final Answer:
indices = [i for i in range(len(s)) if s[i:i+3] == 'ana'] -> Option DQuick Check:
Slice and compare at each index for all matches [OK]
- Using find() only returns first match
- Comparing find() result incorrectly
- Checking substring in single character
Ready to prove it?
Pass the test and this pattern moves unknown
