Substring with Concatenation of All Words — LeetCode 30 Python Solution
HardHash TableStringSliding Window
- Problem
- #30
- Pattern
- Sliding Window
- Reading time
- 4 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times k) |
| Space | O(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
LeetCode 3Longest Substring Without Repeating CharactersMediumLeetCode 76Minimum Window SubstringHardLeetCode 187Repeated DNA SequencesMediumLeetCode 395Longest Substring with At Least K Repeating CharactersMediumLeetCode 424Longest Repeating Character ReplacementMediumLeetCode 438Find All Anagrams in a StringMedium
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.