#3134
Hard Algorithms Find the median of the uniqueness array
Array Hash Table Binary Search Sliding Window
29.9% acceptance
Feb 24, 2026
176
13
You are given an integer array nums. The uniqueness array of nums is the sort
ed array that contains the number of distinct elements of all the subarrays of nums. In other words, it is a sorted array consisting of distinct(nums[i..j]), for all 0 <= i <= j < nums.length.
Here, distinct(nums[i..j]) denotes the number of distinct elements in the sub
array that starts at index i and ends at index j.
Return the median of the uniqueness array of nums.
Note that the median of an array is defined as the middle element of the arra
y when it is sorted in non-decreasing order. If there are two choices for a median, the smaller of the two values is taken.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn median_of_uniqueness_array(nums: Vec<i32>) -> i32 {
let n = nums.len();
let total = (n as i64) * (n as i64 + 1) / 2;
let target = (total + 1) / 2; // median position (1-indexed)
// count_at_most(k): number of subarrays with <= k distinct elements
let count_at_most = |k: i32| -> i64 {
use std::collections::HashMap;
let mut freq: HashMap<i32, i32> = HashMap::new();
let mut left = 0usize;
let mut distinct = 0i32;
let mut count = 0i64;
for right in 0..n {
let e = freq.entry(nums[right]).or_insert(0);
if *e == 0 { distinct += 1; }
*e += 1;
while distinct > k {
let entry = freq.entry(nums[left]).or_insert(0);
*entry -= 1;
if *entry == 0 { distinct -= 1; }
left += 1;
}
count += (right - left + 1) as i64;
}
count
};
// Binary search: smallest k where count_at_most(k) >= target
let mut lo = 1i32;
let mut hi = n as i32;
while lo < hi {
let mid = lo + (hi - lo) / 2;
if count_at_most(mid) >= target {
hi = mid;
} else {
lo = mid + 1;
}
}
lo
}
}