30. Substring with Concatenation of All Words ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Hard
- Tags: String
, Hash Table
, Sliding Window
You are given a string s
and an array of strings words
. All the strings of words
are of the same length.
A concatenated string is a string that exactly contains all the strings of any permutation of words
concatenated.
Return an array of the starting indices of all the concatenated substrings in s
. You can return the answer in any order.
๐น Example 1:
Input:
Output:
Explanation:
The substring starting at 0 is "barfoo". It is the concatenation of ["bar","foo"]
which is a permutation of words
.
The substring starting at 9 is "foobar". It is the concatenation of ["foo","bar"]
which is a permutation of words
.
๐น Example 2:
Input:
Output:
Explanation: There is no concatenated substring.
๐น Example 3:
Input:
Output:
Explanation:
The substring starting at 6 is "foobarthe". It is the concatenation of ["foo","bar","the"]
.
The substring starting at 9 is "barthefoo". It is the concatenation of ["bar","the","foo"]
.
The substring starting at 12 is "thefoobar". It is the concatenation of ["the","foo","bar"]
.
1 <= s.length <= 10^4
1 <= words.length <= 5000
1 <= words[i].length <= 30
s
and words[i]
consist of lowercase English letters.
To solve this problem, we can use a Sliding Window approach with a Hash Table to keep track of the count of each word in words
.
Calculate Word Lengths:
Since all words in words
are the same length, we can calculate the total length of concatenated words and use it to limit our sliding window.
Create a Dictionary for Words:
Create a wordCount
dictionary to count occurrences of each word in words
.
Slide Over Substrings:
Use a sliding window approach across s
, iterating for each possible starting position to cover all possible concatenations.
For each substring in the current window, check if it matches the count in wordCount
.
Verify and Store Results:
If the substring contains all words with matching frequencies, store the starting index.
O(N * M): Where N
is the length of s
and M
is the total length of the words in words
. We check each possible substring of length totalLength
in s
.
O(W): Where W
is the number of unique words in words
, for storing them in wordCount
and seenWords
hash maps.
You can find the full solution and another solution but it Time Limit Exceeded ๐ข.