Skip to content

Python interview practice/Amazon

Find the Index of the First Occurrence in a String

Easytwo-pointers · string

The problem

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Function: def strStr(haystack,needle):

Example input (a JSON list of arguments): ["sadbutsad", "sad"]
Expected output: 0

Inputs satisfy the problem statement. Sequences contain at most 200 elements unless a smaller bound is stated. Use JSON values and the supplied function signature.

Hints

  1. Check each candidate start and compare the whole needle.
  2. Check the supplied examples, empty/boundary cases and the stated answer policy before optimizing.

Worked answer

Try it yourself first. When you are ready, open the answer below.

Show the Python answer
def strStr(haystack,needle):
    for i in range(len(haystack)-len(needle)+1):
        if haystack[i:i+len(needle)]==needle: return i
    return -1

Why it works

Check each candidate start and compare the whole needle. The empty needle occurs at index zero. This direct search states its O(mn) worst case rather than claiming a linear string-matching algorithm.

Complexity: O(mn) time / O(n) slice space.

Time: O(mn) time · Space: O(n) slice space

Run your own solution

Inside your account you write the code in the browser, run it against hidden test cases and save your attempt. Access covers every track, including the rest of Amazon.

See access and price

More free Amazon questions

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.