Substring with Concatenation of All Words Problem
Description
LeetCode Problem 30.
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.
You can return the answer in any order.
Example 1:
Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
Output: []
Example 3:
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
Output: [6,9,12]
Constraints:
- 1 <= s.length <= 10^4
- s consists of lower-case English letters.
- 1 <= words.length <= 5000
- 1 <= words[i].length <= 30
- words[i] consists of lower-case English letters.
Solution
Approach: Sliding Window Over Words
Checking every start index separately rebuilds a word count each time, which costs O(n · m · L) for m words of length L. A sliding window reuses the work between neighboring windows.
All words have the same length L, so a matching substring is m whole words placed back to back. Any start index i falls into one of L "lanes" by i mod L, and inside a lane we can move through s one word at a time:
- Count the words in
wordsintoneed. - For each
offsetfrom0toL - 1, read the words ofsatoffset,offset + L,offset + 2L, …, keeping a window[left, right)with a countseenof its words. - If the word just read is not in
need, no answer can include it: clear the window and start again right after it. - Otherwise add it. If it now appears more often than
needallows, drop words from the left of the window until it does not. - When the window holds exactly
mwords,leftis an answer. Drop the leftmost word and continue.
The detail that is easy to get wrong is duplicates in words (like ["word","good","best","word"]): compare against counts, not a set, and shrink from the left only until the over-counted word is back within its limit.
Complexity: O(n · L + m · L) time, where n is the length of s, m the number of words and L the word length: each of the L lanes reads every word of s at most twice (once added, once dropped), and slicing or hashing a word costs O(L). O(m · L) space for the two counts.
import collections
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
word_len = len(words[0])
word_count = len(words)
need = collections.Counter(words) # word -> how many times it must appear
result = []
# Every answer starts at some offset 0..word_len-1 and then moves in whole words.
for offset in range(word_len):
left = offset # start of the current window
in_window = 0 # number of words in the window
seen = collections.Counter()
for right in range(offset, len(s) - word_len + 1, word_len):
word = s[right:right + word_len]
if word not in need:
# No valid window can contain this word: restart after it.
seen.clear()
in_window = 0
left = right + word_len
continue
seen[word] += 1
in_window += 1
# Too many copies of this word: drop words from the left until it is fine again.
while seen[word] > need[word]:
seen[s[left:left + word_len]] -= 1
in_window -= 1
left += word_len
if in_window == word_count:
result.append(left)
# Slide on by dropping the first word.
seen[s[left:left + word_len]] -= 1
in_window -= 1
left += word_len
return result