惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
Google DeepMind News
Google DeepMind News
Stack Overflow Blog
Stack Overflow Blog
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
I
InfoQ
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
量子位
博客园 - 叶小钗
月光博客
月光博客
IT之家
IT之家
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
S
SegmentFault 最新的问题
Engineering at Meta
Engineering at Meta
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Top K Frequent Elements
Jaspreet singh · 2026-06-24 · via DEV Community

Jaspreet singh

Problem Statement

Given an integer array and an integer k, return the k most frequent elements.


Brute Force Intuition

Count frequencies.

Sort elements based on frequency.

Return first K elements.

Complexity

  • Time Complexity: O(N log N)
  • Space Complexity: O(N)

Moving Towards the Optimal Approach

We only need:

Top K Frequencies

Not the entire sorted order.

Use:

Min Heap of Size K


Pattern Recognition

Whenever you see:

Top K
K Largest
K Smallest

Think:

Heap


Optimal Approach

Step 1:

Count frequencies.

HashMap<Integer,Integer>

Step 2:

Maintain Min Heap ordered by frequency.

If heap size exceeds K:

pq.poll();

At the end:

Heap contains K most frequent elements.


Optimal Java Solution

class Solution {

    public int[] topKFrequent(
        int[] nums,
        int k) {

        HashMap<Integer,Integer> map =
            new HashMap<>();

        for (int num : nums) {

            map.put(
                num,
                map.getOrDefault(num, 0) + 1
            );
        }

        PriorityQueue<Integer> pq =
            new PriorityQueue<>(
                (a,b) ->
                map.get(a) - map.get(b)
            );

        for (int key : map.keySet()) {

            pq.add(key);

            if (pq.size() > k)
                pq.poll();
        }

        int[] ans =
            new int[k];

        int idx = 0;

        while (!pq.isEmpty()) {

            ans[idx++] =
                pq.poll();
        }

        return ans;
    }
}


Dry Run

nums = [1,1,1,2,2,3]

k = 2

Frequency Map:

1 → 3

2 → 2

3 → 1

Heap:

3

removed.

Remaining:

1
2

Answer:

[1,2]


Complexity Analysis

Metric Complexity
Time O(N log K)
Space O(N)

Interview One-Liner

Count frequencies using HashMap and maintain a Min Heap of size K to keep only the most frequent elements.