KatInterview

Unique Element Count in Sorted Array with Binary Search

Heaps, Sorting & SearchAuto-graded · 24 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraysoptimization

Last 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 n can 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.