Second Largest Element

Pattern: Traversal and in-place tricks

easy

Track the largest and the second largest distinct values in one pass, demoting the old largest whenever a new one appears.

The problem

You are given an array of between 1 and 100,000 whole numbers. Return the second largest distinct value: the largest value that is strictly smaller than the maximum. If there is no such value (one element, or all equal), return -1. For example, the answer for [12, 35, 1, 10, 34, 1] is 34, and for [10, 10, 10] it is -1.

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name secondLargest, the "distinct" rule and the -1 rule are this guide's own.

Think first

  • Sorting gives the answer, but what does it cost, and how do you handle repeated maximums?
  • If you keep two notes, largest and second, what happens to them when a new biggest value arrives?
  • What should happen when a value equals the current largest?

Hints

    Brute force, and why it fails

    Sort the array, then walk down from the end until a value differs from the maximum. That works in O(n log n). Two passes (find the max, then the best value below it) is O(n) and also fine. A single pass with two notes does it in one go.

    The key insight

    A new maximum does not throw the old one away: it pushes it down to second place. Handling that demotion, and ignoring copies of the maximum, is all the second-largest logic needs.

    Dry run

    120 
    351 
    12 
    103 
    344 
    15 
    largestnone
    secondnone

    nums = [12, 35, 1, 10, 34, 1]. Both largest and second start as "nothing yet".

    Step 1 of 6

    The plan

    largest = nothing
    second = nothing
    for x in nums:
        if largest is nothing or x > largest:
            second = largest              # the old largest drops to second
            largest = x
        else if x < largest and (second is nothing or x > second):
            second = x
    return -1 if second is nothing, else second
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass with two variables.

    Edge cases

    • One element, or all equal: -1.
    • The second largest appears before the largest, as in [5, 9]: the demotion step handles it.
    • Repeated maximums, as in [3, 9, 9, 3, 1]: the copies of 9 are ignored and the answer is 3.
    • -2147483648 is a real value. Using it as "nothing yet" would confuse the two, which is why the guide uses a wider type or None.
    I've built my logic, show the code

    Java

    class Solution {
        public int secondLargest(int[] nums) {
            long largest = Long.MIN_VALUE;          // "nothing yet", below every int
            long second = Long.MIN_VALUE;
            for (int x : nums) {
                if (x > largest) {
                    second = largest;               // the old largest drops to second
                    largest = x;
                } else if (x < largest && x > second) {
                    second = x;                     // a new second, strictly below largest
                }
            }
            return second == Long.MIN_VALUE ? -1 : (int) second;
        }
    }

    C++

    class Solution {
    public:
        int secondLargest(vector<int>& nums) {
            long long largest = LLONG_MIN;          // "nothing yet", below every int
            long long second = LLONG_MIN;
            for (int x : nums) {
                if (x > largest) {
                    second = largest;               // the old largest drops to second
                    largest = x;
                } else if (x < largest && x > second) {
                    second = x;                     // a new second, strictly below largest
                }
            }
            return second == LLONG_MIN ? -1 : static_cast<int>(second);
        }
    };

    Python

    class Solution:
        def secondLargest(self, nums):
            largest = None                          # "nothing yet"
            second = None
            for x in nums:
                if largest is None or x > largest:
                    second = largest                # the old largest drops to second
                    largest = x
                elif x < largest and (second is None or x > second):
                    second = x                      # a new second, strictly below largest
            return -1 if second is None else second

    Common mistakes

    • Forgetting the demotion, so second is never set when values arrive in increasing order.
    • Treating a copy of the maximum as the second largest.
    • Using Integer.MIN_VALUE as "nothing yet" when that value can appear in the input.

    Similar problems