Data Structures and Algorithms

# What is Knuth Morris Pratt (KMP) Algorithm and How Does it Work?

In this article, I will explain What is Knuth Morris Pratt (KMP) Algorithm and How Does it Work.

The Knuth-Morris-Pratt (KMP) algorithm is a string matching algorithm that finds all occurrences of a pattern string in a text string. The algorithm works by precomputing a partial match table, which contains the length of the longest proper prefix of the pattern string that is also a suffix of each prefix of the pattern string.

The KMP algorithm then compares the pattern string with the text string, starting from the beginning of both strings. At each position in the text string, the algorithm compares the corresponding characters in the pattern string and the text string. If the characters match, the algorithm moves on to the next position in both strings. If there is a mismatch, the algorithm uses the partial match table to determine the next position in the pattern string to compare with the current position in the text string.

The next position is determined by finding the length of the longest proper prefix of the pattern string that is also a suffix of the prefix of the pattern string up to the current position. This value is stored in the partial match table and is used to determine how far to shift the pattern string to the right before comparing the next character.

The time complexity of the KMP algorithm is O(n+m), where n is the length of the text string and m is the length of the pattern string. The KMP algorithm is more efficient than the Naive algorithm for long text and pattern strings, and it has the advantage of being able to find all occurrences of a pattern in a text string in linear time.

Top 30 Algorithms You Must Know for Coding Interview

What is Huffman Coding Algorithm?

How to Create Hashing Table Using Open Addressing?

What is N Queens Problem?

How to Perform Perfect Hashing?

Innovative Project Ideas in Terraform

How to Perform Universal Hashing?

What is Randomized Select Algorithm?

When should we prefer to React over PHP?

What is Radix Sort and How Does it Work?

## You may also like...

Data Structures and Algorithms

### What is Naive String Matching Algorithm and How Does it Work?

Data Structures and Algorithms

### What is Prim’s Algorithm and Does it Work?

Data Structures and Algorithms