Skip to contentKEEP THE CRAFTTHE SANCTUARY

Find Every String Match

Slide the pattern along the text, compare it character by character at each start, and record every start where it fully matches, overlaps included.

The problem

Implement find_occurrences(text, pattern). Return every index where pattern starts in text, from left to right. Matches may overlap: in "aaaa" the pattern "aa" starts at 0, 1 and 2, so the answer is [0, 1, 2]. If pattern never appears, return []. An empty pattern matches at every position from 0 through len(text), so find_occurrences("abc", "") returns [0, 1, 2, 3]. Compare the characters yourself: do not use str.find, str.index or regular expressions.

Starter code

def find_occurrences(text, pattern):
    pass

Public examples

  1. text = "aaaa", pattern = "aa"gives[0, 1, 2]
  2. text = "python", pattern = "java"gives[]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.