Visualize

Pattern visualizer

Implement strStr()

The brute-force approach is simpler than it sounds: try every possible starting position in the haystack, and at each one compare characters against the needle one at a time. The moment a mismatch happens, that start position is ruled out immediately — no need to keep comparing — and the search moves to the next start position. Animated on: haystack = "hello", needle = "ll" — find the index of the first occurrence of needle in haystack..

Slide the needle across the haystack, one start position at a time

time O(n * m)space O(1)step 1 / 4
h
[0]
e
[1]
l
[2]
l
[3]
o
[4]
line 2

haystack="hello", needle="ll". Slide needle across haystack one position at a time, comparing character by character.

Pseudocode
1FUNCTION strStr(haystack, needle):
2 FOR i from 0 to length of haystack - length of needle:
3 matched = 0
4 WHILE haystack[i + matched] == needle[matched]:
5 add 1 to matched
6 IF matched == length of needle: RETURN i
7 RETURN -1

← / → step · space play · Home restart

Where to practice Strings