SDE & MLE Prep

30. Substring with Concatenation of All Words

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)