Bird
Raised Fist0
DSA Cprogramming~10 mins

KMP Pattern Matching Algorithm in DSA C - Interactive Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the length variable in the prefix function.

DSA C
int computeLPSArray(char* pat, int M, int* lps) {
    int len = [1];
    int i = 1;
    lps[0] = 0;
    while (i < M) {
        if (pat[i] == pat[len]) {
            len++;
            lps[i] = len;
            i++;
        } else {
            if (len != 0) {
                len = lps[len - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A1
B0
CM
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing len to 1 causes incorrect prefix length calculation.
Using -1 or M leads to out-of-bound errors.
2fill in blank
medium

Complete the code to reset the index i in the KMP search function after a mismatch.

DSA C
void KMPSearch(char* pat, char* txt) {
    int M = strlen(pat);
    int N = strlen(txt);
    int lps[M];
    computeLPSArray(pat, M, lps);
    int i = 0; // index for txt[]
    int j = 0; // index for pat[]
    while (i < N) {
        if (pat[j] == txt[i]) {
            j++;
            i++;
        }
        if (j == M) {
            printf("Found pattern at index %d\n", i - j);
            j = lps[[1]];
        } else if (i < N && pat[j] != txt[i]) {
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
}
Drag options to blanks, or click blank then click option'
AM - 1
Bi
Cj - 1
Dlps[j - 1]
Attempts:
3 left
💡 Hint
Common Mistakes
Resetting j to i or M-1 causes incorrect search continuation.
Using lps[j] instead of lps[j-1] leads to wrong index.
3fill in blank
hard

Fix the error in the prefix function loop condition to avoid infinite loop.

DSA C
int computeLPSArray(char* pat, int M, int* lps) {
    int len = 0;
    int i = 1;
    lps[0] = 0;
    while ([1]) {
        if (pat[i] == pat[len]) {
            len++;
            lps[i] = len;
            i++;
        } else {
            if (len != 0) {
                len = lps[len - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Ai < M
Blen < M
Ci <= M
Dlen <= M
Attempts:
3 left
💡 Hint
Common Mistakes
Using i <= M causes out-of-bound access.
Using len < M is incorrect because len is prefix length, not index.
4fill in blank
hard

Fill both blanks to correctly update indices after mismatch in KMPSearch.

DSA C
void KMPSearch(char* pat, char* txt) {
    int M = strlen(pat);
    int N = strlen(txt);
    int lps[M];
    computeLPSArray(pat, M, lps);
    int i = 0;
    int j = 0;
    while (i < N) {
        if (pat[j] == txt[i]) {
            i++;
            j++;
        } else {
            if (j != 0) {
                j = [1];
            } else {
                i = [2];
            }
        }
    }
}
Drag options to blanks, or click blank then click option'
Alps[j - 1]
Bi + 1
Cj - 1
Di - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Setting j to j-1 causes wrong prefix reuse.
Incrementing i incorrectly leads to skipping characters.
5fill in blank
hard

Fill all three blanks to complete the prefix function initialization and loop.

DSA C
int computeLPSArray(char* pat, int M, int* lps) {
    int len = [1];
    int i = [2];
    lps[0] = 0;
    while (i [3] M) {
        if (pat[i] == pat[len]) {
            len++;
            lps[i] = len;
            i++;
        } else {
            if (len != 0) {
                len = lps[len - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A0
B1
C<
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Starting i at 0 causes infinite loop.
Using '<=' in loop condition causes out-of-bound errors.

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