Manual Substring Search (No find())

Medium ⏱ 12 min 52% acceptance ★★★★★ 4.5
Write manual_find(s, sub) that returns the index of the first occurrence of sub in s, or -1 if absent — but implemented by manually comparing slices in a loop, without using str.find(), str.index(), or the in operator.

Examples

Example 1
Input
s = 'hello world', sub = 'world'
Output
6
Explanation

Sliding a window of len('world') across s, the match starts at index 6.

Example 2
Input
s = 'abc', sub = 'xyz'
Output
-1
Explanation

No window of s equals sub.

Constraints

  • 1 <= len(sub) <= len(s) (or sub longer than s, which should return -1)

Topics

StringsSubstring Search

Companies

AmazonApple

Hints

Hint 1

Slide a window of length len(sub) across every valid starting index of s.

Hint 2

At each position compare s[i:i+len(sub)] to sub.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.