Find the Second Largest Element in an Array

Problem

Find the second largest element in an array of distinct integers, without sorting.

Input:  nums = [12, 35, 1, 10, 34, 1]
Output: 34

Python Solution

def find_second_largest(nums):
    largest = second_largest = float("-inf")
    for num in nums:
        if num > largest:
            second_largest = largest
            largest = num
        elif largest > num > second_largest:
            second_largest = num
    return second_largest

C++ Solution

int findSecondLargest(vector<int>& nums) {
    long largest = LONG_MIN, secondLargest = LONG_MIN;
    for (int num : nums) {
        if (num > largest) {
            secondLargest = largest;
            largest = num;
        } else if (num < largest && num > secondLargest) {
            secondLargest = num;
        }
    }
    return secondLargest;
}

Java Solution

class Solution {
    public int findSecondLargest(int[] nums) {
        long largest = Long.MIN_VALUE, secondLargest = Long.MIN_VALUE;
        for (int num : nums) {
            if (num > largest) {
                secondLargest = largest;
                largest = num;
            } else if (num < largest && num > secondLargest) {
                secondLargest = num;
            }
        }
        return (int) secondLargest;
    }
}

Complexity

Time: O(n) — one pass, tracking two values. Space: O(1) — two extra variables.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.