v9.1.1
Menu

Implement strStr

easyPROArrays & StringsMicrosoft DSA

Return the index of the first occurrence of needle in haystack, or -1 if not found.

Example

Input
sadbutsad
sad
Output
0
Reasoning
  • The function strStr checks if the substring needle ("sad") exists in the string haystack ("sadbutsad")
  • It starts by comparing the first character of needle with the first character of haystack, finding a match
  • Since the rest of the characters in needle also match the subsequent characters in haystack, it confirms the presence of needle at the starting index
  • The function returns the index where the match is found, which is 00 in this case, as the needle is found at the beginning of the haystack

Constraints

  • 1 <= len(haystack), len(needle) <= 10^4
  • Strings consist of lowercase English letters

More from Microsoft DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.