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: 1
💡 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 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Find the Median of the Uniqueness Array INPUT nums = [1, 2, 1, 3] 1 2 1 3 i=0 i=1 i=2 i=3 All Subarrays: [1] --> 1 distinct [2] --> 1 distinct [1] --> 1 distinct [3] --> 1 distinct [1,2] --> 2 distinct [2,1] --> 2 distinct [1,3] --> 2 distinct [1,2,1] --> 2 distinct [2,1,3] --> 3 distinct [1,2,1,3] --> 3 distinct ALGORITHM STEPS 1 Binary Search Setup Search median in range [1, n] 2 Count Subarrays Use sliding window to count subarrays with <= mid distinct 3 Binary Search Check If count >= (total+1)/2 then answer <= mid 4 Find Smallest Valid Return smallest mid where count reaches median pos Uniqueness Array (sorted): 1 1 1 1 2 2 [1,1,1,1,2,2,2,2,3,3] - 10 elements median pos=5 FINAL RESULT Total subarrays: 10 Median position: (10+1)/2 = 5 Median = 2 Verification: Sorted array: [1,1,1,1,2,2,2,2,3,3] Position 5 value = 2 OK - Answer confirmed! Key Insight: Instead of generating all n*(n+1)/2 subarrays and sorting, use binary search on the answer. For each candidate median value, use sliding window to count subarrays with <= that many distinct elements. Time complexity: O(n * log(n)) instead of O(n^2 * log(n)). Space: O(n) for frequency map. TutorialsPoint - Find the Median of the Uniqueness Array | Optimal Solution
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