Skip to main content

Sum of Min/Max Frequencies of the Arrays - Brute Force & Optimized Approaches

Java · DSA · Hashing

Add the lowest and highest frequency in an array. Solve it two ways, brute force and hashing, then watch both run step by step on your own input.

01 The problem

Given an array of N non-negative integers, find how often each value occurs. Print the minimum frequency + maximum frequency.

For [1, 2, 2, 3, 3, 3, 3], the frequencies are 1 → 1, 2 → 2 and 3 → 4. The lowest is 1 and the highest is 4, so the answer is 1 + 4 = 5.

Type an array to run both programs and see every frequency.

02 Approach 1: Brute force

Walk the array with i. The first time a value appears, mark it in visited and count it with an inner j loop. Then update minFreq and maxFreq with that count.

import java.util.Scanner;

public class SumOfMinMaxFrequenciesBruteForce {
    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 minFreq = Integer.MAX_VALUE;
        int maxFreq = Integer.MIN_VALUE;
        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[i] == arr[j]) {
                        count++;
                    }
                }
                minFreq = Math.min(minFreq, count);
                maxFreq = Math.max(maxFreq, count);
            }
        }
        System.out.println(minFreq + maxFreq);
    }
}
1

visited[] skips repeats

Each distinct value runs the inner loop only once, on its first appearance.

2

Start at the extremes

minFreq starts at MAX_VALUE and maxFreq at MIN_VALUE, so the first real count replaces both.

03 Approach 2: Hashing

Count every value in one pass with hash[arr[i]]++. Then scan hash from 0 to max, skip the zeros, and track the smallest and largest count. There's no inner loop.

import java.util.Scanner;

public class SumOfMinMaxFrequenciesByHashing {
    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 minFreq = Integer.MAX_VALUE;
        int maxFreq = Integer.MIN_VALUE;
        int hash[] = new int[max + 1];
        for (int i = 0; i < n; i++) {
            hash[arr[i]]++;
        }
        for (int i=0;i<=max;i++){
            if(hash[i]!=0){
                minFreq = Math.min(minFreq, hash[i]);
                maxFreq = Math.max(maxFreq, hash[i]);
            }
        }
        System.out.println(minFreq + maxFreq);
    }
}
1

One pass to count

hash[v] holds how many times v appears, for every value at once.

2

Scan hash with i <= max

hash has max + 1 slots, so the last index is max. Skip zeros, because those values never appeared.

04 Live tracer

Pick an approach and step through it. Both use the same input, so you can compare how many steps each one takes.

๐ŸŽฌ Frequency tracer
i
j
arr[]
visited[]
phase = –
i = –
j = –
count = –
steps = 0
minFreq
MAX
Integer.MAX_VALUE
maxFreq
MIN
Integer.MIN_VALUE
Load an array, then press Step ▶ to begin.
0 / 00%
Program printed–
Frequencies–
Steps taken–
Speed
#PhaseijActionminFreqmaxFreq

05 Brute force vs hashing

Let D be the number of distinct values. Brute force runs its inner loop once per distinct value, so it makes D × N comparisons. Hashing touches each element once to count, then scans max + 1 slots.

Brute forceHashing
CountingInner loop per distinct valuehash[arr[i]]++, one pass
TimeO(D × N + max), worst case O(N²)O(N + max)
Extra spaceO(max) for visitedO(max) for hash
Best whenVery few distinct valuesValues are small, non-negative integers

Try [0 0 0 1 1 2] in the tracer: brute force makes 3 × 6 = 18 comparisons, while hashing makes 6 counts and 3 scans. Both need non-negative values, because the value is used as an array index. For negative or huge values, a HashMap<Integer, Integer> does the same job in O(N) average time.

06 Quick revision

1

Answer = min + max frequency

Find every frequency, then add the smallest and the largest.

2

Initialise to the opposite extreme

minFreq = MAX_VALUE, maxFreq = MIN_VALUE.

3

Brute force: count once per value

visited[] stops a repeated value from being counted again.

4

Hashing: count, then scan

Fill hash in one pass, then read hash[i] for i = 0 … max.

5

Skip zero counts

A zero in hash means that value never appeared, so it isn't a frequency.

6

One value counts twice

For [4 4 4 4], min = max = 4, so the answer is 8.

07 Check yourself

Interactive reference for the "sum of min and max frequencies" 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...