Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[Interview question] Find second largest element - Solution/C++

Let coding interview become easy - Find second largest element

Maybe you will face it problem when you have an interview for a job with Tech. company.
The problem is "How to find second largest element?", it seems very easy to get result, but you must propose an efficient approach.

If there is a vector that consists {2, 3, 4, 1, 7, 6, 5}, I delcare two variables as first largest element and second largest element. I initialize variables to INT_MIN. At 13 line, if(input[i]>first) is true, input[i] is largest element and pass it to first after storing a value of first by second. Otherwise, compare input[i] with second, it checks a current value whether it bigger than second or not.

Source code

Version 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <vector>
#include <limits.h>
#include <iostream>

using namespace std;

pair<int, int> findLargest(vector<int> input){
int first = INT_MIN;
int second = INT_MIN;

for(int i = 0; i < input.size(); i++){
if(input[i]>first){
second = first;
first = input[i];
}else if(input[i] > second){
second = input[i];
}
}
return make_pair(first, second);
}

int main()
{
vector<int> arr = {2, 3, 4, 1, 7, 6, 5};
pair<int, int> ans = findLargest(arr);
cout << "The first largest element=" << ans.first << ", the second largest element=" << ans.second << endl;
return 0;
}