0% found this document useful (0 votes)
35 views12 pages

24MTCS003HY KMP Algorithm Presentation

A presentaion related to Knuth Morris Pratt Algorithm

Uploaded by

S. Yawar Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views12 pages

24MTCS003HY KMP Algorithm Presentation

A presentaion related to Knuth Morris Pratt Algorithm

Uploaded by

S. Yawar Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Knuth-

Morris-
Pratt
Algorithm

Presented by: Md Shahim Yawar Ali Ansari


Roll No.: 24MTCS003HY
Date: 08-11-2024
Table of Contents

• Definition
• History
• Components of KMP
• Algorithm
• Example
• Run-Time Analysis
• Advantages and Disadvantages
Definition

• The Knuth-Morris-Pratt (KMP)


Algorithm is an efficient
algorithm used to find a pattern
in a text. It reduces the number
of character comparisons by
using the LPS (Longest Prefix
Suffix) array.
History • Developed by Donald
Knuth, Vaughan Pratt, and
James H. Morris in 1977.

• Motivation: To optimize
string matching.

• Context: Part of
foundational algorithms in
text processing.
Components of
KMP
• 1. Construct the LPS (Longest Prefix Suffix)
array for the pattern.

Algorithm
• 2. Use the LPS array to skip unmatched
characters in the text.
• 3. Continue until the pattern is found or the
text is fully scanned.
Example: LPS Array
Text: ABABABCAB
Pattern: ABABC

LPS Array for Pattern- ABABC


Pattern
A B A B C
Character
LPS Value 0 0 1 2 0
Example: Matching Process
Text: ABABABCAB
Pattern: ABABC
Pattern Char
i (Text Index) j (Pattern Index) Text Character Action
acter
Match - Move
0 0 A A
to next i and j
Match - Move
1 1 B B
to next i and j
Match - Move
2 2 A A
to next i and j
Match - Move
3 3 B B
to next i and j
Example: Matching Process​ -- Cont.
2 2 A A Match - Move
Text: ABABABCAB to next i and j
Pattern: ABABC 3 3 B B Match - Move
to next i and j

Mismatch and Adjust j :


i (Text Index) j (Pattern Index) Text Character Pattern Character Action
Mismatch - Adjust j
4 4 A C
to LPS[3] = 2

Final Matches and Pattern Found :


i (Text Index) j (Pattern Index) Text Character Pattern Character Action
Match - Move to
4 2 A A
next i and j
Match - Move to
5 3 B B
next i and j
Match - Pattern
6 4 C C
found
• • Time Complexity: O(m + n), where:
Run-Time • - m is the length of the pattern.
• - n is the length of the text.
Analysis • • Space Complexity: O(m) for the LPS array.
Advantages and
Disadvantages

Advantages:
• Efficient for large texts.
• Skips unnecessary re-evaluation
of characters.

Disadvantages:
• Requires extra space for LPS
array.
• Slightly complex for beginners.

You might also like