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.
words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", and "efcdab" are all concatenated strings. "acdbef" is not a concatenated string because it is not the concatenation of any permutation of words.Return an array of the starting indices of all the concatenated substrings in s. You can return the answer in any order.
Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
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.
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
Output: []
Explanation:
There is no concatenated substring.
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
Output: [6,9,12]
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"].
s and words[i] consist of lowercase English letters.The simplest approach is to generate all possible substrings of the given string s that can be formed with the total length of all the words. For each substring, check if the substring is a valid concatenation of the words in the given word list with the help of permutations. If it is, record the starting index.
substring_length = words.length * word_length.s with length substring_length.O((n - totalLength + 1) * m!), where n is the length of s and m is the number of words. Generating all permutations takes O(m!).O(m!) to store permutations.Instead of generating permutations, we can use a sliding window with the help of a hashmap to keep track of the word count. This allows us to efficiently check if the current sliding window contains a valid concatenation of the words.
wordCount containing the frequency of each word.s in a sliding window where the step is the word length.seenWords to count words in the current window.O(n * word_length), where n is the length of s. The map operations are O(1), and we slide over s word by word.O(m), where m is the number of distinct words.