Bird
Raised Fist0
DSA Pythonprogramming~20 mins

KMP Pattern Matching Algorithm in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
KMP Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of KMP prefix table computation
What is the output of the prefix table (lps array) after running the KMP preprocessing on the pattern "ABABCABAB"?
DSA Python
def compute_lps(pattern):
    lps = [0] * len(pattern)
    length = 0
    i = 1
    while i < len(pattern):
        if pattern[i] == pattern[length]:
            length += 1
            lps[i] = length
            i += 1
        else:
            if length != 0:
                length = lps[length - 1]
            else:
                lps[i] = 0
                i += 1
    return lps

pattern = "ABABCABAB"
lps = compute_lps(pattern)
print(lps)
A[0, 0, 1, 1, 0, 1, 2, 3, 4]
B[0, 1, 0, 1, 2, 3, 0, 1, 2]
C[0, 0, 1, 2, 3, 0, 1, 2, 3]
D[0, 0, 1, 2, 0, 1, 2, 3, 4]
Attempts:
2 left
💡 Hint
Remember the prefix table stores the length of the longest prefix which is also suffix for each substring ending at index i.
❓ Predict Output
intermediate
2:00remaining
KMP search output for pattern in text
What is the output of the following KMP search code when searching for pattern "ABAB" in text "ABABDABABABC"?
DSA Python
def kmp_search(text, pattern):
    lps = [0] * len(pattern)
    length = 0
    i = 1
    while i < len(pattern):
        if pattern[i] == pattern[length]:
            length += 1
            lps[i] = length
            i += 1
        else:
            if length != 0:
                length = lps[length - 1]
            else:
                lps[i] = 0
                i += 1
    
    i = 0
    j = 0
    result = []
    while i < len(text):
        if pattern[j] == text[i]:
            i += 1
            j += 1
        if j == len(pattern):
            result.append(i - j)
            j = lps[j - 1]
        elif i < len(text) and pattern[j] != text[i]:
            if j != 0:
                j = lps[j - 1]
            else:
                i += 1
    return result

text = "ABABDABABABC"
pattern = "ABAB"
print(kmp_search(text, pattern))
A[0, 5]
B[2, 5, 7]
C[0, 5, 7]
D[1, 3, 5]
Attempts:
2 left
💡 Hint
Check where the pattern fully matches in the text by comparing characters and using the prefix table.
🧠 Conceptual
advanced
1:30remaining
Understanding prefix table updates in KMP
During the computation of the prefix table (lps array) for the pattern "AAACAAAA", what is the value of the lps array at index 5?
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Remember lps[i] stores the length of the longest proper prefix which is also suffix for substring ending at i.
🔧 Debug
advanced
2:00remaining
Identify the error in KMP prefix table code
What error will the following code produce when computing the prefix table for pattern "ABCDABD"?
DSA Python
def compute_lps(pattern):
    lps = [0] * len(pattern)
    length = 0
    i = 1
    while i < len(pattern):
        if pattern[i] == pattern[length]:
            length += 1
            lps[i] = length
            i += 1
        else:
            if length != 0:
                length = lps[length - 1]
            else:
                lps[i] = 0
                i += 1
    return lps

pattern = "ABCDABD"
print(compute_lps(pattern))
AIndexError
BSyntaxError
CTypeError
D[0, 0, 0, 0, 1, 2, 0]
Attempts:
2 left
💡 Hint
Check the line where length is updated inside the else block.
🚀 Application
expert
2:30remaining
Number of pattern occurrences using KMP
Using KMP algorithm, how many times does the pattern "ABC" appear in the text "ABCABCABCABC"?
DSA Python
def kmp_search_count(text, pattern):
    lps = [0] * len(pattern)
    length = 0
    i = 1
    while i < len(pattern):
        if pattern[i] == pattern[length]:
            length += 1
            lps[i] = length
            i += 1
        else:
            if length != 0:
                length = lps[length - 1]
            else:
                lps[i] = 0
                i += 1
    
    i = 0
    j = 0
    count = 0
    while i < len(text):
        if pattern[j] == text[i]:
            i += 1
            j += 1
        if j == len(pattern):
            count += 1
            j = lps[j - 1]
        elif i < len(text) and pattern[j] != text[i]:
            if j != 0:
                j = lps[j - 1]
            else:
                i += 1
    return count

text = "ABCABCABCABC"
pattern = "ABC"
print(kmp_search_count(text, pattern))
A4
B5
C3
D6
Attempts:
2 left
💡 Hint
Count how many times the pattern fully matches in the text.

Practice

(1/5)
1. What is the main purpose of the KMP (Knuth-Morris-Pratt) pattern matching algorithm?
easy
A. To calculate the factorial of a number recursively
B. To sort an array of numbers in ascending order
C. To reverse a string in linear time
D. To find occurrences of a pattern string within a text efficiently

Solution

  1. Step 1: Understand the goal of KMP algorithm

    KMP is designed to search for a pattern inside a larger text efficiently without rechecking characters unnecessarily.
  2. Step 2: Compare with other options

    Sorting, reversing strings, and factorial calculations are unrelated to pattern searching.
  3. Final Answer:

    To find occurrences of a pattern string within a text efficiently -> Option D
  4. Quick Check:

    KMP = Pattern search [OK]
Hint: KMP is about fast pattern search in text [OK]
Common Mistakes:
  • Confusing KMP with sorting algorithms
  • Thinking KMP reverses strings
  • Assuming KMP calculates mathematical functions
2. Which of the following is the correct way to initialize the prefix table (lps array) in KMP algorithm in Python?
easy
A. lps = [0] * len(pattern)
B. lps = []
C. lps = [1] * len(pattern)
D. lps = None

Solution

  1. Step 1: Understand the prefix table initialization

    The prefix table (lps array) stores lengths of longest proper prefix which is also suffix for each prefix of the pattern. It must be initialized with zeros for all positions.
  2. Step 2: Check each option

    lps = [0] * len(pattern) correctly initializes lps with zeros for the entire pattern length. lps = [] is empty list, which is incomplete. lps = [1] * len(pattern) initializes with ones, which is incorrect. lps = None sets None, which is invalid.
  3. Final Answer:

    lps = [0] * len(pattern) -> Option A
  4. Quick Check:

    Prefix table starts with zeros [OK]
Hint: Prefix table starts with zeros for all pattern chars [OK]
Common Mistakes:
  • Initializing lps with ones instead of zeros
  • Leaving lps empty
  • Assigning None to lps
3. What will be the output of the following Python code snippet using KMP algorithm?
def compute_lps(pattern):
    lps = [0] * len(pattern)
    length = 0
    i = 1
    while i < len(pattern):
        if pattern[i] == pattern[length]:
            length += 1
            lps[i] = length
            i += 1
        else:
            if length != 0:
                length = lps[length - 1]
            else:
                lps[i] = 0
                i += 1
    return lps

pattern = "ABABC"
lps = compute_lps(pattern)
print(lps)
medium
A. [1, 0, 1, 0, 1]
B. [0, 0, 1, 2, 0]
C. [0, 1, 2, 3, 4]
D. [0, 0, 0, 0, 0]

Solution

  1. Step 1: Compute lps array for pattern "ABABC"

    Index 0: lps[0] = 0 (always zero)
    Index 1: pattern[1] = 'B' != pattern[0] = 'A', lps[1] = 0
    Index 2: pattern[2] = 'A' == pattern[0] = 'A', lps[2] = 1
    Index 3: pattern[3] = 'B' == pattern[1] = 'B', lps[3] = 2
    Index 4: pattern[4] = 'C' != pattern[2] = 'A', lps[4] = 0
  2. Step 2: Final lps array

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

    [0, 0, 1, 2, 0] -> Option B
  4. Quick Check:

    lps for "ABABC" = [0,0,1,2,0] [OK]
Hint: Match prefix and suffix lengths stepwise [OK]
Common Mistakes:
  • Confusing lps values with pattern indices
  • Assuming all zeros or all increasing values
  • Mixing up characters when comparing
4. Identify the error in the following KMP prefix table computation code snippet:
def compute_lps(pattern):
    lps = [0] * len(pattern)
    length = 0
    i = 0
    while i < len(pattern):
        if pattern[i] == pattern[length]:
            length += 1
            lps[i] = length
            i += 1
        else:
            if length != 0:
                length = lps[length - 1]
            else:
                lps[i] = 0
                i += 1
    return lps
medium
A. The loop should start with i = 1, not i = 0
B. The lps array should be initialized with ones
C. The length variable should start at 1
D. The function should return pattern instead of lps

Solution

  1. Step 1: Analyze the loop initialization

    In KMP prefix table computation, the first character's lps is always zero and we start comparing from the second character, so i should start at 1.
  2. Step 2: Check the given code

    The code starts with i = 0, which causes comparing pattern[0] with pattern[0] immediately, leading to incorrect lps values and infinite loop risk.
  3. Final Answer:

    The loop should start with i = 1, not i = 0 -> Option A
  4. Quick Check:

    Start i at 1 for prefix table [OK]
Hint: Start prefix loop from second character (i=1) [OK]
Common Mistakes:
  • Starting loop at zero causing wrong comparisons
  • Initializing lps with ones instead of zeros
  • Returning wrong variable
5. Given the text "ABABDABACDABABCABAB" and pattern "ABABCABAB", how many times does the pattern appear in the text using KMP algorithm?
hard
A. 2
B. 3
C. 1
D. 0

Solution

  1. Step 1: Understand the pattern and text

    The pattern "ABABCABAB" is searched inside the text "ABABDABACDABABCABAB" using KMP which efficiently finds all occurrences.
  2. Step 2: Identify pattern occurrences

    By scanning the text:
    - Occurrence starts at index 10 (substring "ABABCABAB")
    So pattern appears 1 time.
  3. Final Answer:

    1 -> Option C
  4. Quick Check:

    Pattern appears once in text [OK]
Hint: Count all pattern matches including overlaps [OK]
Common Mistakes:
  • Counting only first occurrence
  • Ignoring overlapping matches
  • Misreading pattern or text
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