Find the Index of the First Occurrence in a String
Find the Index of the First Occurrence in a String is a easy arrays & hashing problem solved with the string matching (kmp) pattern.
The best approach, optimal (prefix function / failure table), runs in O(n + m) time and O(m) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (try every start) up.
Problem
Given two strings haystack and needle, return the index at which needle first appears as a contiguous substring of haystack.
If needle does not occur in haystack, return -1.
Examples
Example 1
- Input
haystack = "banana", needle = "ana"- Output
1- Why
- "ana" appears at index 1 and again at index 3; the first one is returned.
Example 2
- Input
haystack = "orchard", needle = "chart"- Output
-1- Why
- "chart" never appears inside "orchard".
Example 3
- Input
haystack = "aaab", needle = "aab"- Output
1- Why
- A naive scan that jumps ahead after a partial match would miss this; the match starts at index 1.
Constraints
1 <= haystack.length, needle.length <= 10^4- Both strings consist only of lowercase English letters
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every start) | O(n · m) | O(1) |
| Optimal (prefix function / failure table) | O(n + m) | O(m) |
1Brute force (try every start)
O(n · m)Up to n - m + 1 starts, each comparing up to m characters.O(1)Only loop indices.For every index where the needle could still fit, compare the needle with the haystack character by character and return the first index where all characters match.
- For i from 0 to n - m:
- Compare haystack[i + k] with needle[k] for k = 0..m-1, stopping at the first mismatch.
- If all m characters match, return i.
- Return -1.
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
for (int i = 0; i + m <= n; i++) {
int k = 0;
while (k < m && haystack.charAt(i + k) == needle.charAt(k)) k++;
if (k == m) return i;
}
return -1;
}
}class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n, m = len(haystack), len(needle)
for i in range(n - m + 1):
k = 0
while k < m and haystack[i + k] == needle[k]:
k += 1
if k == m:
return i
return -1class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
for (int i = 0; i + m <= n; i++) {
int k = 0;
while (k < m && haystack[i + k] == needle[k]) k++;
if (k == m) return i;
}
return -1;
}
};function strStr(haystack, needle) {
const n = haystack.length, m = needle.length;
for (let i = 0; i + m <= n; i++) {
let k = 0;
while (k < m && haystack[i + k] === needle[k]) k++;
if (k === m) return i;
}
return -1;
}2Optimal (prefix function / failure table)
O(n + m)Each pointer only moves forward overall; every fallback is paid for by an earlier step forward.O(m)The lps table has m entries.Build the failure table lps for the needle: lps[k] is the length of the longest proper prefix of needle[0..k] that is also its suffix. Then scan the haystack once with a pointer k into the needle. On a mismatch, fall back to lps[k - 1] instead of restarting, so no haystack character is ever re-read.
- Build lps: for i = 1..m-1, while len > 0 and needle[i] != needle[len], len = lps[len - 1]; if they match, len++; lps[i] = len.
- Scan haystack with k = 0: while k > 0 and haystack[i] != needle[k], k = lps[k - 1]; if they match, k++.
- When k == m, return i - m + 1.
- Return -1.
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
int[] lps = new int[m];
for (int i = 1, len = 0; i < m; i++) {
while (len > 0 && needle.charAt(i) != needle.charAt(len)) len = lps[len - 1];
if (needle.charAt(i) == needle.charAt(len)) len++;
lps[i] = len;
}
for (int i = 0, k = 0; i < n; i++) {
while (k > 0 && haystack.charAt(i) != needle.charAt(k)) k = lps[k - 1];
if (haystack.charAt(i) == needle.charAt(k)) k++;
if (k == m) return i - m + 1;
}
return -1;
}
}class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n, m = len(haystack), len(needle)
lps = [0] * m
length = 0
for i in range(1, m):
while length > 0 and needle[i] != needle[length]:
length = lps[length - 1]
if needle[i] == needle[length]:
length += 1
lps[i] = length
k = 0
for i in range(n):
while k > 0 and haystack[i] != needle[k]:
k = lps[k - 1]
if haystack[i] == needle[k]:
k += 1
if k == m:
return i - m + 1
return -1class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
vector<int> lps(m, 0);
for (int i = 1, len = 0; i < m; i++) {
while (len > 0 && needle[i] != needle[len]) len = lps[len - 1];
if (needle[i] == needle[len]) len++;
lps[i] = len;
}
for (int i = 0, k = 0; i < n; i++) {
while (k > 0 && haystack[i] != needle[k]) k = lps[k - 1];
if (haystack[i] == needle[k]) k++;
if (k == m) return i - m + 1;
}
return -1;
}
};function strStr(haystack, needle) {
const n = haystack.length, m = needle.length;
const lps = new Array(m).fill(0);
for (let i = 1, len = 0; i < m; i++) {
while (len > 0 && needle[i] !== needle[len]) len = lps[len - 1];
if (needle[i] === needle[len]) len++;
lps[i] = len;
}
for (let i = 0, k = 0; i < n; i++) {
while (k > 0 && haystack[i] !== needle[k]) k = lps[k - 1];
if (haystack[i] === needle[k]) k++;
if (k === m) return i - m + 1;
}
return -1;
}Edge cases to test
- needle longer than haystack
- needle equals haystack
- Match at the very start or the very end
- Overlapping partial matches, like haystack = "aaaaab", needle = "aab"
Hints
Hint 1
Try every starting position and compare character by character.
Hint 2
After a mismatch, the part of the needle you already matched tells you where the next possible match can start.
Hint 3
Precompute, for each prefix of the needle, the length of its longest proper prefix that is also a suffix (a failure table).
FAQ
What is the best time complexity for Find the Index of the First Occurrence in a String?
Optimal (prefix function / failure table) runs in O(n + m) time and O(m) extra space. Each pointer only moves forward overall; every fallback is paid for by an earlier step forward.
Which pattern does Find the Index of the First Occurrence in a String use?
It is a arrays & hashing problem that uses the string matching (kmp) pattern. Other problems with the same pattern: Longest Happy Prefix.
Is there a brute force solution for Find the Index of the First Occurrence in a String?
Yes. Brute force (try every start) takes O(n · m) time and O(1) space. For every index where the needle could still fit, compare the needle with the haystack character by character and return the first index where all characters match.
Which edge cases should I test for Find the Index of the First Occurrence in a String?
needle longer than haystack; needle equals haystack; Match at the very start or the very end; Overlapping partial matches, like haystack = "aaaaab", needle = "aab".