Count Distinct Values in a Sorted Array When K Is Small
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Count distinct values in a sorted array efficiently when the number of unique values is much smaller than the array length. The challenge tests adapting complexity to output diversity rather than raw length, meeting an O(k log n) target with constant auxiliary space, and handling empty or uniform arrays.
Read the full Meta Software Engineer interview experience this question came from
Constraints
- 0 <= numbers.length <= 10^6
- -10^9 <= numbers[i] <= 10^9
- numbers is sorted in nondecreasing order (numbers[i] <= numbers[i + 1] for every valid i).
- The returned count is in the range 0 <= answer <= 10^6, so every value and every intermediate index fits comfortably in a 32-bit signed integer; int in Java and C++ is sufficient.
Examples
Input: ([],)
Expected Output: 0
Input: ([7],)
Expected Output: 1
Hints
- The array is sorted, so all copies of a value sit in one contiguous block. Counting distinct values is exactly counting blocks.
- Walking element by element costs O(n) no matter how few blocks there are. If you can jump from the start of a block straight to the start of the next one, the total work becomes proportional to k instead.
- To find where the current block ends without scanning it, probe at offsets 1, 2, 4, 8, ... from the block's start until you overshoot it, then binary search inside the last (at most doubled) window to pin down the exact boundary.