Unique Element Count via Binary Search Jumps
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Count unique values in a sorted array by jumping between runs using binary search, achieving sublinear time when diversity is low.
You are given an integer array arranged in nondecreasing order. Your task is to determine how many unique values appear in the array.
Write a function that computes this count efficiently. While a straightforward iteration works correctly, your goal is to exploit the sorted property: design an algorithm that performs well when the diversity of values is much lower than the total length.
Specifically, if the array contains n elements but only k unique values (where k << n), aim for O(k log n) time complexity with O(1) extra space.
Function Signature
def count_unique_values(arr: list[int]) -> int:
...
Constraints
0 <= len(arr) <= 1_000_000arris sorted in nondecreasing order-1_000_000_000 <= arr[i] <= 1_000_000_000
Examples
Example 1
Input: count_unique_values([1, 1, 1, 4, 4, 9, 9, 9, 9])
Output: 3
Example 2
Input: count_unique_values([])
Output: 0
Example 3
Input: count_unique_values([5, 5, 5])
Output: 1
Hints
Hint 1
In a sorted array, identical values always form a contiguous block. Counting unique values is equivalent to counting these blocks.
Hint 2
You can skip over an entire block in one step by finding where the next different value begins. Binary search can locate that boundary efficiently.
Hint 3
Use bisect_right with a starting index parameter to search only the unprocessed portion of the array, avoiding redundant work and achieving O(1) space.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since the array is sorted, all occurrences of any particular value must be adjacent. This means we can think of the array as a sequence of contiguous "runs" where each run contains copies of the same value. The number of unique values equals the number of these runs.
Rather than examining every element, we can jump directly from the beginning of one run to the beginning of the next. For the value at index i, we use binary search to find the first position where a strictly larger value appears. This position marks the start of the next run (or the end of the array if no larger value exists).
The algorithm:
- Initialize a counter to zero and start at index 0
- While the current index is within bounds:
- Increment the counter (we've found a new unique value)
- Use
bisect_rightto find the first index after all copies of the current value - Move to that index
- Return the counter
By passing the current index as the lo parameter to bisect_right, we restrict the search to the remaining portion of the array, avoiding redundant comparisons with elements we've already processed.
Correctness
At each step, we count exactly one unique value and advance to the next distinct value (or reach the end). Since bisect_right(arr, arr[i], i) returns an index strictly greater than i (because arr[i] itself satisfies the equality condition), we always make progress and the loop terminates.
The sorted property guarantees that once we move past all copies of a value, we'll never encounter it again. Therefore, we count each unique value exactly once.
Complexity
Time: O(k log n) where k is the number of unique values and n is the array length. We perform k iterations, each doing a binary search that costs O(log n). When k is small relative to n, this is substantially faster than linear time. In the worst case where all elements are distinct, this becomes O(n log n).
Space: O(1) auxiliary space. We use only a constant number of variables. The bisect_right function operates on the original list without creating copies.
Edge Cases
- Empty array: returns 0 immediately since the loop never executes
- Single element or all identical values: one binary search jumps to the end, returning 1
- All distinct elements: each search advances by one position, still producing the correct count
- Negative numbers and large values: handled correctly since we only perform comparisons
Solution
from bisect import bisect_right
def count_unique_values(arr: list[int]) -> int:
n = len(arr)
i = 0
count = 0
while i < n:
count += 1
i = bisect_right(arr, arr[i], i)
return count