Substring Search Patterns in DSA Java - 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 code snippet.
public int substringSearch(String text, String pattern) {
int n = text.length();
int m = pattern.length();
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if (text.charAt(i + j) != pattern.charAt(j)) {
break;
}
}
if (j == m) {
return i; // pattern found
}
}
return -1; // pattern not found
}
This code checks each possible position in the text to see if the pattern matches starting there.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops comparing characters of pattern and text.
- How many times: Outer loop runs about (n - m + 1) times; inner loop runs up to m times per outer loop.
As the text and pattern get longer, the number of character comparisons grows roughly by multiplying their lengths.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (text), 3 (pattern) | About 8 * 3 = 24 comparisons |
| 100 (text), 5 (pattern) | About 96 * 5 = 480 comparisons |
| 1000 (text), 10 (pattern) | About 991 * 10 = 9,910 comparisons |
Pattern observation: Operations grow roughly like text length times pattern length.
Time Complexity: O(n * m)
This means the time to search grows proportionally to the product of the text and pattern lengths.
[X] Wrong: "The search always takes time proportional to the text length only."
[OK] Correct: Because for each position in the text, we may compare many characters of the pattern, so pattern length also affects time.
Understanding this helps you explain why simple substring search can be slow and why smarter methods exist, showing your grasp of algorithm efficiency.
"What if we used a smarter algorithm like KMP that preprocesses the pattern? How would the time complexity change?"
Practice
indexOf method in Java's String class return when searching for a substring that exists in the string?Solution
Step 1: Understand the purpose of
TheindexOfindexOfmethod searches for the first occurrence of a substring inside a string and returns its position.Step 2: Identify the return value when substring exists
If the substring is found,indexOfreturns the starting index (0-based) of that substring in the string.Final Answer:
The starting index of the first occurrence of the substring -> Option AQuick Check:
indexOfreturns index, not count or boolean [OK]
- Thinking indexOf returns count of occurrences
- Assuming it returns true/false
- Confusing indexOf with substring length
"cat" in string str in Java?Solution
Step 1: Recall Java String methods for substring search
Java'sStringclass usesindexOfto find substring positions.Step 2: Check method names and return types
findandsearchare not valid String methods;containsreturns boolean, not int.Final Answer:
int pos = str.indexOf("cat"); -> Option CQuick Check:
UseindexOffor substring position [OK]
- Using non-existent methods like find or search
- Using contains which returns boolean, not index
- Confusing method names from other languages
String text = "hello world";
int pos = text.indexOf("lo");
System.out.println(pos);Solution
Step 1: Locate substring "lo" in "hello world"
Counting indices: h(0), e(1), l(2), l(3), o(4). The substring "lo" starts at index 3 (l at 3, o at 4).Step 2: Understand indexOf return value
indexOfreturns the starting index of the substring, which is 3 here.Final Answer:
3 -> Option BQuick Check:
Substring "lo" starts at index 3 [OK]
- Counting from 1 instead of 0
- Returning index of second character in substring
- Assuming -1 means substring found
String s = "banana";
int index = s.indexOf('an');
System.out.println(index);Solution
Step 1: Check substring argument type in indexOf
TheindexOfmethod expects aStringargument, but single quotes denote achar.Step 2: Identify correct syntax for substring
Substring literals must be in double quotes, so 'an' should be "an".Final Answer:
Using single quotes for substring instead of double quotes -> Option AQuick Check:
Substring literals need double quotes [OK]
- Using single quotes for multi-character substrings
- Confusing char and String types
- Ignoring compiler error messages
text, which code snippet correctly finds all starting indices of substring "ab" in text using indexOf?Solution
Step 1: Understand how to find multiple occurrences with indexOf
UseindexOf(substring, fromIndex)to search from a moving start index to find all occurrences.Step 2: Analyze each option's logic
int index = 0; while ((index = text.indexOf("ab", index)) != -1) { System.out.print(index + " "); index++; } correctly updates index after each found occurrence to avoid infinite loop and find all positions. Others either do not update index properly or repeatedly search from start.Final Answer:
int index = 0; while ((index = text.indexOf("ab", index)) != -1) { System.out.print(index + " "); index++; } -> Option DQuick Check:
Use indexOf with start index and increment after each find [OK]
- Not updating start index causing infinite loop
- Always searching from start index 0
- Confusing indexOf usage with for-loop index
Ready to prove it?
Pass the test and this pattern moves unknown
