Educatifu
Open menu

Second Largest

Mediumarrays

Find the second largest distinct value in a list. If there is no such value (fewer than two distinct numbers), print none.

Input

The first line contains an integer n. The second line contains n integers separated by spaces.

Output

The second largest distinct value, or none if it does not exist.

Examples

Example 1

Input
5
3 1 4 1 5
Output
4

Distinct values 5,4,3,1 — the second largest is 4.

Example 2

Input
3
7 7 7
Output
none

Only one distinct value, so none.

Example 3

Input
2
10 20
Output
10

Second largest is 10.

Constraints

  • 1 <= n <= 10^5
  • -10^9 <= each number <= 10^9

Hints

Reveal hint 1

Duplicates should be treated as one value — the second largest of [5, 5, 3] is 3, not 5.

Reveal hint 2

Collect the distinct values, then take the largest and the one just below it. If there is only one distinct value, the answer is none.

Reference solution (spoiler — try it yourself first)

Approach

Reduce to distinct values, sort them descending, and take the element at index 1. If fewer than two distinct values exist, output none.

import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
arr = data[1:1 + n]
uniq = sorted(set(arr), reverse=True)
print(uniq[1] if len(uniq) >= 2 else "none")

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation