Ctrl K

Word Blocks in Any Order

Hard
You are given a string text and a list blocks of strings that all have the **same** length (the list may contain repeats). Find every position in text where a fragment begins that is made of all the blocks written back to back in some order: each block used exactly as many times as it appears in blocks, with nothing in between. Return the 0-based starting indices of such fragments in any order.
Example 1
text="catdogcatcow", blocks=["cat", "dog"] → [0, 3]

Index 0 reads catdog and index 3 reads dogcat, both glued from cat and dog. Index 6 reads catcow, which does not fit.

Example 2
text="abbaab", blocks=["ab", "ba"] → [0, 2]

abba at index 0 and baab at index 2 fit, while bbaa at index 1 does not.

Example 3
text="aaaa", blocks=["aa", "aa", "aa"] → []

Three two-letter blocks take 6 characters, and the string is shorter.

Constraints
  • 1 ≤ len(text) ≤ 10⁴
  • 1 ≤ len(blocks) ≤ 5000
  • 1 ≤ len(blocks[i]) ≤ 30, all blocks have the same length
  • text and blocks[i] consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShortest Covering Window HardLongest Clean Stretch HardEven Stretches Without Jumps HardWindows Covering a Letter Set: Large Input HardA Letter Reaches k Repeats: Large Input Hard
loading Python…
Input
text="catdogcatcow", blocks=["cat", "dog"]
Expected
[0, 3]

Run checks the first 3 tests in your browser. Submit checks all 59 tests on the server, hidden ones included.