AlgoInsight

DSA problem

Find the Second Largest Element

EasyArraysPattern: Array TraversalbeginnerFreeAmazon

Given an array of N integers, find the second largest distinct element. If no such element exists, return -1.

A naive approach sorts the array and picks the second-to-last unique element in O(N log N). But you can do it in a single pass with O(N) time. Track two variables: first (largest) and second (second largest). For each element: if it is greater than first, shift first down into second and update first. If it is strictly between second and first, update second.

The key subtlety is handling duplicates - if the array is [5, 5, 5], there is no second largest, so the answer is -1. This problem teaches you to maintain multiple running states simultaneously.

Examples

Example 1
Input: nums = [12, 35, 1, 10, 34, 1]
Output: 34
Explanation: 35 is the largest value; 34 is the next largest distinct value.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

array

Browse all DSA problems