Skip to main content

Second Largest Element - DSA

Java · DSA · Arrays

Find the second largest distinct element in an array in a single pass, with no sorting and no extra array. Watch largest and secondLargest update step by step on your own input.

01 The problem

Given an array of N integers, print the second largest distinct value. Duplicates of the largest don't count. If there is no second distinct value, print -1.

For [10, 20, 20, 15, 5], the largest is 20. The next distinct value below it is 15. For [7, 7, 7] there is no second value, so the answer is -1.

Type an array to see what the program prints. Negative numbers work too.

02 The code

Keep two variables while walking the array once: largest and secondLargest. A boolean, isSLargestFound, records whether a real second value was ever seen.

package Day9;

import java.util.Scanner;

public class SecondMaxElement {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n=scanner.nextInt();
        int[] arr=new int[n];
        for (int i = 0; i < arr.length; i++) {
            arr[i]= scanner.nextInt();
        }
        int largest=Integer.MIN_VALUE;
        int secondLargest=Integer.MIN_VALUE;
        boolean isSLargestFound=false;
        for (int i = 0; i < arr.length; i++) {
            int current=arr[i];
            if (current > largest) {
                if (largest != Integer.MIN_VALUE) {
                    secondLargest = largest;
                    isSLargestFound = true;
                }
                largest = current;
            } else if (current < largest && current > secondLargest) {
                secondLargest = current;
                isSLargestFound = true;
            }
        }
        if (isSLargestFound) {
            System.out.println(secondLargest);
        } else {
            System.out.println(-1);
        }
    }
}

03 How it works

1

Start below everything

Both trackers start at Integer.MIN_VALUE, so the first element always becomes largest.

2

New maximum: demote, then replace

If current > largest, the old largest drops to secondLargest, and current takes the top spot.

3

In between: update second

If current is below largest but above secondLargest, it becomes the new second.

4

Duplicates are ignored

A value equal to largest fails both checks, so [20, 20] never makes 20 the second largest.

5

Guard on the first demotion

largest != Integer.MIN_VALUE stops the starting placeholder from being treated as a real second value.

6

The flag decides the output

If isSLargestFound is still false, every value was equal (or there was one value), so it prints -1.

04 Live tracer

This runs the code above one element at a time.

๐ŸŽฌ Second-max tracer
The amber pointer is i. The violet cell is the current largest and the rose cell is secondLargest. Click any table row to jump to it.
i
arr[]
i = –
current = –
isSLargestFound = false
steps = 0
largest
MIN
Integer.MIN_VALUE
secondLargest
MIN
Integer.MIN_VALUE
Load an array, then press Step ▶ to begin.
0 / 00%
Program printed–
Distinct values, high → low–
Speed
#icurrentBranchlargestsecondLargestfound

05 Three ways to solve it

The single-pass version is the one interviewers look for, but it helps to know where it sits next to the other common approaches.

ApproachIdeaTimeExtra space
SortSort the array, then walk back from the end to the first value smaller than the lastO(N log N)O(1) to O(N)
Two passesPass 1 finds the largest, pass 2 finds the biggest value below itO(2N) = O(N)O(1)
One pass (this post)Track largest and secondLargest togetherO(N)O(1)

One limit to know: the code uses Integer.MIN_VALUE as "not set yet", so an input that actually contains −2,147,483,648 is treated as empty. For example, [-2147483648, 5] prints -1. Also, if the real second largest is -1, the output looks the same as "not found". The flag tells them apart inside the program.

06 Quick revision

1

Distinct means distinct

Second largest of [20, 20, 15] is 15, not 20.

2

Demote before you replace

Copy largest into secondLargest first, then overwrite largest.

3

Strict comparisons

> and <, never >=, so equal values are skipped.

4

One pass, two variables

O(N) time and O(1) space. No sorting, no extra array.

5

Use a flag for "not found"

isSLargestFound separates "no second value" from a real answer.

6

Test the edge inputs

Try one element, all equal, the max first [7 3], the max last [3 7], and negatives.

07 Check yourself

Interactive reference for the "second largest element" pattern in Java-based DSA practice.

Comments

Popular posts from this blog

Get Keycloak Auth Access Token

Understanding Keycloak Auth Access Token – A Deep Dive $ keycloak / auth-deep-dive ๐Ÿ” Identity & Access Management Getting a Keycloak Access Token — and Actually Understanding It June 2025 Keycloak OAuth 2.0 JWT OpenID Connect Service Account You hit Keycloak's token endpoint, you get back a fat JSON blob — but what is all that stuff? This post dismantles a real token response piece by piece so you know exactly what you have, why the JWT is structured the way it is, and what to do with it next. ๐Ÿ“ก Step 1 — How to Get the Token Keycloak speaks OAuth 2.0 . The endpoint that issues tokens lives under your realm: HTTP Token Endpoint POST http://127.0.0.1:7080/realms/master/protocol/openid-connect/token Content-Type : application/x-www-form-urlencoded grant_type =client_credentials &client_id =eazybank-callcenter-cc ...

Observability & Monitoring through Loki,Promtail (Alloy),Prometheus,Micrometer in Grafana

๐Ÿ”ง What this demo covers End-to-end observability setup using Prometheus + Loki + Grafana Integration of Micrometer with Spring Boot for real-time metrics Log collection using Promtail / Alloy from application containers ๐Ÿ“Š Metrics Monitoring (Prometheus) Scraping metrics from /actuator/prometheus endpoint JVM metrics: memory, threads, GC activity HTTP metrics: request count, latency, error rates Custom metrics via Micrometer ๐Ÿ“œ Centralized Logging (Loki + Promtail) Aggregates logs from multiple microservices Label-based log filtering (fast & efficient) No heavy indexing → lightweight compared to ELK ๐Ÿ“ˆ Visualization (Grafana Dashboards) Real-time dashboards for metrics & logs Correlate logs with metrics for faster debugging Pre-built + custom dashboards ⚙️ Architecture Flow Spring Boot app → exposes metrics via Micrometer Prometheus → scrapes & stores metrics Promtail/Alloy → collects logs → pushes to Loki...

Setting Alerts , Notification Policies , Contact Points in Grafana

Grafana · Alerting Setting Up Alert Policies, Contact Points & Notification Policies in Grafana Published May 23, 2026  ·  14 min read  ·  Grafana 10+ A complete step-by-step guide to configuring Grafana's three pillars of alerting — alert rules, contact points, and notification policies — so your team gets the right alert, on the right channel, at the right time. Table of Contents 1. How Grafana Alerting Works 2. Prerequisites & Enabling Unified Alerting 3. Setting Up Contact Points 4. Configuring Email Contact Points 5. Configuring Webhook Contact Points 6. Other Contact Point Types 7. Creating Alert Rules (Alert Policies) 8. Setting Up Notification Policies 9. Mute Timings & Silences 10. Testing & Troubleshooting 11. Best Practices 1. How Grafana Alerting Works Grafana Unified Alerting has three core bui...