Top K Frequent Elements Solution with HashMap and Heap

Day 72 of DSA Journey ✅ Solved Problem: Top K Frequent Elements 💻 Platform: LeetCode (Problem 347) 🧠 Topic: HashMap, Priority Queue, Heap 📌 The Problem: Given an integer array and an integer k, return the k most frequent elements. The answer can be in any order. Classic frequency problem — count first, then find the top k! 🎯 My Approach - HashMap + Max Heap: 1. Build a HashMap counting the frequency of every element in the array 2. Create a max heap (PriorityQueue) sorted by frequency in descending order using a comparator 3. Add all unique elements from the HashMap into the max heap 4. The heap automatically orders elements by their frequency — highest on top 5. Poll k elements from the top of the heap one by one 6. Each poll gives the next most frequent element 7. Store the results in an output array and return it 📊 Complexity: Time: O(n log n) — building heap takes O(n log n) Space: O(n) — HashMap and heap both store at most n unique elements 🚀Day 72 down — New topic, new energy! #100DaysOfCode #DSA #LeetCode #HashMap #PriorityQueue #Heap #Day72 #Consistency #ProblemSolving #CodingJourney #KeepGoing

  • text

To view or add a comment, sign in

Explore content categories