FastPrepFind the First Substring Occurrence
Problems/Find the First Substring Occurrence

Find the First Substring Occurrence

Google logoGoogle● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The Google MLE onsite report describes a string-search variant, cites LeetCode 28, and suggests KMP or Rabin–Karp. Its variant and the linked forum task are unavailable. This practice implements the baseline first-occurrence task; it does not claim to reproduce the changed interview setup.

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) → int

Examples

Example 1

haystack = "abababac"needle = "ababac"return = 2

The prefix at index 0 differs before the needle ends; the complete match starts at index 2.

Example 2

haystack = "mississippi"needle = "issi"return = 1

The first complete issi begins at index 1.

Example 3

haystack = "aaaaa"needle = "bba"return = -1

No starting position matches the complete needle.

Constraints

  • 1 <= haystack.length, needle.length <= 10000.
  • Both strings contain only lowercase English letters.

More Google problems

  • Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
  • Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
  • 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
All Google interview questionsSee Google hiring insights
Saved
public int findFirstOccurrence(String haystack, String needle) {
    // Write your code here.
}
Checking account…