Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 58

Second Largest Element in Array (Java)

In this lesson: Find the second largest element in an array in Java in one pass — code, dry run and output. In Hindi & English.

The problem

Given an array like {10, 5, 20, 8, 15}, the second largest element is 15 (the largest is 20). We can find it in a single pass using just two variables — no sorting needed. This is a common interview question.

💡 Track two values as you go: the largest so far and the second largest so far.

The two-variable idea

Keep first (largest) and second (second largest), both starting at the smallest possible value. For each element:

  • If it beats first, the old first becomes second, and this becomes first.
  • Else if it beats second (but not first), it becomes second.

The Java program

public class SecondLargest {
    public static void main(String[] args) {
        int[] a = {10, 5, 20, 8, 15};
        int first = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;

        for (int x : a) {
            if (x > first) {
                second = first;   // old max slides down
                first = x;
            } else if (x > second && x != first) {
                second = x;
            }
        }
        System.out.println("Second largest: " + second);
    }
}
Second largest: 15

Both start at Integer.MIN_VALUE. Each new maximum pushes the old one into second. Values between the two update only second.

Dry run

Dry Run — Second largest, array {10,5,20,8,15}
xx > first?firstsecond
Start—−∞−∞
10yes10−∞
5no (5>−∞ second)105
20yes2010
8no2010
15no (15>10)2015
Second largest = 15
💡 Understand it this way

When a new biggest appears (20), the old biggest (10) slides into second. Values like 15 that beat second but not first just update second. At the end second = 15.

Why one pass is enough

Because we track both the largest and second largest at the same time, a single loop sees every value once and keeps the two we care about updated. This is O(n) — faster than sorting the whole array (O(n log n)) just to look at the second element, and it does not change the array.

Common mistakes

  • Starting variables at 0. Use Integer.MIN_VALUE, or negative arrays break.
  • Forgetting to slide first into second. On a new max, move the old max down.
  • Counting duplicate maxes. Add x != first if you want a distinct second.
  • Sorting unnecessarily. A single pass is faster and keeps the array intact.

Summary

  • The second largest is the biggest value after the maximum.
  • Track first and second in one pass.
  • A new maximum pushes the old one into second.
  • Start both at Integer.MIN_VALUE for safety.
  • This is O(n) — faster than sorting and does not change the array.

Next, sort an array with bubble sort, or remove repeats in remove duplicates from an array.

Frequently Asked Questions

How do I find the second largest element in an array?
Keep two variables, first and second, both starting very small. Loop once through the array: if a value beats first, move first to second and update first; else if it beats second (but not first), update second. At the end, second holds the answer.
Can I find the second largest in a single pass?
Yes. With two variables tracking the largest and second largest, one loop through the array is enough — O(n). You do not need to sort the array, which would be slower.
Why not just sort the array and take the second element?
Sorting works but is O(n log n) and changes the array order. The two-variable method is faster at O(n) and does not modify the array, so it is preferred for just finding the second largest.
Why start the variables at very small values?
Starting first and second at the smallest possible value (like Integer.MIN_VALUE) ensures the first real elements will always be bigger, so the comparisons work correctly from the start.
What if the array has duplicate largest values?
You may want the second largest distinct value. In that case, skip values equal to first when updating second, so duplicates of the maximum do not count as the second largest.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicAnagram Check Your progress: 58 / 61 (95%) · Lesson 59 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free