15% off all plans & roadmaps Use code
See plansFind the Index of the First Occurrence in a String
- LeetCode 28
- Easy
- String Manipulation Patterns
- Naive / KMP / Rabin-Karp
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^4haystackandneedleconsist 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.
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.
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
- Let
nbe the haystack length andmthe needle length. Ifmis 0, return 0. - Loop
ifrom 0 ton - minclusive. - For each
i, setj = 0and advancejwhilehaystack[i + j]equalsneedle[j]. - If
jreachesm, every character matched, so returni. - 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: compareswiths, thenawitha, thendwithd. All three match, sojreaches 3.j == m, so the function returns 0.
The later starts never run. The answer is 0, which matches the example.
Complexity
| Time | O(n * m) |
|---|---|
| Space | O(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 -1JavaTested in our runner
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length();
int m = needle.length();
if (m == 0) return 0;
for (int i = 0; i + m <= n; i++) {
int j = 0;
while (j < m && haystack.charAt(i + j) == needle.charAt(j)) {
j++;
}
if (j == m) return i;
}
return -1;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
int n = (int)haystack.size();
int m = (int)needle.size();
if (m == 0) return 0;
for (int i = 0; i + m <= n; i++) {
int j = 0;
while (j < m && haystack[i + j] == needle[j]) j++;
if (j == m) return i;
}
return -1;
}
};JavaScriptTested in our runner
var strStr = function(haystack, needle) {
const n = haystack.length;
const m = needle.length;
if (m === 0) return 0;
for (let i = 0; i + m <= n; i++) {
let j = 0;
while (j < m && haystack[i + j] === needle[j]) j++;
if (j === m) return i;
}
return -1;
};GoTested in our runner
func strStr(haystack string, needle string) int {
n := len(haystack)
m := len(needle)
if m == 0 {
return 0
}
for i := 0; i+m <= n; i++ {
j := 0
for j < m && haystack[i+j] == needle[j] {
j++
}
if j == m {
return i
}
}
return -1
}C#Tested in our runner
public class Solution {
public int strStr(string haystack, string needle) {
int n = haystack.Length;
int m = needle.Length;
if (m == 0) return 0;
for (int i = 0; i + m <= n; i++) {
int j = 0;
while (j < m && haystack[i + j] == needle[j]) j++;
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 infographicSolution 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
- Build
lps, an array of lengthm. Setlps[0] = 0. - Use a pointer
lengthfor the current border and a pointerifor the position being filled. On a match, increaselength, store it inlps[i], and advancei. - On a mismatch with
length > 0, setlength = lps[length - 1]and try again without advancingi. - On a mismatch with
length == 0, setlps[i] = 0and advancei. - Set
j = 0and walk the haystack withkfrom 0 ton - 1. Never movekbackward. - On a mismatch with
j > 0, setj = lps[j - 1]and compare the same haystack character again. - When the characters match, advance
j. Whenj == m, returnk - m + 1. - 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.
| Step | k | haystack[k] | j before | Compare | j after |
|---|---|---|---|---|---|
| 1 | 0 | s | 0 | s = s, match | 1 |
| 2 | 1 | a | 1 | a = a, match | 2 |
| 3 | 2 | d | 2 | d = d, match | 3 |
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
| Time | O(n + m) |
|---|---|
| Space | O(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 -1JavaTested in our runner
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length();
int m = needle.length();
if (m == 0) return 0;
int[] lps = new int[m];
int length = 0;
int i = 1;
while (i < m) {
if (needle.charAt(i) == needle.charAt(length)) {
length++;
lps[i] = length;
i++;
} else if (length > 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
int j = 0;
for (int k = 0; k < n; k++) {
while (j > 0 && haystack.charAt(k) != needle.charAt(j)) {
j = lps[j - 1];
}
if (haystack.charAt(k) == needle.charAt(j)) j++;
if (j == m) return k - m + 1;
}
return -1;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
int n = (int)haystack.size();
int m = (int)needle.size();
if (m == 0) return 0;
vector<int> lps(m, 0);
int length = 0;
int i = 1;
while (i < m) {
if (needle[i] == needle[length]) {
length++;
lps[i] = length;
i++;
} else if (length > 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
int j = 0;
for (int k = 0; k < n; k++) {
while (j > 0 && haystack[k] != needle[j]) {
j = lps[j - 1];
}
if (haystack[k] == needle[j]) j++;
if (j == m) return k - m + 1;
}
return -1;
}
};JavaScriptTested in our runner
var strStr = function(haystack, needle) {
const n = haystack.length;
const m = needle.length;
if (m === 0) return 0;
const lps = new Array(m).fill(0);
let length = 0;
let i = 1;
while (i < m) {
if (needle[i] === needle[length]) {
length++;
lps[i] = length;
i++;
} else if (length > 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
let j = 0;
for (let k = 0; k < n; k++) {
while (j > 0 && haystack[k] !== needle[j]) {
j = lps[j - 1];
}
if (haystack[k] === needle[j]) j++;
if (j === m) return k - m + 1;
}
return -1;
};GoTested in our runner
func strStr(haystack string, needle string) int {
n := len(haystack)
m := len(needle)
if m == 0 {
return 0
}
lps := make([]int, m)
length := 0
i := 1
for i < m {
if needle[i] == needle[length] {
length++
lps[i] = length
i++
} else if length > 0 {
length = lps[length-1]
} else {
lps[i] = 0
i++
}
}
j := 0
for k := 0; k < n; k++ {
for j > 0 && haystack[k] != needle[j] {
j = lps[j-1]
}
if haystack[k] == needle[j] {
j++
}
if j == m {
return k - m + 1
}
}
return -1
}C#Tested in our runner
public class Solution {
public int strStr(string haystack, string needle) {
int n = haystack.Length;
int m = needle.Length;
if (m == 0) return 0;
int[] lps = new int[m];
int length = 0;
int i = 1;
while (i < m) {
if (needle[i] == needle[length]) {
length++;
lps[i] = length;
i++;
} else if (length > 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
int j = 0;
for (int k = 0; k < n; k++) {
while (j > 0 && haystack[k] != needle[j]) {
j = lps[j - 1];
}
if (haystack[k] == needle[j]) j++;
if (j == m) return k - m + 1;
}
return -1;
}
}Common mistakes
i = i - j + 1; j = 0on a mismatch in the search loop. This moves the haystack pointer backward and rescans characters. Keep the haystack index where it is and setj = lps[j - 1].length = 0on a mismatch while building the table. This undercounts the borders. Fall back withlength = lps[length - 1]and only reset to 0 whenlengthis already 0.- Reading
needle[j]afterjhas already reachedm. This is an index out of range. Return as soon asj == m, before the next comparison. - Returning
kinstead ofk - m + 1. The indexkis where the match ends, so the start ism - 1positions earlier. - Writing
for i in range(n - m)in brute force. This skips the last valid start, soabcwithcreturns -1 instead of 2. The loop must run throughn - minclusive. - Comparing substrings with
==in Java.haystack.substring(i, i + m) == needlecompares references, not contents. UsecharAtin a loop orequals.
Edge cases
- Needle longer than haystack, such as haystack
aband needleabc: the loop runs zero times and the answer is -1. - Needle equal to haystack, such as
abcandabc: the answer is 0. - Match at the very end, such as haystack
leetcodeand needlecode: the answer is 4, so the loop must reach the last character. - Repeated prefix, such as haystack
mississippiand needleissip: the answer is 4. This input exercises the fallback in KMP and the restart in brute force. - Several occurrences, such as haystack
sadbutsadand needlesad: the answer is 0, not 6, because the first match wins. - Single character that is absent, such as haystack
abcand needlez: 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 setj = 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
jnever 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
Related problems
- Longest Common Prefix · same technique: Naive / KMP / Rabin-Karp
- Greatest Common Divisor of Strings · same technique: Naive / KMP / Rabin-Karp
- Repeated Substring Pattern · same technique: Naive / KMP / Rabin-Karp
- Rotate String · same technique: Naive / KMP / Rabin-Karp
- Group Anagrams · next harder, same pattern
- Valid Anagram · same pattern: String Manipulation Patterns
- Valid Palindrome · same pattern: String Manipulation Patterns
- Roman to Integer · same pattern: String Manipulation Patterns
- Add Binary · same pattern: String Manipulation Patterns
- Valid Palindrome II · same pattern: String Manipulation Patterns