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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay