Substring Search Patterns in DSA Javascript - Time & Space Complexity
When searching for a smaller string inside a bigger one, it is important to know how the time needed grows as the strings get longer.
We want to find out how the search time changes with input size.
Analyze the time complexity of the following code snippet.
function containsSubstring(text, pattern) {
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) {
return true;
}
}
return false;
}
This code checks if the pattern string exists inside the text string by comparing characters one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops where the outer loop moves through the text and the inner loop compares characters of the pattern.
- How many times: Outer loop runs about (text length - pattern length + 1) times; inner loop runs up to pattern length times for each outer loop iteration.
As the text and pattern get longer, the number of character comparisons grows roughly by multiplying their lengths.
| Input Size (text length n) | Approx. Operations |
|---|---|
| 10 (pattern length m = 3) | About 8 * 3 = 24 comparisons |
| 100 (pattern length m = 5) | About 96 * 5 = 480 comparisons |
| 1000 (pattern length m = 10) | About 991 * 10 = 9,910 comparisons |
Pattern observation: The operations grow roughly by the product of text length and pattern length.
Time Complexity: O(n * m)
This means the time to search 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 pattern length also affects time.
Understanding how substring search time grows helps you explain and improve string matching in real applications, showing your grasp of algorithm efficiency.
"What if we used a more advanced algorithm like KMP that preprocesses the pattern? How would the time complexity change?"
Practice
indexOf method do when used on a string in JavaScript?Solution
Step 1: Understand the purpose of
TheindexOfindexOfmethod searches a string for a specified substring and returns the position of its first occurrence.Step 2: Confirm behavior on strings
If the substring is found, it returns the zero-based index; if not found, it returns -1.Final Answer:
Finds the position of the first occurrence of a substring -> Option DQuick Check:
indexOf= position of substring [OK]
- Confusing indexOf with replace method
- Thinking indexOf splits the string
- Assuming indexOf changes the string case
'cat' exists in the string text using includes method?Solution
Step 1: Recall the correct method name
The correct method to check substring presence isincludes, called on the string object.Step 2: Verify syntax
The syntax isstring.includes(substring), sotext.includes('cat')is correct.Final Answer:
text.includes('cat') -> Option CQuick Check:
Correct method call syntax = text.includes('cat') [OK]
string.includes(substring) to check presence [OK]- Using wrong method name like include or contains
- Calling includes as a standalone function
- Passing arguments in wrong order
const text = 'hello world';
const pos = text.indexOf('o');
console.log(pos);Solution
Step 1: Identify the string and substring
The string is 'hello world' and the substring searched is 'o'.Step 2: Find the first occurrence of 'o'
Counting from zero: h(0) e(1) l(2) l(3) o(4) (space 5) w(6) o(7). The first 'o' is at index 4.Step 3: Verify the output
The code usesindexOf('o')which returns the first occurrence index, which is 4.Final Answer:
4 -> Option AQuick Check:
First 'o' index = 4 [OK]
- Counting index starting from 1 instead of 0
- Confusing second 'o' position with first
- Assuming indexOf returns -1 if substring exists
'test' exists in str. What is the error?const str = 'this is a test';
if (str.indexOf == 'test') {
console.log('Found');
} else {
console.log('Not Found');
}Solution
Step 1: Analyze the use of indexOf
The code usesstr.indexOfwithout parentheses, so it refers to the function itself, not the result of calling it.Step 2: Understand the comparison
Comparing a function to a string ('test') is always false, so the condition is incorrect.Final Answer:
indexOf is used without parentheses, so it compares function to string -> Option BQuick Check:
Missing parentheses on indexOf causes error [OK]
- Forgetting parentheses on indexOf
- Using wrong comparison operator
- Assuming indexOf returns boolean directly
'ana' in the string 'banana'. Which approach correctly finds all positions?Solution
Step 1: Understand the problem of multiple occurrences
To find all positions, you must repeatedly search starting after the last found position.Step 2: Use a loop with indexOf and update start
UseindexOf('ana', start)in a loop, updatingstartto position + 1 each time until no more found.Final Answer:
Use a loop withindexOfand update the start position after each find -> Option AQuick Check:
Loop + indexOf with updated start = all positions [OK]
- Using includes which returns only true/false
- Using lastIndexOf which finds only last occurrence
- Using replace which changes string and loses positions
Ready to prove it?
Pass the test and this pattern moves unknown
