Challenge - 5 Problems
KMP Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of KMP prefix table computation
What is the output array (prefix table) computed by the KMP algorithm for the pattern "ABABAC"?
DSA C
int pattern[] = { 'A', 'B', 'A', 'B', 'A', 'C' }; int prefix[] = {0, 0, 0, 0, 0, 0}; // KMP prefix table computation logic here // Output prefix array after computation
Attempts:
2 left
💡 Hint
Remember the prefix table stores the length of the longest proper prefix which is also a suffix for each prefix of the pattern.
✗ Incorrect
The prefix table for "ABABAC" is computed by comparing characters and updating the longest prefix-suffix lengths. The correct prefix table is [0, 0, 1, 2, 3, 0].
❓ Predict Output
intermediate2:00remaining
KMP search output for given text and pattern
What is the output (starting indices) of the KMP search for pattern "ABABC" in text "ABABABCABABC"?
DSA C
char text[] = "ABABABCABABC"; char pattern[] = "ABABC"; // KMP search logic // Print all starting indices where pattern is found
Attempts:
2 left
💡 Hint
Check carefully where the pattern fully matches in the text.
✗ Incorrect
The pattern "ABABC" appears starting at indices 2 and 7 in the text "ABABABCABABC".
🔧 Debug
advanced2:00remaining
Identify the bug in prefix table computation
Given the following prefix table computation code snippet, what error will it cause when run with pattern "AAAAB"?
DSA C
int computePrefix(char* pattern, int length, int* prefix) { int j = 0; prefix[0] = 0; for (int i = 1; i < length; i++) { while (j > 0 && pattern[i] != pattern[j]) { j = prefix[j - 1]; } if (pattern[i] == pattern[j]) { j++; } prefix[i] = j; } return 0; }
Attempts:
2 left
💡 Hint
Check the line where j is updated inside the while loop.
✗ Incorrect
For pattern "AAAAB", after prefix[0..3] = [0,1,2,3], at i=4 ('B' != pattern[3]='A'), the while loop sets j = prefix[3] = 3 repeatedly, causing an infinite loop.
🧠 Conceptual
advanced1:00remaining
Time complexity of KMP algorithm
What is the time complexity of the KMP pattern matching algorithm for a text of length n and pattern of length m?
Attempts:
2 left
💡 Hint
KMP avoids rechecking characters by using the prefix table.
✗ Incorrect
KMP preprocesses the pattern in O(m) and searches the text in O(n), so total time is O(n + m).
🚀 Application
expert2:00remaining
Using KMP to find the longest prefix which is also suffix
Given a string s, how can the KMP prefix table be used to find the length of the longest prefix of s which is also a suffix (excluding the whole string)?
Attempts:
2 left
💡 Hint
The prefix table stores lengths of longest prefix-suffix for each prefix of the string.
✗ Incorrect
The last value in the prefix table corresponds to the longest prefix which is also suffix for the entire string (excluding the whole string itself).
