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
INPUTALGORITHMRESULTMain String:abcabc...Pattern:abcFind all positions wherepattern matches in string1Check Position 0Compare abc vs abc2Move to Position 1Compare bca vs abc3Continue CheckingFind matches at 0, 3, 64Collect ResultsStore all match positionsMatch Positions:[0, 3, 6]Pattern abc found at:• Position 0: abc• Position 3: abc• Position 6: abcKey Insight:Instead of checking every character repeatedly, we can use patternpreprocessing (KMP algorithm) to skip redundant comparisons.TutorialsPoint - Substring Finder | Pattern Matching Algorithm
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
34.2K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen