Substring with Concatenation of All Words

Hard · Sliding Window · String · Hash Table · Sliding Window

Problem

You are given a string s and an array words in which every word has the same length. A concatenation of words is any string made by joining all of the words in some order, each word used exactly as many times as it appears in the array. For words = ["ab", "cd", "ab"], both "abcdab" and "ababcd" are concatenations.

Return every starting index in s where a concatenation of words begins, in any order.

Examples

Input: s = "catdogdogcat", words = ["cat","dog"]
Output: [0,6]

catdog starts at 0 and dogcat at 6. The window at 3 is dogdog, which uses dog twice.

Input: s = "aaaa", words = ["aa","aa"]
Output: [0]

Two copies of aa need all 4 characters, so only the window starting at 0 fits.

Input: s = "abc", words = ["abcd"]
Output: []

The string is shorter than the word.

Constraints

Approaches

Follow-up

With w = 1 this is "find all anagrams of a pattern", a plain character window. If the words had different lengths the alignment trick breaks and the problem becomes a search over ways to cut the string, much like word break.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…