/28. Find the Index of the First Occurrence in a String

28. Find the Index of the First Occurrence in a String

Easy
Two Pointers46.3% acceptance

Given two strings, source_string and target_substring, return the index of the first occurrence of target_substring in source_string. If target_substring does not occur in source_string, return -1.

Example 1

Input: source_string=abcabcabc, target_substring=bca

Output: 1

Explanation: The substring bca first occurs at index 1.

Example 2

Input: source_string=abcdefgh, target_substring=xyz

Output: -1

Explanation: The substring xyz does not occur in abcdefgh.

Example 3

Input: source_string=mississippi, target_substring=issi

Output: 1

Explanation: The substring issi first occurs at index 1.

Constraints

  • 1 <= len(source_string) <= 104
  • 1 <= len(target_substring) <= 104
  • source_string and target_substring consist only of lowercase English letters
Python (current runtime)

Case 1

Input: source_string='aabbccdd', target_substring='bcc'

Expected: 3

Case 2

Input: source_string='banana', target_substring='ana'

Expected: 1

Case 3

Input: source_string='testcase', target_substring='case'

Expected: 4

Case 4

Input: source_string='abcdefg', target_substring='hij'

Expected: -1

Case 5

Input: source_string='repeatrepeat', target_substring='peat'

Expected: 2