</>EmbeddedInterview
← All problems · Arrays & Searching

Count Occurrences of Each Element in a Sorted Array

Easy

Given a sorted array, write one value/count record per distinct element to a separate output array of capacity n. Return the number of records. Implement size_t frequencies(const int *a, size_t n, struct frequency *out).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Equal elements form consecutive runs.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
struct frequency { int value; size_t count; };
size_t frequencies(const int *a, size_t n, struct frequency *out)
{
    size_t k=0;
    for(size_t i=0;i<n;){
        size_t j=i+1;
        while(j<n && a[j]==a[i])++j;
        out[k++]=(struct frequency){a[i],j-i}; i=j;
    }
    return k;
}

Scan each run once, recording its value and length. Time O(n), excluding the caller's output storage, extra space O(1).

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    int a[]={10,10,10,10,30,30}, b[]={-1,3,9}; struct frequency out[6];
    CHECK(frequencies(a,6,out)==2 && out[0].value==10 && out[0].count==4 && out[1].value==30 && out[1].count==2);
    CHECK(frequencies(b,3,out)==3 && out[2].value==9 && out[2].count==1);
    CHECK(frequencies(NULL,0,NULL)==0);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}