easy +8 pts

Index of First Occurrence

Find the starting index of a substring in a string, or -1 if it doesn't occur.

Write a function `first_occurrence(haystack, needle)` that returns the index of the first occurrence of the substring `needle` inside the string `haystack`. If `needle` is not present, return -1. If `needle` is empty, return 0. The comparison is case-sensitive. You may not use built-in string methods like `.find()`, `.index()`, `in`, or `re.search()` — but you may use indexing, slicing, and loops.

Constraints

`0 <= len(haystack) <= 1000`, `0 <= len(needle) <= 1000`. The function must run in O(n*m) time or better.

Example

>>> first_occurrence("hello", "ll")
2
>>> first_occurrence("hello", "")
0
>>> first_occurrence("hello", "bark")
-1
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about sliding a window of length len(needle) across haystack.
Compare slice haystack[i:i+len(needle)] to needle.
Remember to handle the empty needle case.
You can stop looping when the remaining part of haystack is shorter than needle.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.