String Pattern Matching Naive in DSA Typescript - Time & Space Complexity
We want to understand how long it takes to find a pattern inside a text using a simple search method.
How does the time needed grow as the text and pattern get bigger?
Analyze the time complexity of the following code snippet.
function naivePatternSearch(text: string, pattern: string): number[] {
const result: number[] = [];
const n = text.length;
const m = pattern.length;
for (let i = 0; i <= n - m; i++) {
let j = 0;
while (j < m && text[i + j] === pattern[j]) {
j++;
}
if (j === m) result.push(i);
}
return result;
}
This code checks every possible position in the text to see if the pattern matches starting there.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer loop runs through the text positions, and the inner while loop compares characters of the pattern to the text.
- How many times: The outer loop runs about n - m + 1 times, and the inner loop can run up to m times for each outer loop iteration.
As the text and pattern grow, the number of checks grows roughly by multiplying their sizes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (text), 3 (pattern) | About 8 * 3 = 24 checks |
| 100 (text), 5 (pattern) | About 96 * 5 = 480 checks |
| 1000 (text), 10 (pattern) | About 991 * 10 = 9,910 checks |
Pattern observation: The work grows roughly by the product of text length and pattern length.
Time Complexity: O(n * m)
This means the time needed grows proportionally to the size of the text times the size of the pattern.
[X] Wrong: "The search always takes time proportional only to the text length (O(n))."
[OK] Correct: Because for each position in the text, we may need to check all characters of the pattern, so the pattern length also affects the time.
Understanding this simple search helps build a foundation for more advanced pattern matching methods and shows how nested loops affect performance.
"What if we used a more efficient algorithm like KMP? How would the time complexity change?"
Practice
Solution
Step 1: Understand naive pattern matching
The naive algorithm tries to match the pattern starting at each position in the text one by one.Step 2: Compare with other methods
Unlike hashing or trees, naive does not use extra data structures or preprocessing.Final Answer:
It checks every possible position in the text to find the pattern. -> Option CQuick Check:
Naive = check all positions [OK]
- Confusing naive with hashing or advanced algorithms
- Thinking it sorts text before matching
- Assuming it uses trees or graphs
Solution
Step 1: Determine loop range for matching
The loop must start at 0 and go up to text.length - pattern.length inclusive to check all valid positions.Step 2: Check syntax correctness
for (let i = 0; i <= text.length - pattern.length; i++) uses <= and correct boundaries, others either start at 1 or wrong limits.Final Answer:
for (let i = 0; i <= text.length - pattern.length; i++) -> Option DQuick Check:
Loop from 0 to text.length - pattern.length inclusive [OK]
- Starting loop at 1 instead of 0
- Looping beyond valid range causing errors
- Using pattern length as loop limit
const text = "abcabcabc";
const pattern = "abc";
let count = 0;
for (let i = 0; i <= text.length - pattern.length; i++) {
let j = 0;
while (j < pattern.length && text[i + j] === pattern[j]) {
j++;
}
if (j === pattern.length) {
count++;
}
}
console.log(count);Solution
Step 1: Identify pattern occurrences in text
The pattern "abc" appears at positions 0, 3, and 6 in the text "abcabcabc".Step 2: Count matches using the loop
The code increments count each time the pattern matches fully, so count becomes 3.Final Answer:
3 -> Option AQuick Check:
Pattern "abc" occurs 3 times [OK]
- Counting overlapping matches incorrectly
- Stopping after first match
- Off-by-one errors in loop
const text = "hellohello";
const pattern = "lo";
for (let i = 0; i < text.length - pattern.length; i++) {
let j = 0;
while (j < pattern.length && text[i + j] === pattern[j]) {
j++;
}
if (j === pattern.length) {
console.log(i);
}
}Solution
Step 1: Check loop boundary for matching
The loop ends at text.length - pattern.length - 1 due to < operator, missing last valid position.Step 2: Correct loop condition
Changing < to <= includes the last position where pattern can match.Final Answer:
The loop should use <= instead of < to include last position. -> Option BQuick Check:
Loop boundary must cover all valid start indices [OK]
- Using < instead of <= in loop
- Changing && to || in while condition
- Misplacing console.log outside loop
Solution
Step 1: Understand overlapping matches
Overlapping means matches can start inside a previous match, so we must check every position.Step 2: Adjust index increment after match
Instead of jumping by pattern length, increment start index by 1 to check next position for overlaps.Final Answer:
After finding a match, move the start index by 1 instead of pattern length. -> Option AQuick Check:
Increment by 1 to count overlaps [OK]
- Skipping positions after match causing missed overlaps
- Using hash functions unnecessarily
- Trying to skip overlaps to speed up
Ready to prove it?
Pass the test and this pattern moves unknown
