Substring with Concatenation of All Words

You are given a string `s` and an array `words` whose strings all have the same length. A concatenated substring is a substring of `s` made of every string in `words` exactly once, joined in any order. Return the starting indices of all concatenated substrings in `s`, in any order.

30:00

Substring with Concatenation of All Words
hard
Free written solution
Topics
Companies

You are given a string s and an array words whose strings all have the same length. A concatenated substring is a substring of s made of every string in words exactly once, joined in any order. Return the starting indices of all concatenated substrings in s, in any order.

Example 1:
Input: {"s":"barfoothefoobarman","words":["foo","bar"]}
Output: [0,9]
Constraints:
  • 1≤s.length≤1041 \leq s.\text{length} \leq 10^4

  • 1≤words.length≤50001 \leq \text{words.length} \leq 5000

  • 1≤words[i].length≤301 \leq \text{words}[i].\text{length} \leq 30

  • s and words[i] consist of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"barfoothefoobarman","words":["foo","bar"]}

Every word has length 3 and there are 2, so a match is 6 characters long. Tally how many of each word we need.

s in 3-letter chunks

lane 0
lane 1
lane 2
b
a
r

0

f
o
o

3

t
h
e

6

f
o
o

9

b
a
r

12

m
a
n

15

window

chunk just read

dropped

not a word

word bag: in window / needed

count 0 / 2

foo

0/1

bar

0/1

answers

[]

Variables
VariableValue
off0
left-1
right-1
count0
res[]
DepthFunction Call
Stack empty
0/24