30. Substring with Concatenation of All Words
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find all starting indices of substrings in a given string s that are a concatenation of all words from a given array words. All words in words have the same length. A key observation is that the order of words in the concatenation doesn't matter, which means we are looking for permutations. However, generating all permutations of words would be computationally expensive (O(numWords!)) and lead to a timeout.
Solution
Substring with Concatenation of All Words in Python
from collections import Counter
class Solution:
def findSubstring(self, s: str, words: list[str]) -> list[int]:
if not s or not words:
return []
word_len = len(words[0])
num_words = len(words)
total_len = word_len * num_words
result = []
if len(s) < total_len:
return []
word_count = Counter(words)
# Iterate over each possible starting offset
for i in range(word_len):
left = i
count = 0
seen_words = Counter()
# Use a sliding window
for j in range(i, len(s) - word_len + 1, word_len):
word = s[j:j + word_len]
if word in word_count:
seen_words[word] += 1
count += 1
# If a word is seen more than required, shrink window from left
while seen_words[word] > word_count[word]:
left_word = s[left:left + word_len]
seen_words[left_word] -= 1
count -= 1
left += word_len
# If a valid concatenation is found
if count == num_words:
result.append(left)
# Slide window forward to find next possible match
left_word = s[left:left + word_len]
seen_words[left_word] -= 1
count -= 1
left += word_len
else:
# Invalid word, reset the window
seen_words.clear()
count = 0
left = j + word_len
return result
Substring with Concatenation of All Words in Java
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> result = new ArrayList<>();
if (s == null || s.length() == 0 || words == null || words.length == 0) {
return result;
}
int wordLen = words[0].length();
int numWords = words.length;
int totalLen = wordLen * numWords;
if (s.length() < totalLen) {
return result;
}
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
// Iterate over each possible starting offset
for (int i = 0; i < wordLen; i++) {
int left = i;
int count = 0;
Map<String, Integer> seenWords = new HashMap<>();
// Use a sliding window
for (int j = i; j <= s.length() - wordLen; j += wordLen) {
String word = s.substring(j, j + wordLen);
if (wordCount.containsKey(word)) {
seenWords.put(word, seenWords.getOrDefault(word, 0) + 1);
count++;
// If a word is seen more than required, shrink window from left
while (seenWords.get(word) > wordCount.get(word)) {
String leftWord = s.substring(left, left + wordLen);
seenWords.put(leftWord, seenWords.get(leftWord) - 1);
count--;
left += wordLen;
}
// If a valid concatenation is found
if (count == numWords) {
result.add(left);
// Slide window forward to find next possible match
String leftWord = s.substring(left, left + wordLen);
seenWords.put(leftWord, seenWords.get(leftWord) - 1);
count--;
left += wordLen;
}
} else {
// Invalid word, reset the window
seenWords.clear();
count = 0;
left = j + wordLen;
}
}
}
return result;
}
}
Substring with Concatenation of All Words in C++
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
if (s.empty() || words.empty()) {
return {};
}
int wordLen = words[0].length();
int numWords = words.size();
int totalLen = wordLen * numWords;
vector<int> result;
if (s.length() < totalLen) {
return {};
}
unordered_map<string, int> wordCount;
for (const string& word : words) {
wordCount[word]++;
}
// Iterate over each possible starting offset
for (int i = 0; i < wordLen; ++i) {
int left = i;
int count = 0;
unordered_map<string, int> seenWords;
// Use a sliding window
for (int j = i; j <= (int)s.length() - wordLen; j += wordLen) {
string word = s.substr(j, wordLen);
if (wordCount.count(word)) {
seenWords[word]++;
count++;
// If a word is seen more than required, shrink window from left
while (seenWords[word] > wordCount[word]) {
string leftWord = s.substr(left, wordLen);
seenWords[leftWord]--;
count--;
left += wordLen;
}
// If a valid concatenation is found
if (count == numWords) {
result.push_back(left);
// Slide window forward to find next possible match
string leftWord = s.substr(left, wordLen);
seenWords[leftWord]--;
count--;
left += wordLen;
}
} else {
// Invalid word, reset the window
seenWords.clear();
count = 0;
left = j + wordLen;
}
}
}
return result;
}
};
Substring with Concatenation of All Words in TypeScript
function findSubstring(s: string, words: string[]): number[] {
const result: number[] = [];
if (!s || s.length === 0 || !words || words.length === 0) {
return result;
}
const wordLen = words[0].length;
const numWords = words.length;
const totalLen = wordLen * numWords;
if (s.length < totalLen) {
return result;
}
const wordCount = new Map<string, number>();
for (const word of words) {
wordCount.set(word, (wordCount.get(word) || 0) + 1);
}
// Iterate over each possible starting offset
for (let i = 0; i < wordLen; i++) {
let left = i;
let count = 0;
const seenWords = new Map<string, number>();
// Use a sliding window
for (let j = i; j <= s.length - wordLen; j += wordLen) {
const word = s.substring(j, j + wordLen);
if (wordCount.has(word)) {
seenWords.set(word, (seenWords.get(word) || 0) + 1);
count++;
// If a word is seen more than required, shrink window from left
while ((seenWords.get(word) || 0) > (wordCount.get(word) || 0)) {
const leftWord = s.substring(left, left + wordLen);
seenWords.set(leftWord, (seenWords.get(leftWord) || 0) - 1);
count--;
left += wordLen;
}
// If a valid concatenation is found
if (count === numWords) {
result.push(left);
// Slide window forward to find next possible match
const leftWord = s.substring(left, left + wordLen);
seenWords.set(leftWord, (seenWords.get(leftWord) || 0) - 1);
count--;
left += wordLen;
}
} else {
// Invalid word, reset the window
seenWords.clear();
count = 0;
left = j + wordLen;
}
}
}
return result;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.