Ctrl K

Median of Window Variety

Hard
You are given an array values. For every contiguous subarray values[i..j] (0 ≤ i ≤ j < len(values)), count how many distinct numbers it contains. Write all these counts down and sort them in non-decreasing order. Return the median of that list. If its length is even and there are two middle elements, take the smaller one.
Example 1
values=[7, 7, 2] → 1

The six subarrays give distinct counts 1, 1, 1, 1, 2, 2. The two middle ones, third and fourth, are both 1.

Example 2
values=[1, 2, 1, 3] → 2

Sorted counts: 1, 1, 1, 1, 2, 2, 2, 2, 3, 3. The middle ones, fifth and sixth, are both 2.

Example 3
values=[9] → 1
Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Run With No Gaps HardTwo Separate Segments With a Given Sum MediumTrim the Ends to a Target MediumSame-Value Run After Removals MediumMoving Window Median Hard
loading Python…
Input
values=[7, 7, 2]
Expected
1

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