Back to Interview Prep

Warm Up · Second Largest

Find the Second Largest Number in an Array

Problem Statement

Write a function secondLargest(arr) that returns the second largest distinct number in an array.

Requirements

  • The array must contain at least two elements.
  • If all elements are equal, return: No second largest found.
  • If the array has fewer than two elements, return: Array should have at least two numbers.

Examples

Input: arr = [0, 3, 5, 2, 7, 9]→Output: 7

Input: arr = [4, 4, 4, 4]→Output: No second largest found

Input: arr = [5]→Output: Array should have at least two numbers

Input: arr = [10, 20]→Output: 10

Approach

  • Check the array length. If there are fewer than 2 elements, return the appropriate message.
  • Use two variables: firstLargest and secondLargest.
  • Ignore duplicates by checking num !== firstLargest before assigning secondLargest.

Time & Space Complexity

Time Complexity: O(n) - single pass through the array.

Space Complexity: O(1) - constant space.

Visualisation

1Start with the array[0, 3, 5, 5, 2, 7, 9]
2Track the first largestfirst = 9
3Duplicate values are ignorede.g. 5
4Second largest7

Explanation

  • When a new maximum appears, the old first slides down into second before first is updated.
  • A value between second and first only replaces second if it is not equal to first.
  • If second is still -Infinity at the end, every element was the same.

Your solution

Solve it in JavaScript and print the answer with console.log(). Run to see your output, then Submit to check it against the test cases.

// Write your solution in JavaScript
// Print the answer with console.log()


Console

No output yet. Use console.log() to print values here.

Write your own solution and press Submit once to unlock the answer.

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in