Z function

Strings (Advanced Algo) Advanced Problems (Less asked) Hard
  • Fun Fact: The underlying concept of this problem, finding the occurrences of a pattern in a text string, is commonly used in search engines and text editors
  • For example, the 'Find' or 'Search' function in text editors like Notepad or Word, uses similar algorithms to highlight or navigate to the occurrences of a search term within the open document
  • Similarly, search engines like Google also use more complex variations of this algorithm to find and display relevant web pages containing the user's search terms

Given two strings, one is a text string, text, and the other is a pattern string, pattern. Print the indexes of all occurrences of the pattern string in the text string using the Z function algorithm. Use 0-based indexing while returning the indices.

Examples:

Input: text = "xyzabxyzabxyz", pattern = "xyz"


Output: 0 5 10


Expalanation : The pattern "xyz" occurs three times in text, starting at indices 0, 5, and 10.

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


Output: 1


Expalanation : The pattern "abc" occurs one time in text, starting at index 1.

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

Constraints

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

Hints

  • "Concatenate pattern, a separator ($), and text: S = \text{pattern} + ""$"" + \text{text} This ensures that if pattern exists in text, the Z-array will contain prefix matches at corresponding indices."
  • The Z-array at index i gives the longest prefix of S starting at i that matches the prefix of S. If Z[i] == len(pattern), it means pattern appears in text at index i - (len(pattern) + 1). If Z[i] matches pattern length, compute the starting index in text using offset correction.

Company Tags

Johnson & Johnson IBM Bloomberg Cloudflare Zomato Cerner JPMorgan Chase Bain & Company Walmart AMD PayPal Docker OYO Rooms Chewy Micron Technology Unity Technologies Intel Snowflake Twilio Teladoc Health Freshworks Nutanix Texas Instruments Wayfair Rockstar Games Google Microsoft Amazon Meta Apple Netflix Adobe