FastPrepFind the Index of the First Occurrence in a String

Find the Index of the First Occurrence in a String

Bloomberg LP logoBloomberg LP● EasyNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Return the zero-based index of the first occurrence of needle in haystack. Return -1 when no occurrence exists. An empty needle occurs at index 0.

Function

findFirstOccurrence(haystack: String, needle: String) → int

Examples

Example 1

haystack = "sadbutsad"needle = "sad"return = 0

The first match starts at index 0.

Constraints

  • Both strings contain at most 10^5 lowercase English letters.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int findFirstOccurrence(String haystack, String needle) {
  // Write your code here.
}
haystack"sadbutsad"
needle"sad"
expected0
Checking account…