Skip to content

KMP Algorithm

WIP

KMP Failure Function

Time Complexity

Time complexity Worst case Best case
Failure Function $\Omicron(m)$ $\Omicron(m)$
Find Function $\Omicron(n)$ $\Omicron(n)$
Overall $\Omicron(n)$ $\Omicron(n)$

Implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <bits/stdc++.h> 
using namespace std;

vector<int> get_failure(string s) {
    int n = s.size();
    vector<int> res(n);
    res[0] = 0;
    int k = 0;
    for (int i = 1; i < n; i++) {
        while (k > 0 && s[k] != s[i])
            k = res[k - 1];
        if (s[k] == s[i])
            k++;
        res[i] = k;
    }
    return res;
}

vector<pair<int, int>> find(string text, string pattern) {
    vector<pair<int, int>> res; 
    vector<int> failure = get_failure(pattern);
    int n = text.size();
    int m = failure.size();
    int i = 0, j = 0;
    while (i < n) {
        if (text[i] == pattern[j])
            i++,j++;
        if (j == m) {
            res.push_back({i - j, i - 1});
            j = failure[j - 1];
        }
        while (j > 0 && pattern[j] != text[i])
            j = failure[j - 1];
        if (j == 0)
            i++;
    }
    return res;
}

int main() {
    string pattern = "ABABAC";
    string text = "ABABACABAABAABABABABAC";
    vector<pair<int, int>> found = find(text, pattern);
    for (auto x: found) {
        cout << x.first << ' ' << x.second << '\n';
    }
}

Comments