Searching and replacing text in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we search and replace text in a string, we want to know how the time it takes changes as the text gets longer.
We ask: How does the work grow when the input text grows?
Analyze the time complexity of the following code snippet.
text = "hello world hello"
old = "hello"
new = "hi"
result = text.replace(old, new)
print(result)
This code replaces all occurrences of "hello" with "hi" in the given text string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each part of the text to find matches of the old word.
- How many times: The operation runs once for each character in the text string.
As the text gets longer, the program checks more characters to find matches.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the length of the text.
Time Complexity: O(n)
This means the time to replace text grows in a straight line as the text gets longer.
[X] Wrong: "Replacing text takes the same time no matter how long the text is."
[OK] Correct: The program must look through the whole text to find what to replace, so longer text means more work.
Understanding how searching and replacing text scales helps you explain how programs handle big inputs smoothly.
"What if we replaced only the first occurrence instead of all? How would the time complexity change?"
Practice
replace method do in Python strings?Solution
Step 1: Understand the purpose of replace()
Thereplacemethod searches for a substring and replaces it with another substring.Step 2: Check if it modifies original string
Strings are immutable in Python, soreplacereturns a new string without changing the original.Final Answer:
It finds a specified substring and replaces it with another substring. -> Option AQuick Check:
replace() = find and change substring [OK]
- Thinking replace changes the original string
- Confusing replace with delete or count methods
- Assuming replace modifies in-place
text?Solution
Step 1: Recall replace() syntax
The correct syntax isstring.replace(old, new[, count]), whereoldandneware strings.Step 2: Analyze options
text.replace('cat', 'dog') matches the correct syntax. Options A, B, and D use invalid syntax or parameters.Final Answer:
text.replace('cat', 'dog') -> Option BQuick Check:
replace(old, new) syntax = text.replace('cat', 'dog') [OK]
- Using arrows or keywords inside replace()
- Adding unsupported parameters like all=True
- Confusing parameter order
text = 'apple apple apple'
new_text = text.replace('apple', 'orange', 2)
print(new_text)Solution
Step 1: Understand replace with count
The third argument2limits replacements to first two occurrences.Step 2: Apply replacements
First two 'apple' become 'orange', last remains 'apple'. Result: 'orange orange apple'.Final Answer:
'orange orange apple' -> Option CQuick Check:
replace with count=2 changes first two only [OK]
- Replacing all occurrences ignoring count
- Replacing from the end instead of start
- Miscounting number of replacements
text = 'blue sky'
text.replace('blue', 'red', 'all')
print(text)Solution
Step 1: Check replace() parameters
The third parameter must be an integer count, but 'all' is a string.Step 2: Identify error type
Passing a string instead of int causes a TypeError at runtime.Final Answer:
TypeError because 'all' is not an integer for count -> Option DQuick Check:
replace count must be int, not string [OK]
- Using strings instead of integers for count
- Expecting replace to modify original string
- Confusing error types
text. You want to replace only the first 3 occurrences of the word 'error' with 'issue'. Which code snippet correctly does this?Solution
Step 1: Use replace with count parameter
To replace only first 3 occurrences, usereplace(old, new, count)with count=3.Step 2: Analyze options
new_text = text.replace('error', 'issue', 3) uses correct syntax. new_text = text.replace('error', 'issue', count=3) uses invalid keyword argument. new_text = text.replace('error', 'issue', '3') passes count as string. new_text = text.replace('error', 'issue')[:3] slices string incorrectly.Final Answer:
new_text = text.replace('error', 'issue', 3) -> Option AQuick Check:
replace(old, new, 3) replaces first 3 only [OK]
- Using keyword count instead of positional argument
- Passing count as string instead of int
- Trying to slice string after replace
