Substring Finder - Problem
Given a main string and a substring, find all starting positions where the substring occurs in the main string.
Return an array of indices representing all positions where the substring begins. If the substring is not found, return an empty array.
Important: You must implement this without using built-in string search functions like indexOf(), find(), or contains().
Example: In string "abcabcabc", substring "abc" appears at positions [0, 3, 6].
Input & Output
Example 1 — Multiple Matches
$
Input:
mainString = "abcabcabc", substring = "abc"
›
Output:
[0,3,6]
💡 Note:
The pattern 'abc' appears at positions 0, 3, and 6 in the main string 'abcabcabc'
Example 2 — Single Match
$
Input:
mainString = "hello world", substring = "world"
›
Output:
[6]
💡 Note:
The pattern 'world' appears only once at position 6 in 'hello world'
Example 3 — No Match
$
Input:
mainString = "programming", substring = "xyz"
›
Output:
[]
💡 Note:
The pattern 'xyz' does not appear anywhere in 'programming', so return empty array
Constraints
- 1 ≤ mainString.length ≤ 104
- 1 ≤ substring.length ≤ 102
- mainString and substring consist of lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code