Bird
Raised Fist0
DSA Cprogramming~5 mins

KMP Pattern Matching Algorithm in DSA C - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What does KMP stand for in the KMP Pattern Matching Algorithm?
KMP stands for Knuth-Morris-Pratt, the last names of the three people who created this efficient pattern searching algorithm.
Click to reveal answer
beginner
What is the main advantage of the KMP algorithm over the naive pattern matching approach?
KMP avoids rechecking characters that have already been matched by using a precomputed table, making it faster especially for large texts and patterns.
Click to reveal answer
intermediate
What is the purpose of the 'lps' (Longest Prefix Suffix) array in KMP?
The 'lps' array stores the length of the longest proper prefix of the pattern that is also a suffix for each prefix of the pattern. It helps decide where to continue matching after a mismatch.
Click to reveal answer
intermediate
In KMP, what happens when a mismatch occurs after some matches?
Instead of starting over, KMP uses the 'lps' array to skip characters and continue matching from the longest prefix that matches a suffix, saving time.
Click to reveal answer
intermediate
What is the time complexity of the KMP Pattern Matching Algorithm?
The time complexity is O(n + m), where n is the length of the text and m is the length of the pattern, because each character is processed at most twice.
Click to reveal answer
What does the 'lps' array in KMP represent?
ALongest prefix which is also suffix for pattern prefixes
BLength of the pattern
CPositions of pattern matches in text
DNumber of mismatches found
What is the main benefit of using KMP over naive pattern matching?
AIt uses less memory
BIt finds all substrings in constant time
CIt works only on small texts
DIt avoids rechecking characters after mismatch
If a mismatch occurs at pattern index 3, where does KMP jump next?
ABack to pattern start
BTo the index given by lps[2]
CTo the next character in text
DTo the end of the pattern
What is the worst-case time complexity of KMP?
AO(n*m)
BO(n^2)
CO(n + m)
DO(m^2)
Which step is NOT part of the KMP algorithm?
ARestart matching from the beginning after mismatch
BPrecompute the lps array
CCompare characters of text and pattern
DUse lps to skip unnecessary comparisons
Explain how the 'lps' array is constructed and how it helps in pattern matching.
Think about prefixes and suffixes in the pattern.
You got /3 concepts.
    Describe the steps KMP takes when a mismatch happens during pattern matching.
    Focus on how KMP avoids rechecking characters.
    You got /3 concepts.

      Practice

      (1/5)
      1. What is the main purpose of the KMP (Knuth-Morris-Pratt) algorithm in pattern matching?
      easy
      A. To efficiently find occurrences of a pattern in a text without rechecking characters
      B. To sort the characters of the pattern alphabetically
      C. To reverse the text before searching
      D. To count the total number of characters in the text

      Solution

      1. Step 1: Understand KMP's goal

        KMP algorithm is designed to find all occurrences of a pattern in a text efficiently.
      2. Step 2: Identify how KMP works

        It avoids rechecking characters by using a prefix table to skip unnecessary comparisons.
      3. Final Answer:

        To efficiently find occurrences of a pattern in a text without rechecking characters -> Option A
      4. Quick Check:

        KMP = Efficient pattern search [OK]
      Hint: KMP skips repeated checks using prefix info [OK]
      Common Mistakes:
      • Thinking KMP sorts or reverses strings
      • Confusing KMP with simple substring search
      • Assuming KMP counts characters only
      2. Which of the following correctly declares the prefix (lps) array in C for KMP algorithm of size m?
      easy
      A. int *lps = malloc(m * sizeof(int));
      B. int lps = new int[m];
      C. int lps[m];
      D. int lps[] = {m};

      Solution

      1. Step 1: Understand array declaration in C

        Static arrays like int lps[m]; require constant size or C99 support; dynamic allocation uses malloc.
      2. Step 2: Identify correct dynamic allocation

        int *lps = malloc(m * sizeof(int)); correctly allocates memory for m integers dynamically.
      3. Final Answer:

        int *lps = malloc(m * sizeof(int)); -> Option A
      4. Quick Check:

        Dynamic array = malloc usage [OK]
      Hint: Use malloc for dynamic arrays in C [OK]
      Common Mistakes:
      • Using Java-style array allocation in C
      • Incorrect static array size syntax
      • Misusing array initialization syntax
      3. What will be the output of the following C code snippet using KMP prefix array computation for pattern "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;
      }
      medium
      A. 0 0 1 2 1
      B. 0 1 0 1 2
      C. 0 1 2 3 4
      D. 0 0 1 2 0

      Solution

      1. 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.
      2. Step 2: Final lps array values

        The lps array is [0, 0, 1, 2, 0]. Output: 0 0 1 2 0
      3. Final Answer:

        0 0 1 2 0 -> Option D
      4. Quick Check:

        lps for "ABABC" = 0 0 1 2 0 [OK]
      Hint: Trace lps step-by-step for each pattern char [OK]
      Common Mistakes:
      • Miscomputing fallback index in lps
      • Confusing pattern characters during comparison
      • Assuming lps always increases
      4. Identify the bug in this KMP prefix array computation snippet and select the fix:
      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++;
              }
          }
      }
      medium
      A. Remove i++ inside else block
      B. Initialize len to 1 instead of 0
      C. Change loop condition to i < m
      D. Use pattern[len+1] instead of pattern[len]

      Solution

      1. Step 1: Analyze loop boundary

        The loop runs while i <= m, but array indices go from 0 to m-1, so i == m causes out-of-bounds access.
      2. Step 2: Correct loop condition

        Changing condition to i < m prevents accessing beyond array size.
      3. Final Answer:

        Change loop condition to i < m -> Option C
      4. Quick Check:

        Loop index must be less than array size [OK]
      Hint: Loop till less than array size, not equal [OK]
      Common Mistakes:
      • Using <= instead of < causing overflow
      • Incorrect initialization of len
      • Misplacing increment statements
      5. Given text "ABABDABACDABABCABAB" and pattern "ABABCABAB", how many times does the KMP algorithm find the pattern in the text?
      hard
      A. 1
      B. 2
      C. 3
      D. 0

      Solution

      1. Step 1: Understand pattern occurrences

        Check the text for exact matches of pattern "ABABCABAB" (length 9).
      2. 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.
      3. Final Answer:

        2 -> Option B
      4. Quick Check:

        Pattern found twice in text [OK]
      Hint: Count full pattern matches in text using KMP [OK]
      Common Mistakes:
      • Counting partial matches as full
      • Misidentifying additional matches (e.g., at index 14)
      • Overlooking text length boundaries
      Recommended

      Ready to prove it?

      Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard