Unique Element Count in Sorted Array with Binary Search
Heaps, Sorting & SearchAuto-graded · 24 test casesLast updated
Tests efficient counting of distinct values in a sorted array using binary search to skip duplicate runs, achieving better than linear time complexity.
You are given a sorted array arr containing integers. Your task is to determine how many distinct values appear in the array.
Because the array may be extremely large (potentially billions of elements), a simple linear scan that examines every element would be too slow. Instead, you should leverage the sorted property to design a more efficient algorithm.
Write a function that counts the number of unique values in the array using an approach that performs better than O(n) when many duplicate values are present.
Constraints
- The array length
ncan be up to 10^9 - The array supports O(1) random access by index
- The array is sorted in non-decreasing order
- Your solution should use O(1) auxiliary space
- Aim for time complexity better than O(n) when the number of distinct values is much smaller than n
Notes
- An empty array contains 0 distinct values
- An array where all elements are identical contains 1 distinct value
- The integers in the array can be any valid integer values (negative, zero, or positive)
Examples
Example 1
Input: count_unique_values([1, 1, 1, 2, 2, 5, 5, 5, 5, 8])
Output: 4
Example 2
Input: count_unique_values([])
Output: 0
Example 3
Input: count_unique_values([7, 7, 7])
Output: 1
Example 4
Input: count_unique_values([1, 2, 3])
Output: 3
Hints
Hint 1
In a sorted array, all occurrences of the same value form a contiguous block. How many such blocks are there?
Hint 2
You can use binary search to quickly find where one value's block ends and the next begins, rather than checking every element.
Hint 3
Consider exponential search (doubling the step size) to find the boundary, then refine with binary search. This makes the cost proportional to the run length rather than the entire array size.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that in a sorted array, all identical values appear consecutively in a single contiguous segment. The number of distinct values equals the number of such segments.
Rather than examining every element linearly, we can jump from the end of one segment directly to the start of the next. To find where a segment ends, we use a two-phase search strategy:
-
Exponential Search Phase: Starting from the current position, probe indices at exponentially increasing distances (current+1, current+2, current+4, current+8, ...) until we find an index with a different value or reach the array's end. This quickly brackets the segment boundary.
-
Binary Search Phase: Once we've found an interval containing the boundary, use binary search to pinpoint exactly where the current value's segment ends and the next value begins.
This galloping approach ensures that finding a segment of length r costs only O(log r) operations, not O(r) as in a linear scan.
Correctness
Each iteration of the main loop:
- Counts the current distinct value exactly once
- Uses binary search invariants to locate the first index where the value changes
- Jumps to that position to begin processing the next distinct value
Since the array is sorted, no value can reappear after its segment ends, so every distinct value is counted exactly once.
Complexity
-
Time: O(d × log(n/d)) where d is the number of distinct values. In the worst case when all elements are unique, this becomes O(n), matching a linear scan. When d << n (many duplicates), this is significantly faster than O(n).
-
Space: O(1) auxiliary space beyond the input array
Solution Code
from typing import List
def count_unique_values(arr: List[int]) -> int:
n = len(arr)
if n == 0:
return 0
count = 0
i = 0
while i < n:
current_val = arr[i]
count += 1
# Use exponential search to find approximate boundary
lo, step = i, 1
hi = i + 1
while hi < n and arr[hi] == current_val:
lo = hi
step *= 2
hi = min(i + step, n)
# Binary search to find exact first position after current_val
while lo + 1 < hi:
mid = (lo + hi) // 2
if arr[mid] == current_val:
lo = mid
else:
hi = mid
i = hi
return count