FastPrepFind the Index of the First Occurrence in a String

Find the Index of the First Occurrence in a String

Kotak Mahindra Bank logoKotak Mahindra Bank● EasyFULLTIMEONSITE 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.

Source note: Author-written prompt excerpt retained for source fidelity.

More Kotak Mahindra Bank problems

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