← Back to Leo Academy Masterclass

Problem #28: Find the Index of the First Occurrence in a String

Easy Array & String

Intuition & Strategy Breakdown

Use sliding window or string searching (or KMP algorithm) to find the starting index of needle inside haystack, returning the first matching index or -1 if not found.

Python Solution

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle: return 0
        for i in range(len(haystack) - len(needle) + 1):
            if haystack[i:i + len(needle)] == needle:
                return i
        return -1

Java Solution

class Solution {
    public int strStr(String haystack, String needle) {
        if (needle.isEmpty()) return 0;
        for (int i = 0; i <= haystack.length() - needle.length(); i++) {
            if (haystack.substring(i, i + needle.length()).equals(needle)) {
                return i;
            }
        }
        return -1;
    }
}
Watch Interactive Video on Leo Academy Main App