data-structures · beginner · ~15 min

Count distinct ints in a sorted array

Single-pass linear scan with state.

Challenge

Count how many distinct values appear in a sorted array.

Task

Implement size_t count_distinct_sorted(const int *a, size_t n) that returns the number of distinct values in a. The array is sorted in non-decreasing order, so equal values are adjacent.

Input

  • a: array of n ints sorted in non-decreasing order (read-only).
  • n: the number of elements (may be 0).

Output

size_t: the count of distinct values.

Example

{1,1,2,3,3,3,4}   ->   4
{5}               ->   1
{}                ->   0

Edge cases

  • An empty array returns 0.
  • All-equal elements count as 1 distinct value.

Input format

a: n ints sorted non-decreasing; n: element count (may be 0).

Output format

size_t: number of distinct values.

Constraints

Single pass; rely on the sorted order (equal values are adjacent).

Starter code

#include <stddef.h>
size_t count_distinct_sorted(const int *a, size_t n) { /* TODO */ return 0; }

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.