Ctrl K

Variety in a Sliding Window

Medium
A weather station logged its sensor readings as an integer array values. An analyst looks at them through a window of width width (a run of width consecutive readings) and slides it one position at a time from start to end. Return an array whose i-th element is the number of distinct values in the window values[i..i + width - 1]. There are len(values) - width + 1 windows in total. Recounting every window from scratch is slow; aim for O(n).
Example 1
values=[4, 8, 4, 4, 6, 8], width=3 → [2, 2, 2, 3]

The windows are [4, 8, 4] with 2 distinct values, [8, 4, 4] with 2, [4, 4, 6] with 2 and [4, 6, 8] with 3.

Example 2
values=[9, 9, 9, 2], width=1 → [1, 1, 1, 1]

A window of one element always holds exactly one value.

Example 3
values=[3, 1, 3, 2, 1], width=5 → [3]
Constraints
  • 1 ≤ width ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo-Genre Stretch of a Playlist MediumWindows With an Exact Alarm Count MediumStretches With k Odd Numbers MediumTwo Separate Segments With a Given Sum MediumTrim the Ends to a Target Medium
loading Python…
Input
values=[4, 8, 4, 4, 6, 8], width=3
Expected
[2, 2, 2, 3]

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