↓Skip to main content
  1. LeetCode/

LeetCode 28: Find the Index of the First Occurrence in a String

·1 min· ·
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-05-11

  • Submissions: Accepted ×3 → Runtime Error → Accepted ×2

Approach
#

Try haystack[i:i + m] == needle at every start i (String Template 2), with starts up to n - m. In an interview present this O(nm) approach first and mention KMP’s O(n + m) if needed. Python’s str.find returns -1 when not found, exactly as required; str.index raises ValueError.

My Attempts
#

Earlier submissions used the built-in in plus index. One in 2022-10 called only haystack.index(needle), which raises ValueError when not found.

Solution
#

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

Complexity
#

Time O(nm), space O(m) (slicing).

Mistakes to Avoid
#

  • There are n - m + 1 starting positions.
  • With built-ins, index raises when not found; use find.

Interview Explanation
#

I try needle at every possible start and return the first match, or -1, in O(nm); for better bounds KMP precomputes needle’s failure function for O(n + m).

Related

LeetCode 27: Remove Element
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 27 note: the write pointer copies only values not equal to val, returning how many were written
LeetCode 58: Length of Last Word
·1 min
LeetCode Easy String
LeetCode 58 note: split() with no argument ignores trailing spaces; return the length of the last word
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 26: Remove Duplicates from Sorted Array
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 26 note: overwrite in place with a write pointer for the next slot, writing only values different from the last one written
LeetCode 14: Longest Common Prefix
·2 mins
LeetCode Easy Array String Trie
LeetCode 14 note: bound by the shortest string and check each position across all strings; the first mismatch gives the answer’s length
LeetCode 13: Roman to Integer
·1 min
LeetCode Easy Hash-Table Math String
LeetCode 13 note: add each symbol’s value left to right, subtracting instead when it is smaller than the symbol to its right