WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Data Structures & Algorithms · Intermediate · question 39 of 100

Describe the KMP (Knuth-Morris-Pratt) algorithm and its use in pattern searching within a string.?

📕 Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers — PDF + EPUB for $5

The Knuth-Morris-Pratt (KMP) algorithm is a string searching algorithm that is used to find occurrences of a pattern within a larger string. The algorithm achieves this by preprocessing the pattern to construct a table of partial matches, which is then used to avoid unnecessary comparisons when searching for the pattern within the larger string.

The KMP algorithm works as follows:

Construct a table of partial matches for the pattern.

Use the lps table to search for the pattern within the larger string.

The KMP algorithm is particularly useful when searching for a pattern within a large string, as it can avoid unnecessary comparisons by using the lps table to skip over parts of the larger string that are guaranteed not to match the pattern. This makes the algorithm more efficient than other naive string searching algorithms, such as the brute-force method of comparing each possible substring of the larger string with the pattern.

Here is an example implementation of the KMP algorithm in Java:

public static List<Integer> kmp(String text, String pattern) {
    List<Integer> indices = new ArrayList<Integer>();
    int n = text.length();
    int m = pattern.length();
    int[] lps = computeLPS(pattern);
    int i = 0, j = 0;
    while (i < n) {
        if (text.charAt(i) == pattern.charAt(j)) {
            i++;
            j++;
            if (j == m) {
                indices.add(i - j);
                j = lps[j - 1];
            }
        } else if (j > 0) {
            j = lps[j - 1];
        } else {
            i++;
        }
    }
    return indices;
}

private static int[] computeLPS(String pattern) {
    int m = pattern.length();
    int[] lps = new int[m];
    int i = 1, j = 0;
    while (i < m) {
        if (pattern.charAt(i) == pattern.charAt(j)) {
            j++;
            lps[i] = j;
            i++;
        } else if (j > 0) {
            j = lps[j - 1];
        } else {
            lps[i] = 0;
            i++;
        }
    }
    return lps;
}

In this implementation, the kmp method takes as input a larger string text and a pattern string pattern, and

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Data Structures & Algorithms interview — then scores it.
📞 Practice Data Structures & Algorithms — free 15 min
📕 Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers — PDF + EPUB for $5

All 100 Data Structures & Algorithms questions · All topics