Second largest number

Return the second largest DIFFERENT number in nums. If there is none (one number, or all the same), return None in Python or null in JavaScript.

Write second_largest(nums) in Python, secondLargest(nums) in JavaScript or TypeScript, or int second_largest(int nums[], int n) in C. Level: Medium.

Examples

Input: nums = [3, 7, 2, 9, 4]
Output: 7
Input: nums = [5, 5, 3]
Output: 3
  • 1 ≤ length of nums ≤ 1000
  • In [5, 5, 3] the answer is 3, not 5

Hint

Keep two variables, first and second, both starting as None / null. A number bigger than first pushes first down into second; a number between them (and not equal to first) becomes second.

The approach, step by step

  1. first = none, second = none
  2. More numbers?
  3. x = next number
  4. first is none or x > first?
  5. second = first, first = x
  6. x ≠ first and (second is none or x > second)?
  7. second = x
  8. Return second

← All practice problems

Try AI Flowchart free →