← Questions
Count distinct values in a sorted array with few distinct values
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Mar 2026. It tests binary-search and divide and conquer.
You get a sorted (non-decreasing) integer array that can be very long but holds only a handful of distinct values. Return how many distinct values it contains, using fewer than O(n) operations when the number of distinct values k is small.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
count_distinct(nums: list[int]) -> int— the number of distinct values;0for an empty array.
Example
count_distinct([1, 1, 1, 2, 2, 5, 5, 5, 5]) -> 3
count_distinct([7, 7, 7, 7, 7, 7, 7, 7, 7]) -> 1
count_distinct([]) -> 0
Constraints
-
0 <= len(nums) <= 200,000;-10^9 <= nums[i] <= 10^9. -
numsis sorted in non-decreasing order. - Target
O(k log n)time andO(1)extra space, wherekis the number of distinct values.
Clarifying questions
- Is the array really sorted, and ascending or descending?
- Roughly how many distinct values should I expect compared with
n? That decides whether the jump is worth it. - Do I only need the count, or the distinct values and their frequencies too?
- Can the array be empty?
What a strong answer covers
- The linear scan first (count positions where
nums[i] != nums[i-1]), then why equal values form contiguous blocks. - From the start of each block, an upper-bound binary search (or galloping: probe 1, 2, 4, ... steps, then binary search) to land on the next block, for
O(k log n)overall. - When the jump loses: with
kclose tonthe plain scan is faster, and galloping keeps the cost nearO(k log(n/k)). - A divide-and-conquer alternative: if
nums[lo] == nums[hi]the whole range is one value, otherwise split. - Tests: empty, one element, all equal, all distinct, negative values.
Follow-ups
- Return each distinct value with its count.
- The array is too large for memory and you can only read positions through a slow
get(i)call. How many calls do you make? - The array is unsorted but still has few distinct values. What is the best you can do?
Where it's asked
- Meta · AI-enabled coding · Last asked Mar 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
binary-search · divide and conquer
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
