Substring Search Patterns in DSA C - Time & Space Complexity
We want to understand how long it takes to find a smaller string inside a bigger string.
How does the time needed grow when the strings get longer?
Analyze the time complexity of the following code snippet.
int substring_search(const char *text, const char *pattern) {
int n = strlen(text);
int m = strlen(pattern);
for (int i = 0; i <= n - m; i++) {
int j = 0;
while (j < m && text[i + j] == pattern[j]) {
j++;
}
if (j == m) {
return i; // pattern found at index i
}
}
return -1; // pattern not found
}
This code looks for the first place where the pattern appears inside the text.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer loop runs from start to end of text minus pattern length.
- Nested operation: The inner while loop compares characters of pattern and text one by one.
- 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 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: The work grows roughly by the product of text length and pattern length.
Time Complexity: O(n * m)
This means the time needed grows roughly by multiplying the length of the text and the pattern.
[X] Wrong: "The search always takes time proportional to the text length only."
[OK] Correct: Because each position in the text may require checking many characters of the pattern, so pattern length matters too.
Understanding how substring search time grows helps you explain and improve searching methods in real problems.
"What if we used a smarter algorithm like KMP that avoids re-checking characters? 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 definition
Only To find if a smaller string exists inside a larger string describes finding a smaller string inside a larger one, which matches substring search.Final Answer:
To find if a smaller string exists inside a larger string -> Option AQuick 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
pattern is a substring of string text in C?Solution
Step 1: Recall C substring search function
In C,strstr()returns a pointer to the first occurrence ofpatternintext, or NULL if not found.Step 2: Check each option's syntax
if (strstr(text, pattern) != NULL) { /* found */ } usesstrstrcorrectly with NULL check. Options A, B, C use syntax from other languages or invalid in C.Final Answer:
if (strstr(text, pattern) != NULL) { /* found */ } -> Option DQuick Check:
C substring search uses strstr() [OK]
- Using methods from other languages like contains() or find()
- Not checking if strstr() returns NULL
- Confusing order of arguments in strstr()
char text[] = "hello world";
char *pos = strstr(text, "wor");
if (pos != NULL) {
printf("%ld", pos - text);
} else {
printf("-1");
}Solution
Step 1: Understand strstr() return value
strstr(text, "wor")returns pointer to first occurrence of "wor" in "hello world", which starts at index 6.Step 2: Calculate pointer difference
Subtractingtextpointer fromposgives index 6, which is printed.Final Answer:
6 -> Option AQuick Check:
Substring "wor" starts at index 6 [OK]
- Printing pointer value instead of index difference
- Assuming substring starts at 0 or 3 incorrectly
- Not checking if strstr() returns NULL before subtracting
char *find_substring(char *text, char *pattern) {
for (int i = 0; i <= strlen(text); i++) {
if (strncmp(&text[i], pattern, strlen(pattern)) == 0) {
return &text[i];
}
}
return NULL;
}Solution
Step 1: Analyze loop boundary
The loop runs from 0 to strlen(text), but comparing substrings beyond text length minus pattern length causes overflow.Step 2: Correct loop condition
Loop should run untili <= strlen(text) - strlen(pattern)to safely compare substrings of pattern length.Final Answer:
The loop condition should be 'i < strlen(text) - strlen(pattern) + 1' to avoid overflow -> Option CQuick Check:
Loop boundary must prevent substring overflow [OK]
- Looping beyond valid substring start positions
- Using strcmp instead of strncmp for partial comparison
- Ignoring return type correctness
pat in string txt using C. Which approach correctly finds all start indices of pat in txt?Solution
Step 1: Understand strstr() usage for multiple occurrences
strstr() returns pointer to first occurrence. To find all, repeatedly call strstr() starting after last found position.Step 2: Evaluate options
Use a loop with strstr() starting from last found position + 1 until strstr() returns NULL correctly describes looping with strstr() advancing pointer. Use strstr() once and return the first found position only finds only first occurrence. Options C and D do not find all occurrences.Final Answer:
Use a loop with strstr() starting from last found position + 1 until strstr() returns NULL -> Option BQuick Check:
Loop with strstr() to find all occurrences [OK]
- Using strstr() only once for all matches
- Using strcmp() which compares whole strings only
- Relying on length checks without searching
Ready to prove it?
Pass the test and this pattern moves unknown
