Implement the countPatternOccurrences method that counts how many times a pattern appears inside the given text.

The input contains two strings: text and pattern. Your task is to count how many times pattern appears inside text.

Overlapping matches must also be counted. For example, in aaaa, the pattern aa appears at positions 0, 1, and 2, so the answer is 3.

Example 1

Input
text (string) = aaaa
pattern (string) = aa
Returns (int) 3

Example 2

Input
text (string) = abcabcabc
pattern (string) = abc
Returns (int) 3

Example 3

Input
text (string) = hello
pattern (string) = z
Returns (int) 0

Check every possible starting position in text where the pattern can fit.

At each position, compare the substring of the same length as pattern. If it matches, increase the count. Move only one position at a time so overlapping occurrences are also included.

Pseudocode:

function countPatternOccurrences(text, pattern):
    count = 0
    textLength = length of text
    patternLength = length of pattern
    for i from 0 to textLength - patternLength:
        if substring of text from i with patternLength == pattern:
            count++
    return count
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.