As reported: Verizon SDE 2, Embedded Software Developer (C/C++), 2025, round 2: implement KMP — a brute-force approach, a better one, and KMP — with the time and space complexity of each.
This is LeetCode 28 — Find the Index of the First Occurrence in a String. Our write-up: /implement-strstr.
Given two strings haystack and needle, return the index of the first occurrence of needle in haystack, or -1 if needle does not occur. An empty needle matches at index 0.
Implement it three ways — brute force, an improved version, and Knuth–Morris–Pratt (KMP) — and give the time and space complexity of each.
Example 1
haystack = "hello", needle = "ll"
Output: 2
Example 2
haystack = "aaaaa", needle = "bba"
Output: -1
Example 3
haystack = "mississippi", needle = "issip"
Output: 4
Constraints: 0 <= haystack.length, needle.length <= 10^5; both contain only lowercase English letters.
Code runner format: two JSON strings, one per line: haystack, then needle. Implement strStr(haystack, needle) returning an integer. The tests include long, repetitive inputs where only a linear-time algorithm is safe.