Update appNew update is available. Click here to update.
Last Updated: 4 Feb, 2021
Search Pattern (Rabin-Karp Algorithm)
Moderate
Problem statement

You’re given two strings, 'text' of length 'n' and 'pattern' of length 'm', consisting of lowercase characters.


Find all the occurrences of the string β€˜pattern’ in β€˜text’.


For each occurrence, print the index from where it starts in the string β€˜text’ (1 - indexed).


Example:
Input: β€˜text’ = β€œcxyzghxyzvjkxyz” and β€˜pattern’ = β€œxyz”

Output: 2 7 13

Explanation: The pattern β€˜pattern’ = β€œxyz” appears at 3 positions in β€˜text’.
Input Format:
The first line contains the string β€˜text’.
The second line contains the string β€˜pattern’.


Output format:
The first line contains an integer β€˜count’, the number of occurrences.
The first line contains β€˜count’ integers, the positions of occurrence of β€˜pattern’ in β€˜text’ in sorted order.


Note:
You need not print anything. Return the list of positions in any order. They will be sorted and printed.
Approaches

01Approach

Check each substring in β€˜text’ of length β€˜m’ and see if they are equal to β€˜pattern’.

If we find a match we add the current index (1 - based) in our list β€˜ans’.

The steps are as follows:

List stringMatch(string β€˜text’, string β€˜pattern’)

  1. Let β€˜n’ = β€˜text.length’, β€˜m’ = β€˜pattern.length’
  2. Let β€˜ans’ be a list storing the indices of occurrences.
  3. For β€˜i’ in the range from 0 to β€˜n’ - β€˜m’ (inclusive):
    • Check whether the substring of β€˜text’ from index β€˜i’ to β€˜i’ + β€˜m’ is equal to β€˜pattern’ or not.
    • If the substring is equal to β€˜pattern’:
      • Add β€˜i’ + 1 in β€˜ans’.
  4. Return β€˜ans’.