Scrivio Interview library
Arrays and hashingArrays and stringsReported 52 times · 15 min read · updated 15 November 2026

Find the second largest element in an array.

1What second largest means, told as a pile of exam papers

Imagine a teacher with a pile of marked exam papers who wants to give a prize to the best mark and a second prize to the next best. She does not need to sort the whole pile. She reads the papers one at a time and keeps two numbers on a slip of paper, the best mark so far and the runner-up. When a paper beats the best, the old best becomes the runner-up. When a paper beats only the runner-up, it takes second place. Hold on to this slip of paper, because our program will keep exactly the same two numbers.

The question gives us an array, a row of numbers reached by position, called the index, starting at 0. We will use [4, 9, 2, 9, 7] throughout. The largest value is easy to see, 9. But what comes second? If we sorted the array from biggest to smallest we would get 9, 9, 7, 4, 2, and the second position holds 9 again. That is rarely what an interviewer means. The usual meaning, and ours, is the largest value strictly smaller than the maximum. Strictly smaller means smaller and not equal. So the answer here is 7.

Let us find it by hand, the teacher's way. We read 4, so the best is 4 and there is no runner-up yet. We read 9, better than 4, so 9 is best and 4 drops to runner-up. We read 2, which beats neither. We read the second 9, which only ties the best, so it changes nothing. We read 7, which is below 9 but above 4, so 7 becomes the runner-up. The answer is 7, found in one reading of the pile.

PictureThe example array and its second largest value

The largest value, 9, appears twice. The answer is the largest value strictly below 9.

  1. 4091229374
    largest
    9
    second largest
    7

    1The largest value is 9, at indexes 1 and 3. The largest value strictly smaller than 9 is the 7 at index 4, so the answer is 7.

What to assume

Does a copy of the maximum count as second?
We assume not.
What if there is no second largest, as in [7, 7, 7], a single element, or an empty array?
We return an empty OptionalInt, Java's box that either holds an int or says that there is none, rather than a made-up number, because any int could also be a real answer.
Can values be negative, even Integer.MIN_VALUE, the smallest int?
Yes.
Is the array sorted?
No.

The problem is small, and the hand working shows why: at every moment we only need two numbers, however long the array is. The rest of the article is about doing exactly what we just did, without slipping on the special cases.

A careful candidate asks a few questions first. Does a copy of the maximum count as second? We assume not, as above. What if there is no second largest, as in [7, 7, 7], a single element, or an empty array? We return an empty OptionalInt, Java's box that either holds an int or says that there is none, rather than a made-up number, because any int could also be a real answer. Can values be negative, even Integer.MIN_VALUE, the smallest int? Yes. Is the array sorted? No.

2How to recognise the single pass pattern with running values

A beginner who reads find the second largest often reaches for sorting at once, because sorting puts everything in order and the answer can then be read off. That works, and we will try it, but it does far more than the question asks. Let us read the question slowly and see what it really needs.

The first clue is the word largest. The answer is an extreme value, the kind we can judge one element at a time. Whether 7 could be the answer depends only on how it compares with the biggest values we have seen, never on the order of the smaller ones.

The second clue is the word second. The question wants a fixed, small number of extreme values, here two. When the number of values we must remember is fixed and small, we can keep each one in its own variable instead of keeping the whole array in some order.

The third clue is what the question does not ask. It wants a value, not a position, and not the array in order. Nothing forces us to look back at earlier elements once we have read them.

These clues point to the arrays and hashing family, and within it to a technique called a single pass with running values. A single pass means we read the array once, from left to right. A running value is a variable that sums up everything read so far, like the teacher's two numbers. The rule to carry to new problems is this: when a question asks for the best one, two or three of something, keep that many running values and update them as each element arrives. When it asks for the best k with k large or unknown, a heap of size k takes over.

Some tools look useful but are heavier than needed. A HashSet could remove duplicates first, but it costs memory for every distinct value. A heap of size two would work, but it brings a whole data structure to hold two numbers. And sorting, the honest first attempt, orders all of the values when we need only two.

3The honest first attempt, sorting a copy

When a problem feels unfamiliar, it is a good habit to turn it into one we already know how to solve. Sorting is familiar, and after sorting the answer is easy to find. So the honest first attempt, our brute force, sorts a copy of the array from smallest to largest, which puts the maximum in the last slot, and then walks backwards until it meets a value smaller than that maximum. Walking backwards past equal values is what handles copies of the maximum. We sort a copy, made with clone, so that the caller's array is not changed behind its back.

Step throughSorting a copy, then looking below the maximum

The sorted copy of 4, 9, 2, 9, 7. The maximum is in the last slot, and i walks backwards from the slot before it.

  1. 2041729394
    max
    9
    sorted
    all 5 values

    1Arrays.sort puts the copy in order, 2, 4, 7, 9, 9. The maximum is now the last element, s[4] = 9.

  2. 2041729394i
    max
    9
    s[i]
    9
    below max?
    no

    2i starts at 3. s[3] is 9, which is not smaller than the maximum; it is the second copy of 9, so we keep walking.

  3. 2041729394i
    max
    9
    s[i]
    7
    below max?
    yes
    answer
    7

    3i moves to 2. s[2] is 7, smaller than 9, so it is the first value below the maximum, and we return 7.

Java
static OptionalInt secondBySort(int[] a) {
int[] s = a.clone(); // sort a copy, not the caller's array
Arrays.sort(s); // smallest first, so the maximum is last
for (int i = s.length - 2; i >= 0; i--) // walk backwards from just before the end
if (s[i] < s[s.length - 1]) return OptionalInt.of(s[i]); // first value below the max
return OptionalInt.empty(); // every value equals the maximum
}

It is correct, and it handles [7, 7, 7] as well: the backward walk finds no value below 7 and falls out of the loop to return empty.

Now let us count. Sorting n values with Arrays.sort takes about n times log n steps, where log n is how many times we can halve n before reaching 1. For our 5 values that is a small number, but for a million values it is about twenty million comparisons. The copy also takes memory for all n values. So the time is O(n log n) and the extra space is O(n).

Where is the waste? Look at the first frame. Sorting worked out that 2 comes before 4 and 4 before 7, and then we never looked at 2 or 4 at all. Almost all of the ordering work was thrown away. That leads to the question worth asking. Could we learn the top two values while reading the array once, the way the teacher did with her slip of paper?

4Getting to one pass with two running values

There is a middle step that removes the sort. Read the array once to find the maximum, then read it a second time to find the largest value strictly smaller than that maximum. That is O(n) time and O(1) space, already much better. But it reads the array twice, and it raises a fair question. During the first reading, every time the maximum changed, we knew something useful and forgot it.

Here is the key observation. When a new maximum arrives, the old maximum does not stop mattering. It is now the best value below the new one, which is exactly the runner-up. So we keep two running values, first, the largest so far, and second, the largest so far that is strictly below first, and we update both in the same pass.

Each new value x then falls into exactly one of three cases, shown in the table. Read it row by row with the teacher in mind.

The three cases for each new value x
CaseWhat we doWhy
x is bigger than firstsecond = first, then first = xthe old best becomes the runner-up
x is below first and above secondsecond = xa better runner-up; the best is unchanged
x equals first, or x is not above secondnothinga copy of the best, or too small

A beginner usually asks two questions here. The first is why we cannot simply start first and second at Integer.MIN_VALUE, the smallest int, so every real value beats them. Let us try it on [Integer.MIN_VALUE, 5]. The true answer is Integer.MIN_VALUE itself, since it is the only value below 5. Our loop would end with second equal to Integer.MIN_VALUE, and we could not tell whether that is a real answer or the untouched starting value. So instead we keep two booleans, haveFirst and haveSecond, which say whether each variable holds a real value yet.

The second question is why we skip x when it equals first. Let us try not skipping, on [4, 9, 9]. After 4 and 9, first is 9 and second is 4. The second 9 is not bigger than first, but if we let equal values into the middle case, it would replace second, and we would answer 9, a copy of the maximum. The test x < first in the middle case is what keeps copies out.

The most common mistake is to update second only when a new maximum arrives and forget the middle case. It is tempting, because it feels as if second always comes from an old first. Try [9, 7]. 9 becomes first, and 7 is not a new maximum, so second is never set, and the answer would be empty instead of 7. Values that never were the maximum can still be the runner-up.

Why does this always work? After each step, first is the largest value read so far and second is the largest value read so far that is strictly below first. Each of the three cases keeps that sentence true when one more value is read. So after the last value, second is the answer, and haveSecond tells us whether one exists.

5Watching first and second walk across the example

The picture plays the loop on [4, 9, 2, 9, 7]. Under the array, i marks the value being read; values already read are marked as done. The panel shows x, which case applied, and first and second after the step, with none meaning the boolean is still false.

Watch the step where 9 arrives for the first time, and the step where it arrives again. They look alike, but they fall into different cases.

Step throughOne pass over 4, 9, 2, 9, 7 with first and second

i marks the value being read. The panel shows which case applied and the two running values after the step.

  1. 4091229374
    x
    -
    case
    not started
    first
    none
    second
    none

    1Before the loop, haveFirst and haveSecond are false. first and second hold 0, but the booleans say that 0 is not a real value yet.

  2. 4091229374i
    x
    4
    case
    first value
    first
    4
    second
    none

    2x = 4. There is no first yet, so 4 becomes first and haveFirst turns true. There is still no second, because we have seen only one value.

  3. 4091229374i
    x
    9
    case
    new max
    first
    9
    second
    4

    3x = 9 is bigger than first. The old first, 4, moves down to second, and 9 becomes first. This is the step that teaches us the runner-up for free.

  4. 4091229374i
    x
    2
    case
    too small
    first
    9
    second
    4

    4x = 2 is smaller than first and not bigger than second, 4. It cannot be either of the top two, so nothing changes.

  5. 4091229374i
    x
    9
    case
    copy of max
    first
    9
    second
    4

    5x = 9 equals first. It is a copy of the maximum, not a new value, so it is skipped and second stays 4.

  6. 4091229374i
    x
    7
    case
    between
    first
    9
    second
    7

    6x = 7 is smaller than first, 9, but bigger than second, 4. It is a better runner-up, so second becomes 7.

  7. 4091229374
    first
    9
    second
    7
    returned
    OptionalInt[7]

    7The loop is over and haveSecond is true, so we return OptionalInt.of(7). One walk over five values was enough.

Let us read the important frames back. In the third frame the first 9 is a new maximum, so 4 slides down into second without any extra search, which is the observation that removed the second pass. In the fifth frame the second 9 is equal to first, not bigger, so it is skipped, and second stays 4 instead of becoming 9.

In the sixth frame 7 falls into the middle case. It never was the maximum, yet it becomes second, which is exactly the case the common mistake forgets. The last frame returns 7, the same answer the teacher found with her slip of paper.

6The complete Java program

Here is the whole program. The method returns an OptionalInt, so the empty case is visible in the type. main runs our example, an array of equal values, an array whose answer is Integer.MIN_VALUE, and an empty array.

Java
import java.util.OptionalInt;
public class SecondLargest {
// One pass with two variables. "Second largest" means the largest value strictly
// smaller than the maximum; it is empty when the array has fewer than two distinct values.
static OptionalInt secondLargest(int[] a) {
boolean haveFirst = false, haveSecond = false;
int first = 0, second = 0;
for (int x : a) {
if (!haveFirst || x > first) { // new maximum: the old one becomes second
if (haveFirst) { second = first; haveSecond = true; }
first = x;
haveFirst = true;
} else if (x < first && (!haveSecond || x > second)) {
second = x; // between second and first
haveSecond = true;
} // x == first: a duplicate of the maximum, skip
}
return haveSecond ? OptionalInt.of(second) : OptionalInt.empty();
}
public static void main(String[] args) {
System.out.println(secondLargest(new int[] {4, 9, 2, 9, 7})); // OptionalInt[7]
System.out.println(secondLargest(new int[] {7, 7, 7})); // OptionalInt.empty
System.out.println(secondLargest(new int[] {Integer.MIN_VALUE, 5})); // OptionalInt[-2147483648]
System.out.println(secondLargest(new int[] {})); // OptionalInt.empty
}
}

Let us read secondLargest in the order it runs. The two booleans start false, because nothing has been read. first and second start at 0 only because Java needs some value; the booleans make sure that 0 is never mistaken for an answer.

The for loop reads each x once. The first if handles two situations with one test: either there is no first yet, or x beats it. Inside, if there was an old first, it moves down to second and haveSecond becomes true. Then x becomes first. The order matters here. We copy first into second before overwriting first, just as the teacher writes the old best on the runner-up line before writing the new best.

The else if is the middle case. x < first keeps copies of the maximum out, and !haveSecond || x > second lets x in either when there is no runner-up yet or when it beats the current one. Anything else, a copy of first or a value too small, falls through and changes nothing.

After the loop, the last line returns OptionalInt.of(second) when a runner-up exists and OptionalInt.empty() otherwise. So main prints OptionalInt[7], OptionalInt.empty, OptionalInt[-2147483648] and OptionalInt.empty.

7How much it costs, and the cases at the edges

Let us count on the example first. The loop ran five times, once per value, and each time did a few comparisons and at most two assignments, with no sorting and no copy. For n values that is a few steps per value, so the time is O(n). We cannot do better, because any element we skip might be the runner-up.

For memory we keep two ints and two booleans whether the array has five values or five million, so the extra space is O(1), written as constant.

Comparing the ways to find the second largest
ApproachTimeExtra spacePasses
Sort a copy, walk back from the endO(n log n)O(n)sort plus a walk
Find the max, then the largest below itO(n)O(1)2
Two running values, first and secondO(n)O(1)1

The edge cases are where this question is really judged, so let us go through them. An empty array never enters the loop, so haveSecond stays false and we return empty. A single element sets first and nothing else, so it returns empty too. An array of equal values, such as [7, 7, 7], sets first once and then skips every copy, so it returns empty, which is right, because there is no value below 7.

Negative numbers need no special care, because we only compare values with each other. And [Integer.MIN_VALUE, 5] returns OptionalInt[-2147483648] correctly, because the booleans, not a special starting value, tell us that second holds a real value.

8Follow-up questions

How would you find the k-th largest for any k?

Keeping k separate variables does not scale, so we use a min-heap of size k, a structure that always hands back its smallest value. We walk the array and offer each value; whenever the heap holds more than k values, we remove its smallest. At the end the heap holds the k largest values, and its smallest one is the k-th largest. That costs O(n log k) time and O(k) space. If copies of a value must not count twice, we skip any value already in the heap, checked with a set beside it.

What if a copy of the maximum should count, so [4, 9, 9] gives 9?

Then second largest means the second position after sorting, and only the first case changes. We use x >= first instead of x > first, so a copy of the maximum also pushes the old first down into second. On [4, 9, 9] the second 9 moves the first 9 into second, and the answer is 9. It is worth asking the interviewer which meaning they want, because both are reasonable and the code differs by one character.

Can it be done with fewer comparisons?

Our loop can make about 2n comparisons. A tournament does better. Pair the values up and let the larger of each pair go through to the next round, like a knockout competition, until one champion is left, which takes n - 1 comparisons. The second largest must have lost to the champion directly, because any other value lost to something that is not the maximum. The champion played only about log n matches, so we find the largest of those few losers with about log n - 1 more comparisons. In total that is about n + log n - 2.

9Conclusion

We found the second largest element, meaning the largest value strictly below the maximum, the way a teacher finds the top two marks with a slip of paper. Sorting works but orders everything for O(n log n), and two passes work but read the array twice. Keeping first and second in one pass, where a new maximum pushes the old one down, a value between them replaces second, and copies of the maximum are skipped, gives O(n) time and O(1) space, with booleans instead of a starting sentinel so Integer.MIN_VALUE is still handled. The clue to remember is a request for the best one, two or three of something: keep that many running values and update them in a single pass.

What to say in the interviewAbout 80 seconds aloud

Open with

First I would confirm the meaning. I take second largest as the largest value strictly smaller than the maximum, so 4, 9, 2, 9, 7 gives 7, and when there are fewer than two distinct values I return an empty OptionalInt rather than a magic number.

Then, if they want more

The brute force sorts a copy and walks back from the end to the first value below the maximum, which is O(n log n). Finding the maximum and then the largest value below it is O(n) but two passes. Since I need only the top two values, I keep two running values in one pass.

If x is bigger than first, the old first becomes second and x becomes first. If x is below first and above second, it becomes second. If x equals first, it is a copy of the maximum, and I skip it, along with anything not above second.

I do not start with Integer.MIN_VALUE as a sentinel, because it could be the real answer, so I keep two booleans saying whether each value is set. That is O(n) time, one pass, and O(1) space. Empty arrays, single elements and all equal values return empty, and negatives just work. For a general k, I would switch to a min-heap of size k.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 52 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the second largest element in an array.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-second-largest-element-in-an-array-7f1c76/