Substring Search Patterns in DSA Typescript - Time & Space Complexity
When searching for a smaller string inside a bigger one, we want to know how long it takes as the strings grow.
We ask: How does the search time change when the text or pattern gets longer?
Analyze the time complexity of the following simple substring search code.
function simpleSearch(text: string, pattern: string): number {
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 i;
}
return -1;
}
This code checks each position in the text to see if the pattern starts there.
Look for loops or repeated checks that take most time.
- Primary operation: Comparing characters of pattern with text inside the inner while loop.
- How many times: Outer loop runs about (text length - pattern length + 1) times; inner loop runs up to pattern length times per outer loop.
As text and pattern grow, the number of comparisons grows roughly by multiplying their lengths.
| Input Size (text length n) | Approx. Operations |
|---|---|
| 10 | Up to (10 - pattern length + 1) * pattern length comparisons |
| 100 | Up to (100 - pattern length + 1) * pattern length comparisons |
| 1000 | Up to (1000 - pattern length + 1) * pattern length comparisons |
Pattern observation: Doubling the text roughly doubles the work; longer patterns increase work linearly.
Time Complexity: O(n * m)
This means the time grows roughly by multiplying the text length (n) and pattern length (m).
[X] Wrong: "The search always finishes quickly because it stops at the first mismatch."
[OK] Correct: Sometimes many characters match before a mismatch, causing many checks and making the search slower.
Understanding how substring search scales helps you explain and improve search algorithms, a common skill in coding interviews.
"What if we used a more advanced algorithm like KMP? How would the time complexity change?"
Practice
Solution
Step 1: Understand substring search purpose
Substring search algorithms check if a smaller string (pattern) appears inside a bigger string (text).Step 2: Compare options with substring search definition
Only To find if a smaller string exists inside a larger string matches this goal. Sorting, reversing, or counting vowels are different tasks.Final Answer:
To find if a smaller string exists inside a larger string -> Option BQuick Check:
Substring search = find smaller string inside larger [OK]
- Confusing substring search with sorting or reversing strings
- Thinking substring search counts characters
- Mixing substring search with string length calculation
text contains substring pattern?Solution
Step 1: Recall TypeScript string methods
TypeScript strings have a method calledincludesto check substring presence.Step 2: Verify method names
Onlyincludesis valid.contains,has, andfindare not string methods in TypeScript.Final Answer:
text.includes(pattern) -> Option AQuick Check:
Use includes() to check substring presence [OK]
- Using non-existent methods like contains() or has()
- Confusing includes() with find() which is for arrays
- Forgetting parentheses after method name
const text = "hello world"; const pattern = "wor"; console.log(text.indexOf(pattern));
Solution
Step 1: Understand indexOf method
indexOfreturns the starting index of the substring if found, else -1.Step 2: Find substring position in text
In "hello world", substring "wor" starts at index 6 (0-based counting: h=0, e=1, l=2, l=3, o=4, space=5, w=6).Final Answer:
6 -> Option AQuick Check:
indexOf("wor") = 6 [OK]
- Counting index starting from 1 instead of 0
- Confusing indexOf with includes (which returns boolean)
- Assuming indexOf returns substring length
const text = "typescript";
const pattern = "script";
if (text.find(pattern)) {
console.log("Found");
} else {
console.log("Not Found");
}Solution
Step 1: Check string methods in TypeScript
Strings do not have afind()method. The correct method to check substring isincludes()orindexOf().Step 2: Verify other code parts
Semicolons are optional in TypeScript, pattern is declared, and if statement syntax is correct.Final Answer:
Using find() method on string which does not exist -> Option DQuick Check:
Strings have includes(), not find() [OK]
- Assuming find() works on strings like arrays
- Thinking semicolons are mandatory causing errors
- Misreading if statement syntax
pattern in string text. Which approach correctly finds multiple occurrences in TypeScript?Solution
Step 1: Understand multiple substring search
To find all occurrences, you must repeatedly search starting after the last found index.Step 2: Analyze each option
Use a loop with indexOf(pattern, startIndex) updating startIndex after each find uses a loop withindexOfand updates start index, which is correct. Use text.includes(pattern) repeatedly without changing index does not update index, so it loops infinitely or finds only once. Use text.indexOf(pattern) once and return that single index finds only one occurrence. Use text.findAll(pattern) method to get all indices uses a non-existent method.Final Answer:
Use a loop with indexOf(pattern, startIndex) updating startIndex after each find -> Option CQuick Check:
Loop with indexOf and updated start index finds all [OK]
- Not updating start index causing infinite loops
- Using includes() which returns boolean, not index
- Expecting findAll() method which does not exist
Ready to prove it?
Pass the test and this pattern moves unknown
