Note that starting from the first letter of s and starting from the second letter are different, so the sliding window algorithm should run words[0].size times.
int word_len = words[0].size(); int num_words = words.size(); int total_len = word_len * num_words; int n = s.size();
unordered_map<string, int> word_count; for (auto &w : words) word_count[w]++;
for (int i = 0; i < word_len; ++i) { // 0..word_len to prevent missing int left = i, right = i; unordered_map<string, int> curr_count;
while (right + word_len <= n) { string word = s.substr(right, word_len); right += word_len; if (word_count.count(word)) { curr_count[word]++; // If a word appears more times than required, the left window needs to be shrunk. while (curr_count[word] > word_count[word]) { string left_word = s.substr(left, word_len); curr_count[left_word]--; left += word_len; } // Check if the window meets the total length. if (right - left == total_len) { result.push_back(left); } } else { // Encounter a word not in words, reset the window. curr_count.clear(); left = right; } } }