Find the Median of the Uniqueness Array - Problem
You are given an integer array nums. The uniqueness array of nums is the sorted 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 subarray 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 array when it is sorted in non-decreasing order. If there are two choices for a median, the smaller of the two values is taken.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,1,3]
›
Output:
2
💡 Note:
All subarrays: [1]=1, [1,2]=2, [1,2,1]=2, [1,2,1,3]=3, [2]=1, [2,1]=2, [2,1,3]=3, [1]=1, [1,3]=2, [3]=1. Uniqueness array: [1,1,1,1,2,2,2,2,3,3]. Median is 2.
Example 2 — All Same Elements
$
Input:
nums = [3,3,3]
›
Output:
1
💡 Note:
All subarrays: [3]=1, [3,3]=1, [3,3,3]=1, [3]=1, [3,3]=1, [3]=1. Uniqueness array: [1,1,1,1,1,1]. Median is 1.
Example 3 — All Different Elements
$
Input:
nums = [1,2,3]
›
Output:
2
💡 Note:
All subarrays: [1]=1, [1,2]=2, [1,2,3]=3, [2]=1, [2,3]=2, [3]=1. Uniqueness array: [1,1,1,2,2,3]. Median is 2.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given integer array [1,2,1,3]
2
Generate Uniqueness
Count distinct elements in all subarrays
3
Find Median
Sort uniqueness array and return median
Key Takeaway
🎯 Key Insight: Binary search on the median value is more efficient than generating all uniqueness counts
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code