Skip to main content

Topic- (Hashing) Second Highest Occuring/Frequency Element Brute Force Approach

Java · DSA · Brute Force

Find the element with the second-highest frequency using a visited array and two leader slots, el1 and el2. Read the code, then watch it run step by step on your own input.

01 The problem

Given an array of N non-negative integers, print the element that occurs the second most times. If no element takes second place, print -1.

For [1, 2, 2, 3, 3, 3], the frequencies are 1 → 1, 2 → 2 and 3 → 3. Value 3 occurs most, so the answer is 2.

Type an array to see what the program prints and how often each value occurs.

02 The code

Walk the array with i. The first time a value shows up, mark it in visited and count its occurrences with an inner j loop. Then compare that count with the two leaders: el1 (highest frequency) and el2 (second highest).

import java.util.Scanner;

public class SecondHighestOccuringElementBruteForce {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int[] arr=new int[n];
        int max = Integer.MIN_VALUE;
        for(int i=0;i<n;i++) {
            arr[i] = sc.nextInt();
            max = Math.max(max, arr[i]);
        }
        int[] visited=new int[max+1];
        int el1Freq=0; int el2Freq=0; int el1=-1; int el2=-1;
        for (int i = 0; i < n ; i++) {
            int count = 0;
            if(visited[arr[i]]==0){
                visited[arr[i]]=1;
                for (int j = 0; j < n; j++) {
                    if (arr[j] == arr[i]) {
                        count++;
                    }
                }
            }
            if(count > el1Freq){
               el2=el1;
                el2Freq=el1Freq;
                el1=arr[i];
                el1Freq=count;
            }
            else if(count > el2Freq ){
                el2=arr[i];
                el2Freq=count;
            }
            else if (count == el1Freq && arr[i] < el1) {
                el1=arr[i];
            } else if (count == el2Freq && arr[i] < el2) {
                el2=arr[i];
            }
        }
        System.out.println(el2);
    }
}

03 How it works

1

Find max, size visited[]

The first loop reads the input and tracks max, so visited can have one slot per possible value.

2

Fresh count for every i

int count = 0; sits inside the outer loop, so every index starts counting from zero.

3

Count each value once

Only a value's first appearance runs the inner j loop. A repeat keeps count = 0, so it doesn't change the leaders.

4

Push the old leader down

If count > el1Freq, the old el1 moves into el2 and arr[i] becomes the new el1.

5

Or take second place

If the count doesn't beat el1Freq but beats el2Freq, arr[i] becomes the new el2.

6

Ties and -1

The last two branches prefer the smaller value on a tie. el2 starts at -1, which is printed if nothing takes second place.

04 Live tracer

This runs exactly the code above, one step at a time.

๐ŸŽฌ Frequency tracer
Amber pointer = i, teal pointer = j. The beam turns teal on a match and rose on a mismatch. The row below is visited[]. Click any table row to jump to it.
i
j
arr[]
visited[]
i = –
j = –
count = 0
comparisons = 0
1st · el1 / el1Freq
-1
freq 0
2nd · el2 / el2Freq
-1
freq 0
Load an array, then press Step ▶ to begin.
0 / 00%
Program printed–
Frequencies–
Speed
#ijarr[i]arr[j]Actioncountel1 (freq)el2 (freq)

05 Complexity

Let D be the number of distinct values. Because of visited, the inner loop runs only D times, once per distinct value, and each run does N comparisons.

StepCost
Read input, find maxO(N)
Allocate visited[max + 1]O(max)
Count each distinct valueO(D × N)
Total timeO(D × N + max), worst case O(N² + max) when all values are distinct
Extra spaceO(max), not O(1): visited grows with the largest value

You can check this in the tracer: [4 4 4 1 1 2] has D = 3 and N = 6, so it makes exactly 3 × 6 = 18 comparisons. For large inputs, a HashMap<Integer, Integer> of frequencies does the same job in O(N) average time and O(D) space, and it handles negative values.

ApproachTimeExtra spaceNegatives / huge values
Brute force + visitedO(D × N + max)O(max)No
HashMap of frequenciesO(N) avgO(D)Yes

06 Quick revision

1

visited[] avoids recounting

The inner loop runs once per distinct value, not once per index.

2

count resets every iteration

Declaring count inside the outer loop means a repeat has count = 0 and leaves the leaders alone.

3

Two slots, one pass

You don't need to sort frequencies. el1 and el2 are updated as each value is counted.

4

Demote before replacing

When a new leader appears, copy el1 into el2 first, then overwrite el1.

5

visited costs O(max) space

It grows with the largest value, not with N, and needs non-negative input.

6

-1 is the "none" answer

If every value occurs equally often, nothing takes second place and -1 is printed.

07 Check yourself

Interactive reference for the "second highest occurring 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...