![]() |
VOOZH | about |
Given a string S and a pattern P, your task is to count the number of positions where the pattern occurs in the string.
Examples:
Input: S = "saippuakauppias", P = "pp"
Output: 2
Explanation: "pp" appears 2 times in S.Input: S = "aaaa", P = "aa"
Output: 3
Explanation: "aa" appears 3 times in S.
Approach: To solve the problem, follow the below idea:
To find all occurrences of a pattern in a text we can use various String-Matching algorithms. The Knuth-Morris-Pratt (KMP) algorithm is a suitable choice for this problem. KMP is an efficient string-matching algorithm that can find all occurrences of a pattern in a string in linear time.
Concatenate the Pattern and Text: The first step is to concatenate the pattern and the text with a special character # in between. This is done to ensure that the pattern and text don’t overlap during the computation of the prefix function.
Compute the Prefix Function: The computePrefix function is used to compute the prefix function of the concatenated string. The prefix function for a position i in the string is defined as the maximum proper prefix of the substring ending at position i that is also a suffix of this substring. This function is a key part of the KMP algorithm.
Count the Occurrences: After the prefix function is computed, the next step is to count the number of occurrences of the pattern in the text. This is done by iterating over the prefix function array and checking how many times the pattern length appears in the array. Each time the pattern length appears in the array, it means an occurrence of the pattern has been found in the text.
Step-by-step algorithm:
Below is the implementation of the algorithm:
2
Time Complexity: O(N+M) where N is the length of the text and M is the length of the pattern to be found.
Auxiliary Space: O(N)