data-structures · beginner · ~15 min
Single-pass linear scan with state.
Count how many distinct values appear in a sorted array.
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.
a: array of n ints sorted in non-decreasing order (read-only).n: the number of elements (may be 0).size_t: the count of distinct values.
{1,1,2,3,3,3,4} -> 4
{5} -> 1
{} -> 0
a: n ints sorted non-decreasing; n: element count (may be 0).
size_t: number of distinct values.
Single pass; rely on the sorted order (equal values are adjacent).
#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.