Scan for all matches in Ruby - Time & Space Complexity
We want to understand how long it takes to find all matches of a pattern in a string.
How does the time needed grow as the string gets longer?
Analyze the time complexity of the following code snippet.
text = "hello hello hello"
pattern = /hello/
matches = text.scan(pattern)
This code finds all occurrences of "hello" in the text string.
- Primary operation: The scan method checks each position in the string to see if the pattern matches.
- How many times: It repeats this check for almost every character in the string.
As the string gets longer, the number of checks grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows steadily as the string grows longer.
Time Complexity: O(n)
This means the time to find all matches grows in a straight line with the string length.
[X] Wrong: "The scan method only looks at the first few characters, so it's very fast regardless of string size."
[OK] Correct: Actually, scan checks the whole string to find all matches, so the time grows with the string length.
Understanding how searching through text grows with input size helps you explain efficiency clearly and confidently.
"What if the pattern was more complex, like a nested group or optional parts? How would the time complexity change?"