DEV Community

Debabrata Halder
Debabrata Halder

Posted on

Second Largest - Java

Find the Second Largest Element in an Array

This method returns the second largest number in an integer array. If the array has fewer than 2 elements or all elements are the same, it returns -1.

Approach:

  1. Edge Case Check:

    • Return -1 if the array is null or has less than 2 elements.
  2. Initialize Variables:

    • largest: Tracks the largest element (Integer.MIN_VALUE initially).
    • secondLargest: Tracks the second largest element (Integer.MIN_VALUE initially).
  3. Traverse the Array:

    • Update Largest: If the current number is greater than largest:
      • Assign largest to secondLargest.
      • Update largest with the current number.
    • Update Second Largest: If the current number is not equal to largest but greater than secondLargest, update secondLargest.
  4. Return Result:

    • If secondLargest remains Integer.MIN_VALUE, return -1. Otherwise, return secondLargest.

Code Explanation

public int getSecondLargest(int[] arr) {
    // Handle edge cases
    if (arr == null || arr.length < 2) 
        return -1;

    // Initialize largest and second largest
    int largest = Integer.MIN_VALUE;
    int secondLargest = Integer.MIN_VALUE;

    // Traverse array
    for (int num : arr) {
        if (num > largest) {
            secondLargest = largest;  // Update second largest
            largest = num;            // Update largest
        } else if (num != largest && num > secondLargest) {
            secondLargest = num;      // Update second largest
        }
    }

    // Check if second largest exists
    return (secondLargest == Integer.MIN_VALUE) ? -1 : secondLargest;
}
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • The n != largest check ensures duplicates of the largest number are ignored.
  • Integer.MIN_VALUE acts as a placeholder to handle negative numbers effectively.

Complexity:

  • Time: O(n) — Single pass through the array.
  • Space: O(1) — No additional space used.

This code is efficient and handles edge cases gracefully.

Top comments (0)