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
haystack="hello", needle="ll". Slide needle across haystack one position at a time, comparing character by character.
1FUNCTION strStr(haystack, needle):2 FOR i from 0 to length of haystack - length of needle:3 matched = 04 WHILE haystack[i + matched] == needle[matched]:5 add 1 to matched6 IF matched == length of needle: RETURN i7 RETURN -1
← / → step · space play · Home restart