HardNo. 0030
Substring with Concatenation of All Words — LeetCode 30 Python Solution
- Pattern
- Sliding Window
- Topics
- Hash Table, String, Sliding Window
- On a study list
- Top Interview 150
- 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
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
- Time
- O(m × k)
- Space · auxiliary
- O(n × k)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0076 | Minimum Window Substring | Hard |
| 0187 | Repeated DNA Sequences | Medium |
| 0395 | Longest Substring with At Least K Repeating Characters | Medium |
| 0424 | Longest Repeating Character Replacement | Medium |
| 0438 | Find All Anagrams in a String | Medium |
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 × k).
- What is the space complexity of LeetCode 30. Substring with Concatenation of All Words?
The Python solution on this page uses O(n × 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.