Problems › Strings & pattern matching

Find the Index of First Match

Difficulty: Easy · Topic: Strings & pattern matching

Return the index of the first occurrence of needle in haystack, or -1 if it isn't present. If needle is the empty string, return 0. (This is the strStr / indexOf operation.)

Examples

str_str("hello", "ll")
→ 2
str_str("aaaaa", "bba")
→ -1
str_str("", "")
→ 0

Target complexity: time O(n·m), space O(1)

Write your solution in Python and run it against hidden tests right on this page. Progressive hints and Python + C++ reference solutions are included.

Learn the idea first: the lesson for this problem.

More Strings & pattern matching problems