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.
Example 1:
Input: nums = [1,2,3]
Output: 1
Explanation:
The uniqueness array of nums is [distinct(nums[0..0]), distinct(nums[1..1]), distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]), distinct(nums[0..2])] which is equal to [1, 1, 1, 2, 2, 3]. The uniqueness array has a median of 1. Therefore, the answer is 1.
Example 2:
Input: nums = [3,4,3,4,5]
Output: 2
Explanation:
The uniqueness array of nums is [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]. The uniqueness array has a median of 2. Therefore, the answer is 2.
Example 3:
Input: nums = [4,3,5,4]
Output: 2
Explanation:
The uniqueness array of nums is [1, 1, 1, 1, 2, 2, 2, 3, 3, 3]. The uniqueness array has a median of 2. Therefore, the answer is 2.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 105This approach involves dividing the problem into smaller subproblems, solving each subproblem independently, and combining the results. This is useful for problems that can be broken down recursively.
This C code represents a typical divide and conquer structure, recursively dividing the problem into two halves until a base condition is met, and then combining the solution. This is a generic template and can be adapted for specific problems like merge sort.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n)
Space Complexity: O(log n) due to recursive stack space.
This approach uses an explicit stack to replace the function call stack, providing an iterative solution to problems that are typically solved recursively. It's beneficial in avoiding stack overflow and managing deeper recursion paths.
This C code demonstrates replacing the recursive stack with an explicit stack. We simulate function calls and solve subproblems iteratively, preventing stack overflow on large inputs.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n)
Space Complexity: O(n) for stack usage.
| Approach | Complexity |
|---|---|
| Divide and Conquer | Time Complexity: O(n log n) |
| Iterative Solution With Stack | Time Complexity: O(n log n) |
Binary Search : Median of two sorted arrays of different sizes. • Tushar Roy - Coding Made Simple • 559,976 views views
Watch 9 more video solutions →Practice Find the Median of the Uniqueness Array with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor