Pattern Count (Non-overlapping)

MediumStringString MatchingMath

Description

Given a text and a pattern, return the number of non-overlapping occurrences of pattern in text. After matching at index i, the next search starts at i + pattern.length.

Examples

Input:text = "ababab", pattern = "ab"
Output:3
Explanation:

Pattern 'ab' occurs at positions 0, 2, and 4 without overlap, giving a total count of 3.

Input:text = "aaaa", pattern = "aa"
Output:2
Explanation:

Pattern 'aa' occurs at positions 0 and 2; matching 'aa' at 0 advances past it so 1 is skipped.

Input:text = "abcabc", pattern = "d"
Output:0
Explanation:

Pattern 'd' does not appear in 'abcabc', so the count is 0.

Constraints

  • 1 ≤ text.length ≤ 10⁴
  • 1 ≤ pattern.length ≤ 10³

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!