🧠 JavaScript Interview Coding Challenge: Find the Second Largest Number in an Array
(Complete Guide, All Methods, Edge Cases, Time Complexity, Best Practices)
📝 Introduction
One of the classic, all-time most popular JavaScript interview coding challenges is:
“Given an array of numbers, find the second largest value.”
Example:
Input: [10, 5, 20, 8, 20]
Output: 20 (if duplicates allowed)
OR
Output: 10 (if unique-only second-largest)
This problem is deceptively simple and tests essential skills:
✅ Array iteration
✅ Comparison logic (greater/less)
✅ Sorting or avoiding sorting
✅ Understanding duplicates
✅ Edge-case handling
✅ Memory/time complexity
✅ Clean, readable code
✅ Communication of algorithmic reasoning
Interviewers love it because it quickly reveals whether a candidate can write robust logic, explain trade-offs, and consider multiple approaches.
This article gives the complete, ultimate, deeply detailed guide to solving this challenge — perfect for interviews and for dominating SEO rankings.
📌 Problem Statement (Core Version)
Write a JavaScript function that returns the second largest number in an array of integers.
Example:
findSecondLargest([3, 1, 4, 7, 9, 2]) → 7
Important Clarification:
Most interviews require one of two interpretations:
✅ Version A — Second Largest (including duplicates)
Example:
[20, 20, 10] → 20 (second occurrence)
✅ Version B — Second Largest Unique Value
Example:
[20, 20, 10] → 10
You should always ask the interviewer which version they expect.
✅ Approach 1 — Simple Sorting (Easy but Often Not Preferred in Interviews)
The most straightforward solution:
Sort the array in descending order, then take the second element.
✅ Code: (Version with duplicates allowed)
function secondLargest(arr) {
const sorted = [...arr].sort((a, b) => b - a);
return sorted[1];
}
console.log(secondLargest([10, 5, 20, 8, 20]));
// Output: 20
✅ Unique-only version:
function secondLargestUnique(arr) {
const sorted = [...new Set(arr)].sort((a, b) => b - a);
return sorted[1];
}
console.log(secondLargestUnique([10, 5, 20, 8, 20]));
// Output: 10
✅ Pros:
- Very easy to write
- Very readable
- Works well for short arrays
❌ Cons:
- Sorting is O(n log n), not optimal
- Interviewers prefer O(n) solutions
- Modifies order unless you clone array
✅ Approach 2 — One-Pass Solution (O(n)): The Interview-Preferred Method
This classic algorithm solves the problem in a single loop, making it O(n) — optimal.
✅ Code (Unique-only version — most common interview requirement)
function secondLargest(arr) {
let max = -Infinity;
let second = -Infinity;
for (let num of arr) {
if (num > max) {
second = max;
max = num;
} else if (num > second && num < max) {
second = num;
}
}
return second;
}
console.log(secondLargest([10, 5, 20, 8, 20]));
// Output: 10
✅ How It Works:
- Keep track of the largest and second largest values.
- Update them dynamically as you iterate.
- Ensure duplicates don’t break the logic.
✅ Complexity:
- Time: O(n)
- Space: O(1) — constant space
✅ Why Interviewers LOVE This:
- Shows algorithmic thinking
- Optimal solution
- Handles duplicates explicitly
- Demonstrates mastery of comparison logic
✅ Approach 3 — Using Set + Math.max (Clean ES6 Solution)
This is an elegant way to handle unique values:
function secondLargest(arr) {
const unique = [...new Set(arr)];
const maxVal = Math.max(...unique);
const uniqueWithoutMax = unique.filter(n => n !== maxVal);
return Math.max(...uniqueWithoutMax);
}
console.log(secondLargest([10, 5, 20, 8, 20]));
// Output: 10
✅ Pros:
- Very readable
- Uses ES6 features
- Automatically removes duplicates
❌ Cons:
- Calls
Math.max()twice (cost: O(n)) - Not optimal but still simple and clear
✅ Approach 4 — Using Reduce (Functional Programming Style)
✅ Code:
function secondLargest(arr) {
return arr.reduce(
(acc, num) => {
let [max, second] = acc;
if (num > max) {
return [num, max];
} else if (num > second && num < max) {
return [max, num];
}
return acc;
},
[-Infinity, -Infinity]
)[1];
}
console.log(secondLargest([10, 5, 20, 8, 20]));
// Output: 10
✅ Pros:
- Functional style
- Shows mastery of reduce()
✅ Cons:
- Harder to read for beginners
✅ Approach 5 — Finding Second Largest Including Duplicates
✅ Code:
function secondLargestWithDuplicates(arr) {
let first = -Infinity;
let second = -Infinity;
for (let num of arr) {
if (num >= first) {
second = first;
first = num;
} else if (num > second) {
second = num;
}
}
return second;
}
console.log(secondLargestWithDuplicates([20, 20, 10]));
// Output: 20
✅ Explanation:
>= firstensures that duplicate maximums count.
✅ Edge Cases (Very Important for Interviews)
You must address these:
✅ 1. Array with fewer than 2 elements
secondLargest([5]) → null or error
✅ 2. All elements equal
[3,3,3] → second largest = 3 OR null
✅ 3. Negative numbers
✅ 4. Very large numbers
✅ 5. Non-numeric values (should we ignore? throw error?)
✅ 6. Mixed duplicates
Interviewers want to see that you think about edge conditions, not just code blindly.
✅ Time Complexity Comparison
| Method | Time Complexity | Space Complexity |
|---|---|---|
| Sorting | O(n log n) | O(n) |
| One-pass iteration | ✅ O(n) | ✅ O(1) |
| Set + max | O(n) + O(n) | O(n) |
| Reduce method | O(n) | O(1) |
✅ The One-Pass O(n) method is the best for interviews.
✅ Real World Use Cases
Finding the second largest number appears in:
✅ Ranking systems (2nd highest score)
✅ Competition results
✅ Leaderboard applications
✅ Analytics dashboards
✅ Stock market top-movers
✅ Server performance metrics
✅ Sorting algorithms optimization
✅ Machine learning data preprocessing
Understanding this challenge is directly applicable to real engineering tasks.
✅ Best Practices
✅ Clarify whether duplicates count
✅ Use O(n) approach in interviews
✅ Do input validation
✅ Consider empty arrays
✅ Prefer pure functions
✅ Write readable variable names
✅ Mention time & space complexity
✅ SEO Keyword Block (for ranking in Google)
- find second largest number javascript
- javascript second highest value
- array second maximum element js
- coding challenge second largest number
- javascript interview questions arrays
- algorithm to find second largest number
- second max value coding challenge
- find second biggest number in array js
- javascript reduce max values
- how to find second largest number without sorting
✅ Final Thoughts
The “Find the second largest number in an array” coding challenge is a fundamental JavaScript interview problem that tests both algorithmic insight and attention to detail.
A strong candidate doesn’t just sort the array — they:
✅ Provide multiple solutions
✅ Explain trade-offs
✅ Consider duplicates
✅ Handle edge cases
✅ Use optimal O(n) logic
✅ Communicate clearly and professionally
Master this challenge and you’ll impress interviewers and stand out as a thoughtful, technically competent JavaScript developer.