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
Docker - Interview preparation guide
May 08 Interview Guides

## What is Docker and why is it used? Docker is a platform for developing, shipping, and running applications in containers. Containers package an application with its dependencies, ensuring....

Application Security - Interview preparation guide
May 27 Interview Guides

# 1. What is application security? Application security refers to the measures and practices implemented to protect applications from security threats throughout their development lifecycle and....

CI/CD concepts - Interview preparation guide
Jan 05 Interview Guides

## What is CI/CD? CI/CD stands for Continuous Integration and Continuous Delivery/Deployment. CI is the practice of automatically integrating code changes from multiple contributors into a....

GraphQL - Interview preparation guide
Oct 01 Interview Guides

## What is GraphQL? GraphQL is a query language for APIs and a runtime for executing those queries. It allows clients to request exactly the data they need, reducing over-fetching and....

Error based SQL Injection
Apr 26 Application Security

In the previous example, we saw how a classic [SQL Injection Login Bypass](https://hacksland.net/sql-injection-login-bypass) works. SQL Injection is not all about that. The real fun is we can extract....

Understanding Assembly Language: Purpose and Structure
Mar 23 Low level Development

Assembly language is a low-level programming language that provides a human-readable representation of a computer's binary instructions. Unlike high-level languages like C, C++, or Python, which are....