Coder's Cat

2020-02-02

## Challenge description

https://leetcode.com/problems/substring-with-concatenation-of-all-words/

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Explanation: Substrings starting at index 0 and 9 are “barfoo” and “foobar” respectively. The output order does not matter, returning [9,0] is fine too.

Example 2:

## Solution

There are two limitations we need to notice.

• All the words are in the same length

• For the concatenation of words, the order of these words is not important, but each of the words can be used exactly once.

First, we need to find an approach to check whether a substrings(s) meet these two limitations. The naive solution is iterating all the enumerations of concatenation, but this will perform badly.

Instead we check the counts of words in a substring. Suppose a corner case:

The word’s count map is: “a” => 3, so “aaa” is a valid concatenation.

The time complexity: $O(NKlog(L))$, where N is the length of s and K is the length of words, L is the length of each words.

Preparing for an interview? Check out this!

Join my Email List for more insights, It's Free!😋