Substring Search Patterns in DSA C# - Time & Space Complexity
When searching for a smaller string inside a bigger one, it is important to know how long it takes as the strings grow.
We want to understand how the search time changes when the text or pattern gets longer.
Analyze the time complexity of the following code snippet.
// Naive substring search
public static int NaiveSearch(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[i + j] != pattern[j])
break;
}
if (j == m) return i; // pattern found
}
return -1; // not found
}
This code tries to find the first place where the pattern appears in the text by checking each position one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two nested loops: outer loop moves through text positions, inner loop compares characters of pattern.
- How many times: Outer loop runs about (n - m + 1) times, inner loop runs up to m times for each outer iteration.
As the text and pattern get longer, the number of character comparisons grows quickly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (text), 3 (pattern) | Up to 24 comparisons |
| 100 (text), 10 (pattern) | Up to 910 comparisons |
| 1000 (text), 50 (pattern) | Up to 47,550 comparisons |
Pattern observation: The work grows roughly by multiplying text length by 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 to the text length only."
[OK] Correct: Because for each position in the text, we may need to check every character of the pattern, so pattern length matters too.
Understanding how substring search time grows helps you explain and improve search algorithms in real projects.
"What if we used a more advanced algorithm like KMP? How would the time complexity change?"
Practice
Solution
Step 1: Understand substring search goal
Substring search algorithms check if a smaller string (pattern) appears inside a bigger string (text).Step 2: Compare with other options
Sorting, reversing, and counting characters are different string operations unrelated to substring search.Final Answer:
To find if a smaller string exists inside a larger string -> Option BQuick Check:
Substring search = find smaller string inside bigger string [OK]
- Confusing substring search with sorting or reversing strings
- Thinking substring search counts characters
- Assuming substring search changes the string
text contains substring pattern in C#?Solution
Step 1: Recall C# string method for substring check
The correct method to check if a string contains another isContains, called on the string instance.Step 2: Validate method usage
text.Contains(pattern)returns a boolean indicating ifpatternis insidetext. Other options are invalid or do not exist.Final Answer:
bool found = text.Contains(pattern); -> Option CQuick Check:
UseContainsmethod on string to check substring [OK]
text.Contains(pattern) to check substring presence [OK]- Using non-existent methods like Find or Index
- Calling Contains as a standalone function
- Confusing method names or parameters
string text = "hello world"; string pattern = "wor"; bool result = text.Contains(pattern); Console.WriteLine(result);
Solution
Step 1: Check if pattern "wor" is in text "hello world"
The substring "wor" appears starting at index 6 in "hello world".Step 2: Evaluate
Since the substring exists,Containsmethod resulttext.Contains(pattern)returnstrue, soresultis true.Final Answer:
True -> Option AQuick Check:
Substring "wor" in "hello world" = true [OK]
- Assuming Contains returns index instead of bool
- Thinking substring is not present due to partial match
- Confusing output with string printing
string text = "data structures";
string pattern = "struct";
int index = text.IndexOf(pattern);
if (index)
{
Console.WriteLine("Found at " + index);
}Solution
Step 1: Understand IndexOf return value
IndexOfreturns the starting index of the substring or -1 if not found.Step 2: Check if condition usage
The if conditionif (index)is invalid becauseindexis an int, not a boolean. It should checkindex >= 0to confirm substring found.Final Answer:
The if condition should check if index >= 0 -> Option AQuick Check:
Checkindex >= 0to confirm substring found [OK]
- Using int directly as boolean in if condition
- Assuming IndexOf returns boolean
- Ignoring negative index meaning not found
words and a pattern string p, which approach best finds all words containing p as a substring efficiently in C#?Solution
Step 1: Understand substring search in multiple strings
To find all words containingp, we must check each word individually for the substring.Step 2: Evaluate options for efficiency and correctness
Using a loop withword.Contains(p)is straightforward and efficient. Sorting and binary search do not help substring search.words.IndexOf(p)is invalid becausewordsis a list of strings, not a string. Replacing substrings does not find matches.Final Answer:
Use a loop to check each word withword.Contains(p)and collect matches -> Option DQuick Check:
Loop + Contains per word finds all substring matches [OK]
- Trying binary search for substring matching
- Using IndexOf on list instead of strings
- Replacing substrings instead of checking presence
Ready to prove it?
Pass the test and this pattern moves unknown
