TRT
Sign in
easyAdvancedLeetCode#Rabin-Karp#KMP

Find the first occurrence in a string

Return the first index where a pattern occurs in a text, with Rabin-Karp or KMP in linear time.

The Runtime Theory Team1 min read
Taught inRolling hash and Rabin-KarpPro — members onlyA rolling hash updates the hash of a sliding window in constant time as one character leaves and another enters. Rabin-Karp uses it to compare a pattern against every window of a text, checking characters only when the hashes match.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inhaystack = "sadbutsad", needle = "sad"

out0

inhaystack = "leetcode", needle = "leeto"

out-1

inhaystack = "a", needle = "a"

out0

inhaystack = "mississippi", needle = "issip"

out4

Return the index of the first occurrence of needle in haystack, or -1 if it doesn't occur. Solve it twice: once with a rolling hash and once with the prefix function.

Before you code

The simple search is accepted here, but it is O(n × m) on inputs such as a run of a's searched for aaab. What makes each of the two linear methods immune to that?

Hints

  1. Rabin-Karp: hash the needle and the first window, roll the window, and compare characters only when the hashes match.
  2. KMP: compute the prefix function of the needle, then scan the haystack, falling back through π on a mismatch instead of moving backward.
  3. Test mississippi with issip: the simple search backs up there, and KMP must not lose the match.

Production & complexity notes

When solving Find the first occurrence in a string on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Rolling hash and Rabin-Karp to reinforce the underlying pattern.

What it practices

Linear-time pattern search, from Rolling hash and Rabin-Karp and KMP and prefix functions.

Not started

Sign in to save your learning progress.

Sign in to save