28. Find the Index of the First Occurrence in a String
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the starting index of the first occurrence of a given string needle within another string haystack. If needle is not found in haystack, we should return -1. This is a classic substring search problem.
Solution
Find the Index of the First Occurrence in a String in Python
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n = len(haystack)
m = len(needle)
# Per constraints, needle length is at least 1.
# If an empty needle were allowed, we would return 0.
if n < m:
# If haystack is shorter than needle, impossible to find.
return -1
# Iterate through haystack, considering each possible start of a match.
# The range stops at n - m + 1 to ensure the slice is valid.
for i in range(n - m + 1):
# Use Python's string slicing to check the window against the needle.
# This is a clean and Pythonic way to perform the check.
if haystack[i:i+m] == needle:
return i # Found the first occurrence, return its index.
# If the loop completes, no match was found.
return -1
Find the Index of the First Occurrence in a String in Java
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length();
int m = needle.length();
// According to constraints, m is at least 1.
// If m were 0, returning 0 is the standard behavior.
if (n < m) {
// Needle can't be a substring if it's longer than haystack.
return -1;
}
// Iterate through haystack. The loop limit ensures the window does not go out of bounds.
for (int i = 0; i <= n - m; i++) {
// Check for a match starting at index i
int j = 0;
for (; j < m; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
// If characters don't match, this window is not a match.
break;
}
}
// If the inner loop finished, it means we found a full match.
if (j == m) {
return i; // Return the starting index of the match.
}
}
// If we get here, the needle was not found in the haystack.
return -1;
}
}
Find the Index of the First Occurrence in a String in C++
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.length();
int m = needle.length();
// According to constraints, m is at least 1.
// If m were 0, we would return 0 as an empty string is a prefix of any string.
if (n < m) {
// If haystack is shorter than needle, a match is impossible.
return -1;
}
// Iterate through haystack with a sliding window of size m.
// The loop goes from the first possible starting point to the last one.
for (int i = 0; i <= n - m; ++i) {
// Check if the substring of haystack starting at i matches needle.
int j = 0;
for (; j < m; ++j) {
if (haystack[i + j] != needle[j]) {
// Mismatch found, break the inner loop and try the next window.
break;
}
}
// If the inner loop completed without a break, it means all characters matched.
if (j == m) {
return i; // Found the first occurrence, return its index.
}
}
// If the loop finishes without finding a match, return -1.
return -1;
}
};
Find the Index of the First Occurrence in a String in TypeScript
function strStr(haystack: string, needle: string): number {
const n = haystack.length;
const m = needle.length;
// As per constraints, needle.length is >= 1.
// If needle were empty, the standard is to return 0.
if (n < m) {
// If haystack is shorter than needle, a match is impossible.
return -1;
}
// Iterate through haystack. The loop limit `n - m` is the last possible
// index where a match could start.
for (let i = 0; i <= n - m; i++) {
// A simple way to check is to extract the substring and compare.
// This is often more readable than a nested loop.
if (haystack.substring(i, i + m) === needle) {
return i; // Match found, return the starting index.
}
}
// If the loop completes without returning, needle was not found.
return -1;
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.