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 WordsInput:s = "barfoothefoobarman""foo""bar"Process: Find concatenationsPosition 0: barfooPosition 9: foobarOutput:[0, 9]Both positions contain exactly one "foo" and one "bar"
Understanding the Visualization
1
Input
String s and array of words (all same length)
2
Process
Find all substrings that contain exact concatenation of words
3
Output
Array of starting indices where concatenations exist
Key Takeaway
🎯 Key Insight: Use hash map frequency counting with sliding window instead of generating all permutations
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