BackmediumStringsAmazon

Substring Pattern Frequency Solution

Problem Statement

Given a string sequence and a substring pattern, determine the total count of occurrences of pattern within sequence, where overlapping occurrences are considered valid.

Example 1
Input
abcabcabc
Output
12

Explanation: Step-by-step: with input 'abcabcabc', we first find the pattern 'abc' at position 0, then at position 3, and so on, giving output 12.

Example 2
Input
xyxyxy
Output
4

Explanation: Step-by-step: with input 'xyxyxy', we first find the pattern 'xy' at position 0, then at position 2, and so on, giving output 4.

Constraints

  • 1 <= length of signal string <= 10^5
  • 1 <= length of pattern <= 100
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

šŸš€ Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Substring Pattern Frequency — Problem Statement & Solution Guide

StringsMediumMixed
TimeO(n*m)
|
SpaceO(1)

Problem Description

Given a string sequence and a substring pattern, determine the total count of occurrences of pattern within sequence, where overlapping occurrences are considered valid.

Examples

Example 1

Input

abcabcabc

Output

12

Explanation: Step-by-step: with input 'abcabcabc', we first find the pattern 'abc' at position 0, then at position 3, and so on, giving output 12.

Example 2

Input

xyxyxy

Output

4

Explanation: Step-by-step: with input 'xyxyxy', we first find the pattern 'xy' at position 0, then at position 2, and so on, giving output 4.

Constraints

  • 1 <= length of signal string <= 10^5
  • 1 <= length of pattern <= 100

Optimal Approach & Strategy

The optimized approach involves using the Knuth-Morris-Pratt (KMP) algorithm or the Rabin-Karp algorithm, which are designed for string pattern matching and can handle overlaps efficiently. These algorithms preprocess the pattern to create a lookup table that allows for efficient matching, resulting in a time complexity of O(n + m).

Brute Force Approach

The brute-force approach involves using two nested loops to check every possible substring of the signal string against the pattern, resulting in a time complexity of O(n²). This approach is simple but inefficient for large inputs. It can be implemented using a simple loop to iterate over the signal string and another loop to check if the pattern matches at each position.

Verified Code Solutions

No solution currently available for JavaScript. Select another language tab above.

Asked in Top Tech Interviews

Amazon

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.