Substring with Concatenation of All Words

Find all start indices where s contains a concatenation of every word in `words` in any order.

Hard
Time O(n * w) Space O(m * w)
LeetCode
6 min read
sliding-window hash-map string

Problem#

words are all the same length w. Find every index i such that s.substr(i, m*w) is a concatenation of all of words in some order.

Examples#

  • s = "barfoothefoobarman", words = ["foo","bar"][0,9]

Constraints#

  • 1 <= words.length, w <= 30, 1 <= s.length <= 10^4.

Hints#

Hint 1
Group alignment offsets by i mod w; within each offset run a word-level sliding window.

Approach#

Bucket the search by start-modulo-w: in each offset, slide a window of m word-slots. Maintain frequency counts of seen words; on mismatch (extra word or unseen word) advance the window by one word.

Solution#

Substring with Concatenation of All Words
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
const int m = words.size(), w = words[0].size();
const int totalLen = m * w;
vector<int> ans;
if ((int)s.size() < totalLen) return ans;
unordered_map<string,int> need;
for (auto& wd : words) ++need[wd];
for (int offset = 0; offset < w; ++offset) {
int left = offset, count = 0;
unordered_map<string,int> have;
for (int right = offset; right + w <= (int)s.size(); right += w) {
string token = s.substr(right, w);
if (!need.count(token)) {
have.clear(); count = 0; left = right + w;
continue;
}
++have[token]; ++count;
while (have[token] > need[token]) {
--have[s.substr(left, w)];
--count;
left += w;
}
if (count == m) {
ans.push_back(left);
--have[s.substr(left, w)];
--count;
left += w;
}
}
}
return ans;
}
};

Editorial#

The word-aligned sliding window beats a naïve substring-by-substring check by a factor of w. Three loop bodies: unknown word → reset; surplus copy → shrink left; full match → record and shift. Each s.substr(_, w) call costs O(w); for tighter performance switch to integer hashes of the words.

Complexity#

  • Time: O(n × w).
  • Space: O(m × w).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.