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
Find the Median of the Uniqueness ArrayStep 1: Input Array1213Step 2: All Subarrays & UniquenessSubarray [1]: 1 distinct → uniqueness = 1Subarray [1,2]: 2 distinct → uniqueness = 2Subarray [1,2,1]: 2 distinct → uniqueness = 2...and 7 more subarraysTotal 10 subarrays with uniqueness:[1,2,2,3,1,2,3,1,2,1]Step 3: Sort & Find MedianSorted: [1,1,1,1,2,2,2,2,3,3]Median (5th element): 2
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
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen