find-index-first-occurrence-in-string.sh — zsh

Find the Index of the First Occurrence in a String

easy
stringstwo-pointers

Return the zero-based index of the first exact occurrence of sub inside s. Return -1 when it does not occur. By convention, an empty sub matches at index 0.

Input / output

  • Input: s: string, sub: string
  • Output: integer index

Examples

  1. s = "mississippi", sub = "iss" returns 1.
  2. s = "abcdef", sub = "gh" returns -1.

Constraints

  • 0 <= s.length, sub.length <= 100,000
  • Matching is case-sensitive.

Follow-up When would KMP or another linear-time matcher be worth the preprocessing cost over a direct scan?

Examples
Example 1
Input: s = "hello world", sub = "l"
Output: 2
Example 2
Input: s = "abcdefg", sub = "x"
Output: -1
Example 3
Input: s = "mississippi", sub = "iss"
Output: 1
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.