Skip to content

Commit f90ad4b

Browse files
add time complexity and preamble
1 parent f430c31 commit f90ad4b

File tree

1 file changed

+9
-0
lines changed
  • src/_Classics_/knuth-morris-pratt

1 file changed

+9
-0
lines changed

src/_Classics_/knuth-morris-pratt/index.js

+9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
11

2+
/* *
3+
* The time complexity of KMP algorithm is O(n) in the worst case
4+
* Example use case: Pattern = AABCAB Text = AAABACABAABCABAABCA
5+
* LPSArray = [ 0, 0, 1, 2, 3, 0 ]
6+
* Found = true, at position 13
7+
* */
8+
29
// Longest prefix suffix - generate an array of the longest previous suffix for each pattern array value
310
const createLPS = (pattern, patternLength, lps) => {
411
// initialise the current longest prefix suffix length and iterator index values
@@ -37,13 +44,15 @@
3744
* array/table to essentially skip chunks of the text that we know will match the pattern.
3845
* This algorithm will return true if the pattern is a subset of the text, else it will return false.
3946
* This algorithm accepts two strings, the pattern and text.
47+
* The time complexity of the KMP algorithm is O(n) in the worst case.
4048
* */
4149
const KMPSearch = (pattern, text) => {
4250
const patternLength = pattern.length; // Often referred to as M
4351
const textLength = text.length; // Often referred to as N
4452

4553
let lps = [patternLength]; // Longest Pattern Suffix - array containing the lps for all pattern value positions
4654
lps = createLPS(pattern, patternLength, lps); // This is preprocessed - before the text is searched for the pattern.
55+
// console.log({ lpsArray: lps })
4756

4857
let patternIndex = 0; // Referred to as P
4958
let textIndex = 0; // Referred to as T

0 commit comments

Comments
 (0)