Go Back
Published on Jul 09, 2025
This is one of those questions that shows up all the time in interviews:
“Given an array of unsorted numbers, return the second largest unique number.”
Let’s go over two practical ways to solve it:
Both will handle edge cases like arrays with fewer than two unique numbers or all values being the same.
const arr = [10, 5, 20, 8, 20];
Here, the largest number is 20.
The second largest unique number is 10.
We don't want 20 again — only distinct values count.
This approach removes duplicates and sorts the array in descending order. It's easy to read and works fine for most situations.
This version avoids sorting altogether. It just loops through the array once and keeps track of the top two unique values.
Both methods get the job done. If performance isn't a concern and you want something quick and readable, go with the sort-based version. If you're optimizing for efficiency or large datasets, the single-pass version is the better choice.