Substring with Concatenation of All Words - Problem

You are given a string s and an array of strings words. All the strings of words are of the same length.

A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated.

For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", and "efcdab" are all concatenated strings. "acdbef" is not a concatenated string because it is not the concatenation of any permutation of words.

Return an array of the starting indices of all the concatenated substrings in s. You can return the answer in any order.

Input & Output

Example 1 — Basic Concatenation
$ Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
💡 Note: Position 0: "barfoo" = "bar" + "foo". Position 9: "foobar" = "foo" + "bar". Both are valid concatenations.
Example 2 — No Matches
$ Input: s = "wordgoodgoodgoodword", words = ["word","good","best","good"]
Output: []
💡 Note: No substring of length 16 contains exactly the words ["word","good","best","good"] in any order.
Example 3 — Multiple Matches
$ Input: s = "barfoobar", words = ["bar","foo"]
Output: [0,3]
💡 Note: Position 0: "barfoo", Position 3: "foobar". Both contain exactly one "bar" and one "foo".

Constraints

  • 1 ≤ s.length ≤ 104
  • 1 ≤ words.length ≤ 5000
  • 1 ≤ words[i].length ≤ 30
  • s and words[i] consist of lowercase English letters

Visualization

Tap to expand
Substring with Concatenation of All Words INPUT String s: b a r f o o t h e f o o b a r m a n 0 3 6 9 12 15 words array: "foo" "bar" Word Length: 3 Total Length: 6 Window Size = 2 x 3 = 6 barfoo or foobar ALGORITHM STEPS 1 Build Word Map Count frequency of each word foo: 1 bar: 1 2 Slide Windows Start at indices 0, 1, 2 i=0 i=1 i=2 3 Match Words Check each word-sized chunk "bar" at 0 --OK "foo" at 3 --OK Match! 4 Expand/Contract Move window by word length Window slides: 0--6, 3--9, 6--12... Found at index 9: "foobar" FINAL RESULT Found Concatenated Substrings: Index 0: "barfoo" bar foo OK Index 9: "foobar" foo bar OK Output: [0, 9] Both permutations found: "bar"+"foo" and "foo"+"bar" Time: O(n * m) | Space: O(m) Key Insight: The optimized sliding window runs wordLen separate scans. Each scan starts at offset 0, 1, ..., wordLen-1 and slides by wordLen at each step. This ensures we check all possible starting positions while reusing the word frequency map, avoiding redundant substring extraction and comparison. TutorialsPoint - Substring with Concatenation of All Words | Optimized Sliding Window
Asked in
Amazon 45 Google 38 Facebook 32 Microsoft 28
85.0K Views
Medium Frequency
~35 min Avg. Time
2.8K 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