InternDoor

The second largest value

Easyarrays

Reported in interviews at (where)

Return the second largest distinct value in nums: the largest value that is strictly smaller than the maximum. If every number in nums is the same, there is no such value; return -1.

Sorting works in O(n log n). Can you do it in one pass?

Example 1
Input
nums = [4,9,2,9,7]
Output
7

The maximum is 9, even though it appears twice. The largest value below it is 7.

Example 2
Input
nums = [5,5]
Output
-1

Every number is 5.

Example 3
Input
nums = [0,3]
Output
0

0 is a real value, smaller than 3.

Limits

  • 1 <= nums.length <= 100000
  • 0 <= nums[i] <= 1000000000

Hints

Hint 1

Keep the largest and second largest seen so far. A new maximum pushes the old one down to second; a value strictly between them becomes the new second.

Where this was reported

Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.

Run your code to check it on the examples. Submit runs every hidden test.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.