← Questions

Count distinct values in a sorted array with few distinct values

0
MetaCodingLast asked Mar 2026

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; 0 for 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.
  • nums is sorted in non-decreasing order.
  • Target O(k log n) time and O(1) extra space, where k is 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 k close to n the plain scan is faster, and galloping keeps the cost near O(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

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