#3134
Find the Median of the Uniqueness Array
HardArrayHash TableBinary SearchSliding WindowHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log(max(nums))) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log(max(nums)))Space O(n)
The optimal approach uses binary search to find the median directly by counting how many subarrays have distinct counts less than or equal to a given value. This reduces the need to generate all subarrays explicitly.
⚙️
Algorithm
5 steps- 1Step 1: Define a function to count the number of subarrays with distinct elements less than or equal to x.
- 2Step 2: Use binary search on the range of possible distinct counts (from 1 to the maximum element in nums).
- 3Step 3: For each mid value in the binary search, use the counting function to determine if it is the median.
- 4Step 4: Adjust the binary search range based on the count of subarrays compared to the desired median position.
- 5Step 5: Return the median value once found.
solution.py28 lines
1# Full working Python code
2
3def countSubarraysWithDistinctLessEqual(nums, x):
4 count = 0
5 left = 0
6 freq = {}
7 for right in range(len(nums)):
8 freq[nums[right]] = freq.get(nums[right], 0) + 1
9 while len(freq) > x:
10 freq[nums[left]] -= 1
11 if freq[nums[left]] == 0:
12 del freq[nums[left]]
13 left += 1
14 count += right - left + 1
15 return count
16
17
18def findMedian(nums):
19 low, high = 1, max(nums)
20 n = len(nums)
21 total_subarrays = n * (n + 1) // 2
22 while low < high:
23 mid = (low + high) // 2
24 if countSubarraysWithDistinctLessEqual(nums, mid) < (total_subarrays + 1) // 2:
25 low = mid + 1
26 else:
27 high = mid
28 return lowℹ
Complexity note: The time complexity is O(n log(max(nums))) due to the binary search over the range of possible distinct counts and the linear time complexity of counting subarrays with distinct elements.
- 1Understanding how to count distinct elements efficiently is crucial.
- 2Binary search can significantly reduce the time complexity when looking for a median.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.