KatInterview

Unique Element Count via Binary Search Jumps

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharrayssorted-array

Last 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_000
  • arr is 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.