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
Abstract Factory Pattern explained simply
Apr 26 Software Architecture

When you want to create **families of related objects** without specifying their concrete classes, the **Abstract Factory Pattern** is your best friend. --- ## What is the Abstract Factory....

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

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

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

Build A Simple Web shell
Mar 23 Application Security

A web shell is a type of code that hackers use to gain control over a web server. It is particularly useful for post-exploitation attacks, and there are various types of web shells available. Some of....

Introduction to Edge Computing
Mar 23 Computing Concepts

Edge computing is a distributed computing paradigm where computation and data storage are performed closer to the location where it is needed. Instead of relying solely on a centralized data center,....