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
SSRF - Server Side Request Forgery
May 27 Application Security

Server-Side Request Forgery (SSRF) is a web security vulnerability that allows an attacker to induce the server-side application to make HTTP requests to an arbitrary domain of the attacker's....

Remote Command Execution
Mar 23 Application Security

Remote Command Execution (RCE) is a critical security vulnerability that allows an attacker to execute arbitrary commands on a remote server. This vulnerability can lead to unauthorized access, data....

Finding the Second Largest Element in an Array
Nov 10 DSA

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.....

REST API - Interview preparation guide
May 08 Interview Guides

## What is a REST API? A REST (Representational State Transfer) API is an architectural style for designing networked applications. It uses standard HTTP methods to interact with resources, making....

Ballerina connector for Hubspot Schema API
Mar 23 WSO2

Hi all, It's a new article on something cool. Here we are going to see how we can use the Hubspot schema connector with Ballerina. When it comes to building connectors for seamless integration....

SQL injection login bypass
Apr 26 Application Security

SQL Injection (SQLi) is one of the oldest and most fundamental web application vulnerabilities. While it’s becoming rarer in modern web apps due to better coding practices and frameworks,....