Second Largest

Practice this coding question on Coding Gurukul.

Problem statement

A sports club records participants’ scores and wants a display for the second distinct score level. Several participants may share the top score, but that does not create a second level. Your task Find the second largest distinct value in the array. If fewer than two distinct values exist, print -1. Important details Duplicates of the largest value must be skipped. Return a value, not a participant index. Scores are positive, so -1 is an unambiguous missing-result marker. Use O(n) time and O(1) auxiliary space by tracking the two best distinct values as you scan. Worked example For scores 12, 35, 1, 10, 35, the largest distinct score is 35 and the next is 12, so print 12.

Input format

The first line contains n. The second line contains n integers.

Output format

Print the second largest distinct value, or -1.

Constraints

1 <= n <= 100000; 1 <= a[i] <= 1000000000.

Sample input

5
12 35 1 10 35

Sample output

12

Sign in to run or submit a solution in C++, Java or Python.

Loading Coding Gurukul…