candidate windows
Start index 0 through haystack.length − needle.length. Each defines a window of needle.length characters. Any start beyond that would run past the end.
A search engine highlights query terms within documents by locating where each keyword
first appears — but raw text offers only characters, not an index. The approach slides
a window across the haystack, comparing it character-by-character against the needle.
For each candidate position, match as far as you can; if every character agrees, return
that position. If not, advance and try the next start. O(n · m) worst case
— simple, correct, and often fast in practice.
Each valid start index defines one candidate window with the same length as the needle. The algorithm tries every window left to right, returning the first full match.
Start index 0 through haystack.length − needle.length. Each defines a window of needle.length characters. Any start beyond that would run past the end.
Within each window, compare characters left to right against the needle. Stop at the first mismatch — no need to check the rest of that window.
A window that matches 4 out of 5 characters is not a partial success — it's a failed candidate. Only a full match counts. Keep scanning later windows.
A nested loop: the outer loop picks window starts, the inner loop compares characters.
The last candidate window starts at haystack.length − needle.length. Any later start would run past the end of the haystack.
At position start, compare haystack[start + j] with needle[j] for j = 0, 1, …. Stop at the first mismatch.
A window where every character agrees is the first occurrence. Return its start index immediately.
After exhausting all candidate windows without a full match, the needle does not occur in the haystack.
Some inputs have very few candidate windows, or none at all.
When the needle is longer, no valid start index exists. The last valid start would be negative. The outer loop never runs — return −1 immediately.
Only one window exists (start = 0), and it spans the entire haystack. If every character matches, the answer is 0. If any character differs, the answer is −1.
Each window is one character wide. The comparison is a single equality check. The first matching character's index is the answer.