FastPrepFind the First Substring Occurrence

Find the First Substring Occurrence

Google logoGoogle● MediumFULLTIMEONSITE INTERVIEW
Learn

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

See Google hiring insights
public int findFirstOccurrence(String haystack, String needle) {
    // Write your code here.
}
haystack"abababac"
needle"ababac"
expected2
Checking account…