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:
firstLargestandsecondLargest. - Ignore duplicates by checking
num !== firstLargestbefore assigningsecondLargest.
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 largest
first = 93Duplicate values are ignored
e.g. 54Second largest
7Explanation
- When a new maximum appears, the old
firstslides down intosecondbeforefirstis updated. - A value between
secondandfirstonly replacessecondif it is not equal tofirst. - If
secondis still-Infinityat 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.