Substring with Concatenation of All Words

Hard#30fixed size

You get a string s and a list of words, all of the same length. Find every index in s where all the words stand one after another, each used once, in any order. Our example: s = "stobeabeto", words = ["to", "be"] — the answer is [6, 1]: "beto" at 6 and "tobe" at 1.

input
s: a string; words: an array of strings of the same length, repeats allowed.
returns
Every index i from which s holds all of words one right after another, in some order, each as many times as it is in words. In any order; [] if there is none.
constraints
  • 1 ≤ s.length ≤ 5000
  • 1 ≤ words.length ≤ 500
  • 1 ≤ words[i].length ≤ 30
  • all words have the same length
  • s, words[i]: lowercase English letters
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string} s
 * @param {string[]} words
 * @return {number[]}
 */
function findSubstring(s, words) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more sliding window problems

Pattern “Sliding window” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.