01
02
03
04
05
06
07
08
09
10
11
A
A2Z Sheet

63. Second Largest & The Silver Medalist

Easy
Step 3: Solve Problems on Arrays [Easy -> Medium -> Hard]›Easy

Second Largest & The Silver Medalist

EasyFunction: secondLargestElement()
ASCI Mission Breakdown • Simple as Hell
"Find the second-highest distinct number in an array, or -1 if no second largest exists."
Real-World Metaphor:

Think of an awards podium. You watch runners cross the line. If someone beats the current Gold winner, the old Gold winner drops down to Silver! If someone doesn't beat Gold but beats Silver, they take Silver. If everyone ties, Silver remains unclaimed.

Interactive Visual WalkthroughARRAY-POINTERS
Step 1 / 3
Scores: [1, 2, 4, 7, 7, 5]
1
[0]
2
[1]
Gold
4
[2]
7
[3]
7
[4]
5
[5]
Memory Notepad / State Tracker
Gold:4
Silver:2
Evaluating

1. Track Leaders up to Index 2

Scanning [1, 2, 4]: Gold is 4, Silver is 2.

How to Think About This (Mental Model)

  1. Keep two variables: largest = -Infinity, secondLargest = -Infinity.
  2. For each num in nums: if num > largest, then secondLargest becomes largest, and largest becomes num.
  3. Else if num < largest and num > secondLargest, update secondLargest = num.
  4. Return secondLargest === -Infinity ? -1 : secondLargest.

### The Mission In a championship race, you need to crown both the **Gold Medalist** (the largest distinct number) and the **Silver Medalist** (the second largest distinct number). If all runners recorded the exact same score (e.g. `[10, 10, 10]`), then no distinct second place exists, so return **-1**.

Examples

Example 1
Input: nums = [1,2,3,4,5]
Output: [1,2,3,4,5]

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Topic Tags:
Solve Problems on Arrays [Easy -> Medium -> Hard]EasysecondLargestElement
14px
Ln 1:Col 1
8 lines•124 chars
Spaces: 2•UTF-8
JS(Node v20.12)