</>EmbeddedInterview
← All problems · Arrays & Searching

Find Leaders in an Array

Easy

A leader is strictly greater than every element to its right; the last element is always a leader. Write leaders in right-to-left discovery order to a separate output array with capacity n. Return the count. Implement size_t leaders(const int *a, size_t n, int *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.

Scan from the right while tracking the largest value seen.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>

size_t leaders(const int *a, size_t n, int *out)
{
    if(!n)return 0;
    int max=a[n-1]; size_t k=0;
    out[k++]=max;
    for(size_t i=n-1;i>0;){--i;if(a[i]>max){max=a[i];out[k++]=max;}}
    return k;
}

Each new strict maximum is a leader. This matches the right-to-left order of the supplied exercise.

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[]={7,10,4,3,6,5,2}, b[]={-3,-1,-1}, c[]={3,2,1}, out[7];
    CHECK(leaders(a,7,out)==4 && out[0]==2 && out[1]==5 && out[2]==6 && out[3]==10);
    CHECK(leaders(b,3,out)==1 && out[0]==-1);
    CHECK(leaders(c,3,out)==3 && out[2]==3);
    CHECK(leaders(NULL,0,NULL)==0);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}