String Matching - KMP
Algorithm
- Read text and pattern.
- Build LPS array for pattern.
- Start two indices: i for text, j for pattern.
- If characters match, move both i and j.
- If j reaches pattern length, report one match and set j = LPS[j-1].
- On mismatch:
- If j is not 0, set j = LPS[j-1].
- Else move i.
- Continue until end of text.
Time Complexity
- O(n + m)
Space Complexity
- O(m)