Find the First Substring Occurrence
Updated
Problem statement
Given two nonempty lowercase strings haystack and needle, return the zero-based starting index of the first complete occurrence of needle in haystack. Return -1 if no complete occurrence exists.
Occurrences may overlap. An occurrence must match every character of needle in order.
Function
findFirstOccurrence(haystack: String, needle: String) → intExamples
Example 1
haystack = "abababac"needle = "ababac"return = 2The prefix at index 0 differs before the needle ends; the complete match starts at index 2.
Example 2
haystack = "mississippi"needle = "issi"return = 1The first complete issi begins at index 1.
Example 3
haystack = "aaaaa"needle = "bba"return = -1No starting position matches the complete needle.
Constraints
1 <= haystack.length, needle.length <= 10000.- Both strings contain only lowercase English letters.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Classify Password StrengthHackerRank · OA · PHONE SCREEN · ONSITE INTERVIEW
- Highest Bid Campaign MatcherStackAdapt · ONSITE INTERVIEW
- Rank Word-Translation Hints from Sentence TranslationsDuolingo · PHONE SCREEN · ONSITE INTERVIEW
- Group AnagramsAmazon Web Services · ONSITE INTERVIEW
- Query Log MatchDatadog · PHONE SCREEN · ONSITE INTERVIEW
- Response Time Stats by URL PatternGusto · ONSITE INTERVIEW
- File System Shell CommandsHarvey · ONSITE INTERVIEW
- Invoice / Payment ReconciliationStripe · PHONE SCREEN · ONSITE INTERVIEW
- Most Frequent Call Path From Function Trace LogsRoblox · PHONE SCREEN · ONSITE INTERVIEW
- Shortest Uncommon SubstringAirbnb · ONSITE INTERVIEW