Problem 365400 · medium · Level 03 Linear Management & Searching

Scrambled Key Positions

sliding window · fixed-size window · character counts

A secret key may appear inside text with its letters scrambled in any order. Return the list of all start indices i such that text[i:i + len(key)] is a rearrangement of key, in increasing order. Return [] if there are none.

Examples

Input:  text = "stopspotpost", key = "tops"
Output: [0, 1, 4, 7, 8]
Explanation: "stop", "tops", "spot", "tpos" and "post" start at 0, 1, 4, 7 and 8.

Input:  text = "xyxyx", key = "yx"
Output: [0, 1, 2, 3]
Explanation: overlapping blocks count, so every start works.

Constraints

  • 1 <= len(text) <= 10**5, 1 <= len(key) <= 10**5; when key is longer than text the answer is [].
  • Both strings consist of lowercase English letters.
  • Target complexity: O(n) time; sorting or recounting each window is too slow for the largest tests.

Goals

  • Compare letter frequencies of a window with a target in O(1) per step
  • Update a count array as characters enter and leave the window
Starting Python…