15% off all plans & roadmaps Use code

See plans

Find the Index of the First Occurrence in a String

Updated

TL;DR: Return the index where `needle` first appears inside `haystack`, or -1 if it never does. Brute force tries every start position, while KMP precomputes a prefix table so the haystack pointer only moves forward.

Problem

You are given two strings, haystack and needle. Return the index of the first place needle appears inside haystack. If needle does not appear at all, return -1.

Example 1

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: sad occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.

Example 2

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: leeto does not occur in leetcode, so we return -1.

Constraints

  • 1 <= haystack.length, needle.length <= 10^4
  • haystack and needle consist of only lowercase English letters.

Constraints that matter

  • Lengths go up to 10^4, so n * m is at most about 2.5 * 10^7 in the worst split. Brute force passes the limit, but the interviewer still expects a bound that does not grow with n * m.
  • Both strings use only lowercase letters, so each comparison is a plain character check with no Unicode handling.
  • Lengths are at least 1, so an empty needle never arrives. Code should still return 0 for it, because that is the usual convention.
  • Only the first occurrence matters, so the search can stop at the first full match and does not need to find the others.

View on LeetCode

Hints

Hint 1

This is substring search.

Hint 2

Try every start index i from 0 to n - m.

Solution

Intuition

This is substring search. Brute force checks every start position, and that method is often called naive string matching. The constraints are small enough that brute force passes, but the interview expects a solution that is linear in the input size. The pattern to reach for is Knuth-Morris-Pratt (KMP), which uses the needle's own structure to avoid rechecking characters.

Picture reading a long line of text with a ruler that never moves backward. The lps table is a note saying how far to slide the needle after a failed letter, so you never reread text.

The waste in brute force shows up after a partial match. If you matched five characters and then fail, you know exactly what those five haystack characters were. Brute force throws that knowledge away and restarts one position later.

KMP keeps that knowledge in a table. For each prefix of the needle, the table stores the length of the longest proper prefix that is also a suffix of that prefix. After a failed match, the table tells you how far the needle can shift while still agreeing with the text you already read. The haystack pointer never moves backward.

Rabin-Karp is the other common answer. It compares rolling hashes and verifies each hash hit with a direct comparison, which gives average linear time.

Watch the pattern animation

Worked example

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: The string sad starts at index 0 and again at index 6. Index 0 comes first, so the answer is 0. The same example drives every dry run on this page.

Approach 1: Brute force

Try every start index i from 0 to n - m. At each start, compare the needle with the haystack one character at a time. The first start where all m characters match is the answer. If no start matches, return -1.

This is the first solution most people write, and it is correct for every input. Its weakness is that a mismatch after a long partial match throws away all the work done for that start, and the next start repeats most of it.

Steps

  1. Let n be the haystack length and m the needle length. If m is 0, return 0.
  2. Loop i from 0 to n - m inclusive.
  3. For each i, set j = 0 and advance j while haystack[i + j] equals needle[j].
  4. If j reaches m, every character matched, so return i.
  5. If the outer loop finishes without a full match, return -1.

Dry run

Here n = 9 and m = 3, so the starts run from 0 to 6.

  • i = 0: compare s with s, then a with a, then d with d. All three match, so j reaches 3.
  • j == m, so the function returns 0.

The later starts never run. The answer is 0, which matches the example.

Complexity

TimeO(n * m)
SpaceO(1)

Let n be the haystack length and m the needle length. The outer loop tries n - m + 1 starts. For each start, the inner loop does at most m character comparisons, so the total is at most (n - m + 1) * m, which is O(n * m).

The function stores only a few integers, so the extra space is O(1). The worst case is a haystack like aaaa...ab with a needle like aaa...ac, where almost every start runs nearly to the last character.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(haystack)
        m = len(needle)
        if m == 0:
            return 0
        # try every start position
        for i in range(n - m + 1):
            j = 0
            while j < m and haystack[i + j] == needle[j]:
                j += 1
            if j == m:
                return i
        return -1

The Naive / KMP / Rabin-Karp infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Naive / KMP / Rabin-Karp

Part of String Manipulation Patterns

Approach 2: KMP with a prefix tableOptimalNaive / KMP / Rabin-Karp

What is slow in brute force is the restart. After matching j characters and failing, brute force moves the start forward by one and compares those same haystack characters again. Those characters are known, so their information can be reused.

The insight is the prefix table, often called the LPS or failure array. For each prefix of the needle, it stores the length of its longest proper prefix that is also a suffix. On a mismatch at needle position j, the value lps[j - 1] says how many matched characters can stay aligned. You set j to that value and keep the haystack pointer where it is.

Why it is correct. After a mismatch at position j, the last j haystack characters equal the first j needle characters. Any alignment that could still match must agree with a border of the matched prefix, and chaining lps visits every border in order. Since the haystack pointer never moves back, every possible start is still checked, so no match is missed.

Steps

  1. Build lps, an array of length m. Set lps[0] = 0.
  2. Use a pointer length for the current border and a pointer i for the position being filled. On a match, increase length, store it in lps[i], and advance i.
  3. On a mismatch with length > 0, set length = lps[length - 1] and try again without advancing i.
  4. On a mismatch with length == 0, set lps[i] = 0 and advance i.
  5. Set j = 0 and walk the haystack with k from 0 to n - 1. Never move k backward.
  6. On a mismatch with j > 0, set j = lps[j - 1] and compare the same haystack character again.
  7. When the characters match, advance j. When j == m, return k - m + 1.
  8. If the haystack ends first, return -1.

Dry run

First, build the table for the needle sad. lps[0] is 0 by definition. At position 1, a does not match s, and length is 0, so lps[1] = 0. At position 2, d does not match s, so lps[2] = 0.

The table is [0, 0, 0]. The needle has no repeated prefix, so the fallback never helps on this example.

Now search the haystack sadbutsad.

Stepkhaystack[k]j beforeComparej after
10s0s = s, match1
21a1a = a, match2
32d2d = d, match3

After step 3, j equals m = 3. The function returns k - m + 1 = 2 - 3 + 1 = 0.

The fallback does run on a different input. Take haystack aabaaab and needle aaab. The table is [0, 1, 2, 0].

At k = 2, the b fails against needle[2] = a with j = 2, so j drops to lps[1] = 1. The b fails again against needle[1], so j drops to lps[0] = 0. The haystack pointer stays at k = 2 for both checks, and the search resumes at k = 3. The match completes at k = 6, and the function returns 3.

Complexity

TimeO(n + m)
SpaceO(m)

Let n be the haystack length and m the needle length. Building the table takes O(m). The pointer i rises from 1 to m - 1, and length can fall only as often as it rose, so the loop runs at most about 2m times.

The search loop advances k exactly n times. Each step raises j by at most 1, and each fallback lowers j by at least 1, so the fallbacks total at most n. The whole algorithm costs O(n + m), and the table stores m integers, so the space is O(m).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(haystack)
        m = len(needle)
        if m == 0:
            return 0
        # lps[k] = length of the longest proper prefix of needle[:k+1] that is also a suffix of it
        lps = [0] * m
        length = 0
        i = 1
        while i < m:
            if needle[i] == needle[length]:
                length += 1
                lps[i] = length
                i += 1
            elif length > 0:
                # fall back to the next shorter border
                length = lps[length - 1]
            else:
                lps[i] = 0
                i += 1
        j = 0  # characters of needle matched so far
        for k in range(n):
            while j > 0 and haystack[k] != needle[j]:
                j = lps[j - 1]
            if haystack[k] == needle[j]:
                j += 1
            if j == m:
                return k - m + 1
        return -1

Common mistakes

  • i = i - j + 1; j = 0 on a mismatch in the search loop. This moves the haystack pointer backward and rescans characters. Keep the haystack index where it is and set j = lps[j - 1].
  • length = 0 on a mismatch while building the table. This undercounts the borders. Fall back with length = lps[length - 1] and only reset to 0 when length is already 0.
  • Reading needle[j] after j has already reached m. This is an index out of range. Return as soon as j == m, before the next comparison.
  • Returning k instead of k - m + 1. The index k is where the match ends, so the start is m - 1 positions earlier.
  • Writing for i in range(n - m) in brute force. This skips the last valid start, so abc with c returns -1 instead of 2. The loop must run through n - m inclusive.
  • Comparing substrings with == in Java. haystack.substring(i, i + m) == needle compares references, not contents. Use charAt in a loop or equals.

Edge cases

  • Needle longer than haystack, such as haystack ab and needle abc: the loop runs zero times and the answer is -1.
  • Needle equal to haystack, such as abc and abc: the answer is 0.
  • Match at the very end, such as haystack leetcode and needle code: the answer is 4, so the loop must reach the last character.
  • Repeated prefix, such as haystack mississippi and needle issip: the answer is 4. This input exercises the fallback in KMP and the restart in brute force.
  • Several occurrences, such as haystack sadbutsad and needle sad: the answer is 0, not 6, because the first match wins.
  • Single character that is absent, such as haystack abc and needle z: the answer is -1.

Follow-ups interviewers ask

What if you need every starting index, not only the first?
Keep going after a full match. Record k - m + 1, then set j = lps[m - 1] so the search can continue from the longest border. The total time stays O(n + m) plus the size of the output, because each reported index comes from a full match.
Can you solve it in O(1) extra space?
Brute force uses O(1) extra space, but it costs O(n * m) time. Linear time with O(1) extra space is possible with the two-way algorithm of Crochemore and Perrin, but it is hard to write correctly under interview time. KMP needs O(m) for the table, and that table cannot be removed from KMP itself.
What if the haystack is too large for memory and arrives as a stream?
KMP still works. It reads each haystack character once, and j never needs earlier characters because the table tells it where to resume. The memory use is the needle and its table, which is O(m). Brute force would need to look back at earlier characters, so it does not stream cleanly.

Find the Index of the First Occurrence in a String FAQ

What is the time complexity of Find the Index of First Occurrence in a String?

With KMP, the time is O(n + m), where n is the haystack length and m is the needle length. Brute force takes O(n * m) in the worst case. KMP is the answer to give when the interviewer asks for linear time.

Why use KMP for Find the Index of First Occurrence in a String?

KMP stores, for each needle prefix, how far the needle can shift after a mismatch. That lets the haystack pointer move only forward. Brute force restarts the comparison after every mismatch and repeats work.

Can Find the Index of First Occurrence in a String be solved in O(1) extra space?

Yes, with brute force, but that version runs in O(n * m) time. A linear-time solution with O(1) extra space needs the two-way algorithm. KMP itself needs an O(m) table, so no, KMP cannot drop that table.

Do languages have built-in functions for this problem?

Yes. Python has str.find, Java has indexOf, C++ has find, JavaScript has indexOf, Go has strings.Index, and C# has IndexOf. They return the same answer for this problem. Interview problems like this one test the matching logic, so write the search yourself when asked.

How does Rabin-Karp compare with KMP here?

Rabin-Karp slides a rolling hash over the haystack and checks each hash match with a direct comparison. Its average time is O(n + m), but a bad case with many collisions can reach O(n * m). KMP always runs in O(n + m) and needs no hashing.

Asked at

See which companies ask this — Pro

Practise it