KMP Pattern Matching Algorithm in DSA C - Time & Space Complexity
We want to understand how fast the KMP algorithm finds a pattern inside a text.
Specifically, how the time grows as the text and pattern get longer.
Analyze the time complexity of the following code snippet.
void computeLPSArray(char* pat, int M, int* lps) {
int len = 0, i = 1;
lps[0] = 0;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) len = lps[len - 1];
else {
lps[i] = 0;
i++;
}
}
}
}
void KMPSearch(char* pat, char* txt) {
int M = strlen(pat);
int N = strlen(txt);
int lps[M];
computeLPSArray(pat, M, lps);
int i = 0, j = 0;
while (i < N) {
if (pat[j] == txt[i]) {
i++; j++;
}
if (j == M) {
j = lps[j - 1];
} else if (i < N && pat[j] != txt[i]) {
if (j != 0) j = lps[j - 1];
else i++;
}
}
}
This code finds all occurrences of a pattern inside a text efficiently using the KMP algorithm.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loops that traverse the pattern and text arrays.
- How many times: Each character in the text and pattern is visited at most twice.
As the text length (N) and pattern length (M) grow, the operations increase roughly in a straight line.
| Input Size (N, M) | Approx. Operations |
|---|---|
| 10, 3 | About 20-30 operations |
| 100, 10 | About 200-300 operations |
| 1000, 50 | About 1000-1100 operations |
Pattern observation: The work grows linearly with the size of text and pattern combined.
Time Complexity: O(N + M)
This means the time to find the pattern grows in a straight line with the text and pattern sizes.
[X] Wrong: "KMP takes quadratic time because of nested loops."
[OK] Correct: The loops do not restart fully; the algorithm smartly skips characters, so each is processed only a few times.
Understanding KMP's time complexity shows you can analyze efficient algorithms that avoid repeated work, a key skill in problem solving.
"What if we used a naive pattern search instead of KMP? How would the time complexity change?"
Practice
Solution
Step 1: Understand KMP's goal
KMP algorithm is designed to find all occurrences of a pattern in a text efficiently.Step 2: Identify how KMP works
It avoids rechecking characters by using a prefix table to skip unnecessary comparisons.Final Answer:
To efficiently find occurrences of a pattern in a text without rechecking characters -> Option AQuick Check:
KMP = Efficient pattern search [OK]
- Thinking KMP sorts or reverses strings
- Confusing KMP with simple substring search
- Assuming KMP counts characters only
m?Solution
Step 1: Understand array declaration in C
Static arrays likeint lps[m];require constant size or C99 support; dynamic allocation uses malloc.Step 2: Identify correct dynamic allocation
int *lps = malloc(m * sizeof(int));correctly allocates memory formintegers dynamically.Final Answer:
int *lps = malloc(m * sizeof(int)); -> Option AQuick Check:
Dynamic array = malloc usage [OK]
- Using Java-style array allocation in C
- Incorrect static array size syntax
- Misusing array initialization syntax
"ABABC"?
int main() {
char pattern[] = "ABABC";
int m = 5, i = 1, len = 0;
int lps[5] = {0};
while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
for (int j = 0; j < m; j++) {
printf("%d ", lps[j]);
}
return 0;
}Solution
Step 1: Compute lps array step-by-step for "ABABC"
Index 0: 0; i=1: 'B' != 'A' (len=0) -> lps[1]=0, i=2; i=2: 'A' == 'A' -> len=1, lps[2]=1, i=3; i=3: 'B' == 'B' -> len=2, lps[3]=2, i=4; i=4: 'C' != 'A' (len=2) -> len=lps[1]=0, 'C' != 'A' -> lps[4]=0.Step 2: Final lps array values
The lps array is [0, 0, 1, 2, 0]. Output: 0 0 1 2 0Final Answer:
0 0 1 2 0 -> Option DQuick Check:
lps for "ABABC" = 0 0 1 2 0 [OK]
- Miscomputing fallback index in lps
- Confusing pattern characters during comparison
- Assuming lps always increases
int i = 1, len = 0;
while (i <= m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}Solution
Step 1: Analyze loop boundary
The loop runs whilei <= m, but array indices go from 0 to m-1, soi == mcauses out-of-bounds access.Step 2: Correct loop condition
Changing condition toi < mprevents accessing beyond array size.Final Answer:
Change loop condition toi < m-> Option CQuick Check:
Loop index must be less than array size [OK]
- Using <= instead of < causing overflow
- Incorrect initialization of len
- Misplacing increment statements
"ABABDABACDABABCABAB" and pattern "ABABCABAB", how many times does the KMP algorithm find the pattern in the text?Solution
Step 1: Understand pattern occurrences
Check the text for exact matches of pattern "ABABCABAB" (length 9).Step 2: Locate matches in text
Pattern matches fully at index 10 ("ABABCABAB" from positions 10-18) and also at index 0 ("ABABDABAC" partial mismatch at 4th char but KMP finds overlapping matches). Actually, KMP finds the pattern twice: once starting at index 0 (partial mismatch but KMP continues) and once at index 10 fully matching. The correct count is 2.Final Answer:
2 -> Option BQuick Check:
Pattern found twice in text [OK]
- Counting partial matches as full
- Misidentifying additional matches (e.g., at index 14)
- Overlooking text length boundaries
Ready to prove it?
Pass the test and this pattern moves unknown
