String Algorithms MCQs for NSCT
String algorithms find a pattern P of length m inside a text T of length n, and the three you must know are the naive matcher, Knuth-Morris-Pratt (KMP) and Rabin-Karp. They form topic 11 of the Data Structures & Algorithms area, which carries 10% of the NSCT according to HEC's Areas of Competencies. In 2026 candidates averaged 40.2% accuracy in this area, per the HEC NSCT report and APP.
Rabin-Karp relies on hashing, so revise Hashing alongside this page.
Pattern matching and the naive matcher
A shift s is valid when T[s..s + m - 1] equals P. The naive matcher tries every shift from 0 to n - m, which is n - m + 1 shifts, and compares up to m characters at each.
Searching AAAAAA for AAB tests 4 shifts. Each matches two As and then fails on B, so it makes 4 x 3 = 12 comparisons. In the worst case the cost is O((n - m + 1) m), which is O(nm).
Exam angle: count shifts as n - m + 1, not n, and remember that overlapping matches count. The pattern aba occurs 3 times in abababa, at shifts 0, 2 and 4.
KMP
KMP avoids rechecking text it has already read. It first builds the prefix function (also called the LPS or failure array): pi[q] is the length of the longest proper prefix of P[0..q] that is also a suffix of it.
| Pattern | Prefix function |
|---|---|
| AAAA | [0, 1, 2, 3] |
| ABABCABAB | [0, 0, 1, 2, 0, 1, 2, 3, 4] |
| ABCDABD | [0, 0, 0, 0, 1, 2, 0] |
| AABAACAABAA | [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5] |
On a mismatch after q matched characters, KMP sets q = pi[q - 1] and keeps its place in the text. After matching ABAB of ABABCABAB and failing on C, it carries on with AB (q = 2) already matched. After a full match it sets q = pi[m - 1], which finds overlapping occurrences.
Preprocessing is O(m) and matching is O(n), so the total is O(n + m) in the worst case. The O(m) bound is amortised: the matched length rises by at most 1 per step, so it cannot fall more than m times in total.
Exam angle: compute the prefix function by hand, and on a mismatch fall back through pi rather than resetting to 0.
Rabin-Karp
Rabin-Karp treats each length-m window as a number in base d and compares hashes mod q. With d = 10 and q = 13, the pattern 31415 hashes to 31415 mod 13 = 7.
The rolling hash updates each window in O(1):
t_next = (d (t - T[s] h) + T[s + m]) mod q, where h = d^(m - 1) mod q.
With h = 9, the window 314 (hash 2) slides to 141: (10(2 - 27) + 1) mod 13 = 11, and 141 mod 13 is indeed 11. Languages such as C and Java can return a negative remainder, so add q there.
A hash match that fails the character check is a spurious hit. In the text 2359023141526739921, the window 67399 at shift 12 also hashes to 7, so it is spurious, while shift 6 is the real match.
Expected time is O(n + m), but the worst case is O((n - m + 1) m), for example when every window really matches.
| Algorithm | Preprocessing | Matching (worst) | Key idea |
|---|---|---|---|
| Naive | none | O((n - m + 1) m) | Try every shift |
| KMP | O(m) | O(n) | Prefix function; text pointer never moves back |
| Rabin-Karp | O(m) | O((n - m + 1) m), expected O(n + m) | Rolling hash, then verify |
| Boyer-Moore | O(m + alphabet) | O(nm) in the basic version | Compare right to left and skip |
Exam angle: Rabin-Karp extends naturally to many patterns of the same length, since each window's hash can be looked up in a set.
Common traps
- Counting the whole string as its own border; prefix-function values must come from proper prefixes, so pi[0] is always 0.
- Resetting q to 0 on a KMP mismatch instead of following pi[q - 1].
- Assuming a hash match is a real match; Rabin-Karp must verify characters.
- Picking a modulus such as q = d = 10, which hashes on the last digit only and causes constant collisions.
- Looping
for s in range(n - m), which misses the last shift; there are n - m + 1 shifts. - Using a library count function when overlapping matches are needed; Python's str.count is non-overlapping.
Worked examples
1. Understanding. Why is the first prefix-function value always 0? Answer: a single character has no non-empty proper prefix, so its longest border has length 0.
2. Application. What is the prefix function of AABAAB? Answer: [0, 1, 0, 1, 2, 3]. AA gives 1, B breaks it (0), and A, AA, AAB rebuild 1, 2, 3, because AAB is both a prefix and a suffix of AABAAB.
3. Analysis. Rabin-Karp searches 1529 for 29 with d = 10 and q = 7. Which shifts are valid and which are spurious? Answer: shift 2 is valid and shift 0 is spurious. 29 mod 7 = 1. The windows 15, 52 and 29 hash to 1, 3 and 1, and 15 fails the character check.
Practise
The quiz below has 100 String Algorithms questions, filterable by tier and difficulty.
Practise: 100 questions
FAQs
Is KMP always faster than the naive matcher?
In the worst case, yes: KMP is O(n + m) while naive is O(nm). On ordinary text with short patterns, though, the naive matcher usually fails after one or two characters, so it runs in close to linear time and has less overhead. KMP matters most for repetitive text such as DNA or long runs of one character.
Why does Rabin-Karp use a prime modulus?
A large prime spreads window hashes over many values, so unrelated windows rarely collide and spurious hits stay rare. It also avoids patterns that would interact with the base d. Collisions are still possible, which is why every hash match is checked character by character.
What is the difference between the prefix function and the failure function?
They are the same idea. CLRS calls it the prefix function pi, many tutorials call it the LPS (longest proper prefix that is also a suffix) array, and some books call it the failure function. Some versions shift the array by one position or start it at -1, so check the convention in the question.
Next step
Continue with Complexity & Optimization MCQs, go back to the DSA MCQ hub, or test yourself across every area in an NSCT mock test.