Thilan Dissanayaka DSA Nov 10

Finding the Second Largest Element in an Array

Hi all,

Here I'm back with another algorithmic problem. This is a classical interview question asked almost everywhere. As you may know, I recently did a Software Engineering internship at WSO2. While preparing for those interviews, I came across this simple-looking but tricky problem.

Let’s jump into it.

The Problem

You are given an array of integers. Your task is to find the second largest element in the array.

For example,

a4tsq463p78f5kse8op9.png

If we sort this array, we clearly see.

wobv9gthkondeyg7crvr.png

A straightforward Java solution might look like this.

public static int FindSecondLargest(int[] arr) {
    sort(arr);
    return arr[arr.length - 2];
}

But… this is not a good solution.

Why Sorting Is Not the Right Approach

  1. Sorting is unnecessary and inefficient

Sorting takes O(n log n) time. But finding the second largest element can be done in O(n). Why waste extra computation?

  1. Duplicate elements break our logic

If the largest value appears multiple times, this approach might still return the same largest value instead of the second distinct largest.

The O(n) Linear Scan Approach

We can find the second largest in just O(n) time.

vqtqbdrillrcmyss7ssj.png

max     = 1
2nd max = 1

sdf kiesu8p072dgmhod3lue.png

max     = 56
2nd max = 1

zptysdtqesvsripi16ft.png

max     = 56
2nd max = 4
    public static int findSecondLargest(int[] arr) {

        int max = arr[0];
        int second_max = arr[0];

        for (int i = 0; i < arr.length; i++) {
            if (max < arr[i]) {
                second_max = max;
                max = arr[i];

            } else if (second_max < arr[i]) {
                second_max = arr[i];
            }
        }

        return second_max;

    }

The Hidden Bug

It seems like the correct algorithm right? We are good to go.

but, Wait!!

What if the array is something like bellow?

nufalxed6r5cruxdc0pl.png

max     = 56
2nd max = 56

We assume the first element is maximum and second maximum. (Just for the beginning as we did in previous example.)

etuokiie0ueufjlzvixv.png

max     = 56
2nd max = 56

This still keeps the second maximum value as 56. Then this approach is not going to work for finding the second maximum of the array.

But we can correct the algorithm by a simple tweak. We set the maximum and second maximum values to the lowest possible integer value. We can obtain this by using Integer.MIN_VALUE.

    public static int findSecondLargest(int[] arr) {

        int max = Integer.MIN_VALUE;
        int second_max = Integer.MIN_VALUE;

        for (int i = 0; i < arr.length; i++) {
            if (max < arr[i]) {
                second_max = max;
                max = arr[i];

            } else if (second_max < arr[i]) {
                second_max = arr[i];
            }
        }

        return second_max;

    }

Now, algorithm should works as expected.

ALSO READ
Building and Extending a PHP Web Shell
Apr 27 Application Security

A **web shell** is a script that enables an attacker to gain remote control over a web server. It is especially useful for **post-exploitation tasks**, allowing an attacker to execute arbitrary....

XSS - The Ultimate guide for Cross Site Scripting
May 27 Application Security

Cross-Site Scripting (XSS) is one of the most prevalent and dangerous web application security vulnerabilities. According to OWASP, XSS consistently ranks among the top 10 web application security....

Proxy Pattern explained simply
Apr 26 Software Architecture

Sometimes you don't want or can't allow direct access to an object. Maybe it's expensive to create, needs special permissions, or you want to control access in some way. This is where the **Proxy....

Building a Web3 CLI Tool for the Ballerina Language: From Idea to Reality
Apr 26 WSO2

🚀 Excited to finally share my journey of building a web3 CLI tool for Ballerina! This tool bridges the gap between Ethereum smart contracts and the Ballerina programming language by automatically....

Adapter Pattern explained simply
Apr 26 Software Architecture

Ever needed to connect two incompatible interfaces without changing their source code? That’s exactly where the **Adapter Pattern** shines! The Adapter Pattern is a structural design pattern....

Factory Pattern explained simply
Apr 26 Software Architecture

# Factory Pattern Imagine you want to create objects — but you don't want to expose the creation logic to the client and instead ask a factory class to **create objects for you**. That's....