Ctrl K

Where the Fragment Starts

Easy
You get two strings, text and fragment. Find the index at which fragment first appears in text as a contiguous piece and return it (0-based). If fragment does not appear in text at all, return -1. Try not to lean on built-in substring search: the search itself is the point of the exercise.
Example 1
text='bananas', fragment='ana' → 1

"ana" appears at positions 1 and 3 (the occurrences overlap). The first one is 1.

Example 2
text='kettle', fragment='kettles' → -1

The fragment is longer than the text itself, so it cannot be found: the answer is −1.

Example 3
text='abcabd', fragment='abd' → 3
Constraints
  • 1 ≤ len(text), len(fragment) ≤ 10⁵
  • Both strings consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFirst Word With a Given Beginning EasyCapitals Follow the Pattern MediumAnchor Near a Companion MediumWord Near an Anchor HardShortest Match for a Two-Star Pattern Hard
loading Python…
Input
text='bananas', fragment='ana'
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 135 tests on the server, hidden ones included.