KMP Algorithm or LPS array

Strings (Advanced Algo) Advanced Problems (Less asked) Hard
  • The Knuth-Morris-Pratt (KMP) algorithm, the underlying concept for solving this problem, is exceptionally useful and widely applied in the real world
  • For instance, search functions in word processors, text editors, and browsers use pattern matching algorithms similar to KMP
  • It enables them to quickly find and highlight all occurrences of a user's input within the loaded document or webpage — important for productivity and usability
  • Particularly, KMP is known for its efficiency as it avoids backtracking, thus providing quicker search results

Given two strings, one is a text string, text, and the other is a pattern string, pattern. Find and print the indices of all the occurrences of the pattern string within the text string. Use 0-based indexing for the indices, and ensure that the indices are in ascending order. If the pattern does not occur in the text, return an empty list.


Implement this solution using the Knuth-Morris-Pratt (KMP) algorithm for efficient pattern matching.

Examples:

Input: text = "abracadabra", pattern = "abra"


Output: 0 7


Expalanation : The pattern "abra" appears at the 0st and 7th positions in the text "abracadabra".

Input: text = "abcabcabc", pattern = "abc"


Output: 0 3 6


Expalanation : The pattern "abc" appears at the 0st, 3th, and 6th positions in the text "abcabcabc".

Input: text = "daad", pattern = "aa"

Constraints

  • 1<= text.length, pattern.length <=5*104

Hints

  • "Use two pointers: one for text, one for pattern. If characters match, move both forward. If a mismatch occurs, use LPS to avoid unnecessary comparisons."
  • When the pattern completely matches, store its starting index in a result list.

Company Tags

Square Wayfair OYO Rooms Goldman Sachs Flipkart Rockstar Games Activision Blizzard Target MongoDB Databricks Chewy AMD Uber Snowflake Morgan Stanley Airbnb Zomato Western Digital Reddit Lyft Teladoc Health Optum Cerner American Express Seagate Technology Google Microsoft Amazon Meta Apple Netflix Adobe