Substring with Concatenation of All Words — LeetCode 30 Python Solution

HardHash TableStringSliding Window
Problem
#30
Reading time
4 min

The problem

You are given a string s and an array of strings words. All the strings of words are of the same length.

Python solution

Python
class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        cnt = Counter(words)
        m, n = len(s), len(words)
        k = len(words[0])
        ans = []
        for i in range(k):
            l = r = i
            cnt1 = Counter()
            while r + k <= m:
                t = s[r : r + k]
                r += k
                if cnt[t] == 0:
                    l = r
                    cnt1.clear()
                    continue
                cnt1[t] += 1
                while cnt1[t] > cnt[t]:
                    rem = s[l : l + k]
                    l += k
                    cnt1[rem] -= 1
                if r - l == n * k:
                    ans.append(l)
        return ans

Complexity

MeasureComplexity
TimeO(m \times k)
SpaceO(n \times k) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 30. Substring with Concatenation of All Words is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 30. Substring with Concatenation of All Words?
LeetCode 30. Substring with Concatenation of All Words is rated Hard on LeetCode.
What is the time complexity of LeetCode 30. Substring with Concatenation of All Words?
The Python solution on this page runs in O(m \times k).
What is the space complexity of LeetCode 30. Substring with Concatenation of All Words?
The Python solution on this page uses O(n \times k) auxiliary space.
What topics does LeetCode 30. Substring with Concatenation of All Words cover?
LeetCode 30. Substring with Concatenation of All Words is tagged Hash Table, String and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview