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
Top K Frequent Elements Solution with HashMap and Heap
More Relevant Posts
-
Day 105 of #200DaysOfCode Leveling up Consistency is turning into strength. Today I solved "Top K Frequent Elements" on LeetCode using a Min Heap + HashMap approach. Key Idea: Instead of sorting all elements by frequency, we maintain a heap of size k to efficiently track the top k frequent elements. Approach: • Use a hash map to count frequencies • Use a min heap (size k) to store {frequency, element} • If heap size exceeds k remove the least frequent • Remaining elements in heap = top k frequent Concepts Used: • HashMap (unordered_map) • Heap / Priority Queue • Top K Pattern Time Complexity: O(n log k) Space Complexity: O(n) Takeaway: Using a min heap of size k is a powerful optimization over full sorting when dealing with frequency-based problems. Small improvements daily = Big results over time Let’s keep going #Day105 #200DaysOfCode #LeetCode #Heap #HashMap #Cpp #CodingJourney #ProblemSolving #KeepGoing
To view or add a comment, sign in
-
-
Day 30 Today I solved “Top K Frequent Elements” on LeetCode. The problem is to find the k most frequent elements in an array. At first, I thought about sorting or using a heap — but then I learned a more optimal approach: 💡 Bucket Sort + HashMap Approach: Use a HashMap to count frequency of each element Create a bucket array where index = frequency Store elements based on their frequency Traverse from highest frequency to get top k elements 💡 Why this is powerful: Time Complexity: O(n) ✅ Space Complexity: O(n) 👉 Faster than heap-based solution (O(n log k)) 💡 Key takeaway: Sometimes, instead of sorting, we can use frequency-based grouping (bucket sort) to achieve optimal performance. 💡 What I learned: HashMap for frequency counting Bucket sort for grouping Avoiding unnecessary sorting #LeetCode #DSA #LearnInPublic
To view or add a comment, sign in
-
-
Day 43 of #100DaysOfLeetCode Problem: Find the Difference Difficulty: Easy Key Concept Learned: HashMap for Frequency Counting Today I solved the problem Find the Difference. The task was to find the extra character added to string t compared to string s. Instead of sorting or using built in tricks, I used a hashmap to count the frequency of each character in string s. Then I traversed string t and reduced the frequency. If a character was not present in the hashmap or its count became zero, that was the extra character. This approach is simple, clear, and efficient. Time Complexity: O(n) Space Complexity: O(1) Key Takeaways HashMap is very useful for frequency based problems Comparing two datasets using counts is a common pattern Simple logic often leads to clean and readable solutions Easy problems help reinforce strong fundamentals Staying consistent and focusing on clarity. #100DaysOfLeetCode #DSA #LeetCode #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 239 of #500DaysOfCode Solved LeetCode 3488 – Closest Equal Element Queries 🔁 💡 Approach: Store indices of each value using a hashmap Since array is circular, handle wrap-around distance For each query: Use binary search (lower_bound) to find closest index Check neighbors (left & right) Compute min circular distance ⚡ Key Insight: Only adjacent indices in sorted list matter Circular distance = min(|i-j|, n - |i-j|) ⏱️ Complexity: Time: O(n + q log n) Space: O(n) ✨ Takeaway: Combining hashing + binary search + circular logic makes this efficient. Consistency stacking up 🔥 #LeetCode #DSA #BinarySearch #HashMap #Arrays
To view or add a comment, sign in
-
-
Day 36 – #100DaysOfLeetCode Challenge Today I worked on the problem “Subarray Sum Equals K.” Problem Overview: Given an array of integers and an integer k, the task is to find the total number of continuous subarrays whose sum equals k. Example: Input: nums = [1, 1, 1], k = 2 Output: 2 Explanation: The subarrays [1,1] (from index 0→1 and 1→2) both sum to 2. Approach – Prefix Sum + HashMap To solve this efficiently: 🔹 Use a running sum (prefix sum) while iterating through the array 🔹 Store the frequency of prefix sums in a HashMap 🔹 At each step, check if (current_sum - k) exists in the map 🔹 If it exists, add its frequency to the count Time Complexity: O(n) Space Complexity: O(n) Key Learning: This problem highlights how prefix sums combined with hashing can drastically optimize problems involving subarrays and cumulative sums. Day 36 of my #100DaysOfLeetCode journey — staying consistent and improving problem-solving skills one day at a time!
To view or add a comment, sign in
-
-
Day 11 of being consistent with DSA Today’s problem: 𝗧𝗼𝗽 𝗞 𝗙𝗿𝗲𝗾𝘂𝗲𝗻𝘁 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀 The goal is to return the k most frequent elements from an array. I first solved it using a hashmap + heap, which works with 𝗢(𝗻 𝗹𝗼𝗴 𝗻) 𝘁𝗶𝗺𝗲 𝗰𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆. Then I explored the optimal approach using bucket sort, where elements are grouped by their frequency. 𝗛𝗲𝗮𝗽 -> 𝗢(𝗻 𝗹𝗼𝗴 𝗻) 𝘁𝗶𝗺𝗲, 𝗢(𝗻) 𝘀𝗽𝗮𝗰𝗲 𝗕𝘂𝗰𝗸𝗲𝘁 𝘀𝗼𝗿𝘁 -> 𝗢(𝗻) 𝘁𝗶𝗺𝗲, 𝗢(𝗻) 𝘀𝗽𝗮𝗰𝗲 One thing I learned:- Sometimes grouping data based on properties (like frequency) can be more efficient than traditional sorting. Link:-https://lnkd.in/edWTqBaa GitHub Link:- https://lnkd.in/eEGnvF3h #SoftwareEngineering #DSA #ProblemSolving #LearningInPublic #NeetCode250
To view or add a comment, sign in
-
-
Day 3️⃣ /15 — Consistency Challenge 🚀 🔥 Today’s problem: LeetCode 3761 — Minimum Absolute Distance Between Mirror Pairs 🔹 Approach: The goal is to find the minimum index distance between a number and its mirror (reverse) in the array. Using Reverse Function: For each number, compute its reverse (e.g., 123 → 321). HashMap for Tracking: Use a Map<Integer, Integer> to store: key → reversed number value → index where it appeared Traverse the Array: For each index i: Check if nums[i] already exists in the map 👉 This means we have previously seen its mirror If yes, calculate distance: i - previousIndex Update the minimum answer Store Reverse: Insert reverse(nums[i]) into the map with current index Time Complexity: O(n) Space Complexity: HashMap storage → O(n) Small steps. Daily progress. Building consistency. 💯 #LeetCode #DSA #Consistency #CodingJourney #LearnInPublic #DayChallenge
To view or add a comment, sign in
-
-
🚀 LeetCode Day Problem Solving 🚀 Day-50 📌 Problem: You are given a circular array nums and an array queries. For each query index i, find the minimum circular distance to another index j such that: ✔ nums[j] == nums[queries[i]] ✔ If no such index exists → return -1 🧠 Example: Input: nums = [1,3,1,4,1,3,2] queries = [0,3,5] ✅ Output: [2, -1, 3] 📖 Explanation: Query 0 → value = 1 → nearest same value at index 2 → distance = 2 Query 1 → value = 4 → no duplicate → -1 Query 2 → value = 3 → nearest at index 1 (circular path) → distance = 3 💡 Key Insight: ✔ Since array is circular, distance = 👉 min(|i - j|, n - |i - j|) ✔ Store indices of each value using a map (value → list of indices) ✔ For each query: 👉 Use binary search to find nearest index efficiently 📊 Complexity Analysis: ⏱ Time Complexity: O(n + q log n) 📦 Space Complexity: O(n) 🧠 What I Learned: ✔ Handling circular arrays smartly ✔ Using binary search on index lists ✔ Optimizing brute force to efficient lookup ✅ Day 50 Completed 🚀 Leveling up in Arrays + Binary Search + Optimization 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency #MilanSahoo 🚀
To view or add a comment, sign in
-
-
Day 97 of #100DaysOfCode Today I solved "Maximum Width of Binary Tree" on LeetCode using Level Order Traversal (BFS) + Indexing. Key Idea: Treat the binary tree like a complete binary tree by assigning indices to nodes: • Left child → 2 * index • Right child → 2 * index + 1 This helps us calculate the width of each level easily. Approach: • Use a queue storing {node, index} • For each level: Take first and last index Width = right - left + 1 • Normalize indices to avoid overflow Concepts Used: • Binary Trees • Breadth First Search (BFS) • Queue • Index-based traversal Time Complexity: O(n) Space Complexity: O(n) This problem was interesting because it combines tree traversal with indexing logic to solve a non-trivial problem From simple traversal → to smart indexing tricks #Day97 #100DaysOfCode #LeetCode #BinaryTree #BFS #Cpp #CodingJourney
To view or add a comment, sign in
-
-
Day 46 Today I solved: Binary Search (LeetCode 704) 💡 Problem: Given a sorted array, find the index of a target element. If it doesn’t exist, return -1. 💡 My Approach: I used the classic Binary Search technique: 1️⃣ Initialize two pointers: start and end 2️⃣ Find middle index mid 3️⃣ Compare nums[mid] with target 👉 If equal → return mid 👉 If target is greater → search right half 👉 If target is smaller → search left half 4️⃣ Repeat until found or search space is exhausted 💡 Key Insight: Instead of checking every element ❌ Divide the search space in half each time ✅ ⚡ Complexity: Time: O(log n) Space: O(1) #LeetCode #DSA #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development