Learned KMP Algorithm and solved Longest Prefix Suffix problem

Day 33 of my DSA Journey 🚀 🔸Today I explored one of the most powerful string algorithms — KMP (Knuth–Morris–Pratt) Algorithm — and solved the problem “Longest Prefix Suffix.” 🔹Problem Statement: Find the length of the longest proper prefix of the string which is also a suffix. 🔹My Approach (KMP LPS Array): -Built the LPS (Longest Prefix Suffix) array which stores the length of the longest prefix which is also a suffix for each index. -Used two pointers: pre → tracks the prefix. suff → scans the string. -If characters match, extend the prefix and suffix. -If they don’t match, use the previously computed LPS values to avoid unnecessary re-checks. ✅ Time Complexity: O(n) ✅ Space Complexity: O(n) (for the LPS array) This was my first practical implementation of KMP Algorithm, and I can already see how efficient it is compared to the naive substring matching approaches.

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories