30. Substring with Concatenation of All Words
Asked at 10Bloomberg39Amazon37Google34Microsoft33Meta24Apple22Samsung95Texas Instruments88eBay53Infosys30
Problem
words are strings of equal length. Return every start index in s of a substring that is some concatenation of all the words, each used exactly once, in any order.
Example: s = "barfoothefoobarman", words = ["foo","bar"] → [0,9]
Constraints: length of s ≤ 10⁴; up to 5000 words of length ≤ 30.
All words have length L. For each of the L offsets, slide a window word by word, counting words; when a word is over-used, drop words from the left. A window with exactly len(words) words is a match.
Complexity: O(L · n).
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
L, k = len(words[0]), len(words)
need = Counter(words)
res = []
for off in range(L):
l, cnt, used = off, defaultdict(int), 0
for r in range(off, len(s) - L + 1, L):
w = s[r:r + L]
if w not in need:
l, cnt, used = r + L, defaultdict(int), 0
continue
cnt[w] += 1
used += 1
while cnt[w] > need[w]:
cnt[s[l:l + L]] -= 1
used -= 1
l += L
if used == k:
res.append(l)
return sorted(res)
assert sorted(Solution().findSubstring("barfoothefoobarman", ["foo", "bar"])) == sorted([0, 9])
assert sorted(Solution().findSubstring("wordgoodgoodgoodbestword", ["word", "good", "best", "word"])) == sorted([])
assert sorted(Solution().findSubstring("barfoofoobarthefoobarman", ["bar", "foo", "the"])) == sorted([6, 9, 12])
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
int L = words[0].length(), k = words.length;
Map<String, Integer> need = new HashMap<>();
for (String w : words) need.merge(w, 1, Integer::sum);
List<Integer> res = new ArrayList<>();
for (int off = 0; off < L; off++) {
Map<String, Integer> cnt = new HashMap<>();
int l = off, used = 0;
for (int r = off; r + L <= s.length(); r += L) {
String w = s.substring(r, r + L);
if (!need.containsKey(w)) { cnt.clear(); used = 0; l = r + L; continue; }
cnt.merge(w, 1, Integer::sum);
used++;
while (cnt.get(w) > need.get(w)) {
cnt.merge(s.substring(l, l + L), -1, Integer::sum);
used--;
l += L;
}
if (used == k) res.add(l);
}
}
Collections.sort(res);
return res;
}
}
func findSubstring(s string, words []string) []int {
L, k := len(words[0]), len(words)
need := map[string]int{}
for _, w := range words {
need[w]++
}
res := []int{}
for off := 0; off < L; off++ { // one sliding window per alignment
l, used := off, 0
cnt := map[string]int{}
for r := off; r+L <= len(s); r += L {
w := s[r : r+L]
if need[w] == 0 {
l, used, cnt = r+L, 0, map[string]int{}
continue
}
cnt[w]++
used++
for cnt[w] > need[w] {
cnt[s[l:l+L]]--
used--
l += L
}
if used == k {
res = append(res, l)
}
}
}
sort.Ints(res)
return res
}