String Algorithms MCQs for NSCT

By the NSCT Exam Editorial Team · Updated 2026-11-24 · Facts checked against official sources on 2026-11-24

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

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

Interactive quiz loading. The first 10 questions are shown below.

  1. What is the worst-case running time of the naive (brute-force) string matcher for a text of length n and a pattern of length m?

    1. O(n + m)
    2. O(n log m)
    3. O((n - m + 1) m)
    4. O(m^2)
    Show answer

    Answer: C. O((n - m + 1) m)

    The naive matcher tries every shift s from 0 to n - m and may compare up to m characters at each one, so the worst case is O((n - m + 1) m), which is O(nm) when m is small relative to n. O(n + m) is the bound for KMP.

  2. What is the total running time of the Knuth-Morris-Pratt (KMP) algorithm, including preprocessing, for text length n and pattern length m?

    1. O(nm)
    2. O(n log n)
    3. O(m log n)
    4. O(n + m)
    Show answer

    Answer: D. O(n + m)

    KMP builds the prefix function in O(m) and then scans the text in O(n), because the text pointer never moves backwards. The total is O(n + m) in the worst case, unlike the naive matcher's O(nm).

  3. In KMP, what does the prefix-function value pi[q] (also called the LPS value) store for position q of the pattern?

    1. The number of times P[q] appears earlier in the pattern
    2. The index of the next occurrence of P[q] in the text
    3. The length of the longest palindrome ending at position q
    4. The length of the longest proper prefix of P[0..q] that is also a suffix of P[0..q]
    Show answer

    Answer: D. The length of the longest proper prefix of P[0..q] that is also a suffix of P[0..q]

    pi[q] is the length of the longest prefix of P[0..q] that is also a suffix of it, excluding the whole string itself (that is what proper means). On a mismatch KMP falls back to this length instead of restarting from zero.

  4. In the Rabin-Karp algorithm, what is a spurious hit?

    1. A window whose hash equals the pattern's hash although the characters differ
    2. A window that matches the pattern but has a different hash
    3. A match found by comparing characters from right to left
    4. A pattern occurrence that overlaps with a previous occurrence
    Show answer

    Answer: A. A window whose hash equals the pattern's hash although the characters differ

    Rabin-Karp compares hash values modulo q first. Different strings can share a hash, so every hash match must be verified character by character. A hash match that fails verification is a spurious hit. A real match can never have a different hash, because equal strings hash equally.

  5. What are the expected and worst-case running times of Rabin-Karp for text length n and pattern length m (with few valid matches expected)?

    1. Expected O(nm), worst case O(n + m)
    2. O(n + m) in both the expected and the worst case
    3. Expected O(n + m), worst case O((n - m + 1) m)
    4. Expected O(n log m), worst case O(n^2)
    Show answer

    Answer: C. Expected O(n + m), worst case O((n - m + 1) m)

    With a good modulus, spurious hits are rare, so the scan costs O(n + m) on average. In the worst case every window's hash matches (for example many collisions or text made of one repeated character) and each needs an O(m) check, giving O((n - m + 1) m), the same as naive.

  6. Why does Rabin-Karp use a rolling hash?

    1. It removes all spurious hits, so no verification is needed
    2. The next window's hash is computed from the previous one in O(1) instead of rehashing m characters
    3. It lets the algorithm compare the pattern from right to left
    4. It sorts the windows so that binary search can be used
    Show answer

    Answer: B. The next window's hash is computed from the previous one in O(1) instead of rehashing m characters

    Sliding the window by one drops the leading character and adds a new trailing one. With t_new = (d(t - T[s] h) + T[s + m]) mod q, the update is constant time, so all n - m + 1 window hashes cost O(n) in total. Collisions can still happen, so verification remains.

  7. Which property of KMP makes it suitable for matching a stream that can be read only once?

    1. It compares characters from the end of the pattern
    2. It hashes the whole text before matching
    3. The text pointer never moves backwards; only the pattern position falls back
    4. It sorts the text characters before scanning
    Show answer

    Answer: C. The text pointer never moves backwards; only the pattern position falls back

    On a mismatch KMP keeps its place in the text and only changes q, the number of pattern characters matched, using the prefix function. Each text character is consumed once, so there is no need to buffer or re-read the input. The naive matcher must go back to s + 1.

  8. You must find any of 50 different patterns, all of length 8, in one long text. Which algorithm in this list extends most naturally to checking all of them in a single pass?

    1. KMP, because one prefix function covers all 50 patterns
    2. The naive matcher, because it needs no preprocessing
    3. Rabin-Karp, by looking up each window's hash in a set of the 50 pattern hashes
    4. Binary search on the text
    Show answer

    Answer: C. Rabin-Karp, by looking up each window's hash in a set of the 50 pattern hashes

    Rabin-Karp computes one hash per window, and a hash set holds the 50 pattern hashes, so each window costs O(1) expected plus verification on hits. KMP's prefix function is built for one pattern; covering many patterns in one pass needs an automaton such as Aho-Corasick. The text is not sorted, so binary search does not apply.

  9. What is characteristic of the Boyer-Moore string-matching algorithm?

    1. It compares the pattern from right to left and can skip ahead using bad-character and good-suffix rules
    2. It hashes each text window and compares the hash values
    3. It never skips any text position, giving exactly n comparisons
    4. It builds a prefix function and scans left to right
    Show answer

    Answer: A. It compares the pattern from right to left and can skip ahead using bad-character and good-suffix rules

    Boyer-Moore aligns the pattern and compares from its last character backwards. A mismatch on a text character that does not occur in the pattern lets it jump the whole pattern length, so on large alphabets it often inspects far fewer than n characters. Hashing is Rabin-Karp, and the prefix function is KMP.

  10. In string matching, what is a valid shift s for text T and pattern P of length m?

    1. Any shift between 0 and m - 1
    2. A shift where T[s] equals P[0], whatever follows
    3. A shift where T[s..s + m - 1] equals P
    4. The number of characters the pattern moves after a mismatch
    Show answer

    Answer: C. A shift where T[s..s + m - 1] equals P

    Pattern matching asks for every shift s at which P occurs in T, meaning all m characters agree. Matching only the first character is the start of a check, not a valid shift. Shifts run from 0 to n - m.

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.