30. Substring with Concatenation of All Words ๐
Difficulty: Hard
- Tags: String
, Hash Table
, Sliding Window
Problem Statement ๐
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.
Examples ๐
๐น Example 1:
Input:
Output:
Explanation:
The substring starting at 0 is "barfoo". It is the concatenation of
["bar","foo"]
which is a permutation ofwords
.The substring starting at 9 is "foobar". It is the concatenation of
["foo","bar"]
which is a permutation ofwords
.
๐น 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"]
.
Constraints โ๏ธ
1 <= s.length <= 10^4
1 <= words.length <= 5000
1 <= words[i].length <= 30
s
andwords[i]
consist of lowercase English letters.
Solution ๐ก
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 inwords
.
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.
Java Solution
Time Complexity โณ
O(N * M): Where
N
is the length ofs
andM
is the total length of the words inwords
. We check each possible substring of lengthtotalLength
ins
.
Space Complexity ๐พ
O(W): Where
W
is the number of unique words inwords
, for storing them inwordCount
andseenWords
hash maps.
You can find the full solution here and another solution here but it Time Limit Exceeded ๐ข.
Last updated