</>EmbeddedInterview
← All problems · Arrays & Searching

Find the Second Largest Distinct Element

Easy

Find the second largest distinct integer in one pass. Return 1 and write it to out if it exists, otherwise return 0. Assume out is valid. Implement int second_largest(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.

Track the largest and second largest separately.

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

int second_largest(const int *a, size_t n, int *out)
{
    if(!n)return 0;
    int max=a[0], second=0, found=0;
    for(size_t i=1;i<n;++i){
        if(a[i]>max){second=max;max=a[i];found=1;}
        else if(a[i]<max && (!found || a[i]>second)){second=a[i];found=1;}
    }
    if(found)*out=second;
    return found;
}

When a new maximum arrives, the old maximum becomes second largest. A flag handles all-negative values and arrays with no second distinct value.

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