Finding Second Largest and Second Smallest in a Java Array

⚑ Direct Answer & Key Takeaway

To find the second largest and second smallest values in a Java array in a single traversal without sorting, initialize max1 and max2 to Integer.MIN_VALUE, and min1 and min2 to Integer.MAX_VALUE. When a new arr[i] beats max1, demote max1 to max2 before updating max1. Otherwise, if arr[i] > max2 and arr[i] != max1, update max2. Apply the symmetric rule for min1 and min2.

1. Why Initializing With 0 Breaks on Negative Inputs

A classic ICSE Section B trap is writing int max1 = 0, min1 = 0; before scanning an array. If the user enters negative temperatures such as {-14, -3, -27, -8}, no element is positive, so max1 stays frozen at 0 even though 0 never existed in the dataset. Similarly, initializing min1 = arr[0] and min2 = arr[0] fails whenever arr[0] happens to be the true minimum or maximum, locking out the runner-up slot. Using Integer.MIN_VALUE and Integer.MAX_VALUE guarantees any valid int input replaces both initial sentinels cleanly. Always guard arrays where all elements are identical by checking whether max2 or min2 ever changed.

  • Initialize max1 = max2 = Integer.MIN_VALUE so negative numbers still win comparisons.
  • Initialize min1 = min2 = Integer.MAX_VALUE so large positive numbers still win comparisons.
  • Check if (max2 == Integer.MIN_VALUE) after the loop to detect all-equal arrays like {7, 7, 7}.

2. Single-Pass Demotion Logic and Duplicate Protection

Sorting an array solely to read arr[n - 2] and arr[1] destroys the input sequence and breaks on duplicate extremes like {90, 90, 75}, where arr[n - 2] wrongly reports 90. A single-pass scan avoids both problems in O(n) time. First, test if (arr[i] > max1): if true, shift the outgoing champion downward via max2 = max1; and then assign max1 = arr[i];. Second, use else if (arr[i] > max2 && arr[i] != max1) so a tie with max1 never overwrites max2. Mirror this exact structure using < for min1 and min2, ensuring the second smallest stays strictly greater than min1.

  • Always execute max2 = max1 BEFORE max1 = arr[i]; reversing those lines loses the previous maximum.
  • Include arr[i] != max1 in the else-if branch so duplicate maxima do not mask the true runner-up.
  • Keep the original array order intact while finding both extremes in one loop.

3. Dry Run With Duplicate Extremes and Negative Values

Trace the algorithm on {45, -12, 88, 88, 19, -12} (n = 6). At i = 0 (45), max1 becomes 45 and min1 becomes 45 while max2 and min2 stay at their sentinel values. At i = 1 (-12), -12 is smaller than min1, so min2 = 45 and min1 = -12; simultaneously -12 > max2 (MIN_VALUE) updates max2 = -12. At i = 2 (88), max2 receives 45 and max1 becomes 88. At i = 3 (second 88), 88 != max1 is false, protecting max2 = 45. At i = 4 (19), 19 < 45 updates min2 = 19. Finally i = 5 (-12) skips min2 via -12 != min1, finishing with max2 = 45 and min2 = 19.

  • Even when arr[0] is updated first, subsequent elements correctly populate max2 and min2.
  • Duplicate 88 and duplicate -12 are both ignored by the inequality guards.
  • Final verified answers for this trace: Second Largest = 45, Second Smallest = 19.

4. Single-Pass Second Largest & Second Smallest in Java

import java.util.*;

public class SecondLargestSmallest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter array size (at least 2): ");
        int n = sc.nextInt();
        if (n < 2) {
            System.out.println("Need at least 2 elements to find second extremes.");
            sc.close();
            return;
        }

        int[] arr = new int[n];
        System.out.println("Enter " + n + " integers:");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;
        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;

        for (int i = 0; i < n; i++) {
            int val = arr[i];

            if (val > max1) {
                max2 = max1;
                max1 = val;
            } else if (val > max2 && val != max1) {
                max2 = val;
            }

            if (val < min1) {
                min2 = min1;
                min1 = val;
            } else if (val < min2 && val != min1) {
                min2 = val;
            }
        }

        if (max2 == Integer.MIN_VALUE || min2 == Integer.MAX_VALUE) {
            System.out.println("No distinct second largest/smallest exists (all values equal).");
        } else {
            System.out.println("Largest: " + max1 + ", Second Largest: " + max2);
            System.out.println("Smallest: " + min1 + ", Second Smallest: " + min2);
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter array size (at least 2): 6
Enter 6 integers:
45 -12 88 88 19 -12
Largest: 88, Second Largest: 45
Smallest: -12, Second Smallest: 19

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
nintNumber of elements entered by user (e.g., 6)
arr[]int[]Input array storing n integers ({45, -12, 88, 88, 19, -12})
max1, max2intTracks highest and second highest distinct values (88 and 45)
min1, min2intTracks lowest and second lowest distinct values (-12 and 19)
valintHolds current element arr[i] during single-pass scan (e.g., 19)
iintLoop index traversing indices 0 to n - 1
🎯 1-on-1 Live Mentorship & Free Study Kit

Perfect Single-Pass Logic for ICSE Section B

Walk through negative-number edge cases, duplicate extremes, and clean VDT preparation in a live 1-on-1 Java class.

πŸ’¬ WhatsApp Now
πŸ”’ Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Writing max1 = arr[i]; max2 = max1; in that order, which assigns both variables to the same largest value.
  • Avoid Mistake: Omitting the && val != max1 guard, causing {50, 50, 30} to incorrectly report 50 as the second largest.
  • Avoid Mistake: Sorting the array and printing arr[1] and arr[n - 2], which fails whenever duplicates exist or input order must remain unchanged.
  • Examiner / Mentor Tip: Mention Integer.MIN_VALUE and Integer.MAX_VALUE explicitly in your VDT under initial valuesβ€”teachers check for negative-number safety.
  • Examiner / Mentor Tip: Remember that Integer.MIN_VALUE equals -2147483648; examiners often ask its approximate value during practical vivas.
  • Examiner / Mentor Tip: If a question asks for second highest marks where duplicates are allowed to tie, clarify whether strictly distinct second largest is expected.

7. Interactive Concept Check Quiz

Question: What will max1 and max2 hold after processing {10, 40, 40, 25} using the single-pass distinct-runner-up algorithm?

8. Frequently Asked Questions

Why is single-pass traversal preferred over Bubble Sort for finding the second largest in ICSE?
A single-pass loop solves the problem in O(n) steps without modifying the original array positions, whereas Bubble Sort takes O(n^2) comparisons and rearranges data. Moreover, single-pass logic with a val != max1 check naturally skips duplicate maximums like {95, 95, 80}, while naive sorted indexing at arr[n - 2] returns the wrong answer.
What happens if all elements in the array are identical, like {5, 5, 5, 5}?
On the first element, max1 becomes 5 while max2 stays at Integer.MIN_VALUE. Every remaining 5 fails both val > max1 and val != max1, so max2 never changes from Integer.MIN_VALUE. Checking if (max2 == Integer.MIN_VALUE) at the end allows your program to print a clear message instead of garbage.
Can we initialize max1 and max2 using the first two array elements instead of Integer.MIN_VALUE?
Initializing from arr[0] and arr[1] works only if you carefully compare them first and handle cases where arr[0] == arr[1], which gets messy for {5, 5, 2}. Using Integer.MIN_VALUE and Integer.MAX_VALUE eliminates special-case setup code, works cleanly for negative integers, and prevents subtle bugs when n equals 2.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class