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
Solved Top K Frequent Elements on LeetCode with Min Heap + HashMap
More Relevant Posts
-
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 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
To view or add a comment, sign in
-
-
🚀 Day 216 of #300DaysOfCoding 💡 Solved: Minimum Absolute Distance Between Mirror Pairs (LeetCode 3761) Today’s problem was a great mix of hashing + number manipulation that tested both logic and attention to detail. 🔍 Problem Summary: Given an array, find the minimum distance between indices (i, j) such that: 👉 reverse(nums[i]) == nums[j] and i < j ⚡ Key Insight: Instead of checking all pairs (which would be O(n²)), we optimize using a HashMap. Store reversed values while iterating Check if the current number already exists in the map Update the minimum distance 🧠 What I Learned: Direction of logic matters a lot in hashing problems Small mistakes in mapping can lead to wrong answers Always dry run edge cases like [120, 21] ⏱️ Complexity: Time: O(n) Space: O(n) 🔥 Takeaway: Efficient problem solving is not just about knowing concepts, but applying them in the right direction. Consistency is the real game changer — showing up every single day 💯 #LeetCode #DSA #CodingJourney #PlacementPreparation #SoftwareEngineering #HashMap #ProblemSolving #Consistency #LearningEveryday
To view or add a comment, sign in
-
-
🚀 Day 64 of #100DaysOfCode Today, I solved LeetCode 290 – Word Pattern, a problem that focuses on pattern matching and mapping relationships. 💡 Problem Overview: Given a pattern and a string, the task is to determine if the string follows the same pattern, ensuring a one-to-one mapping between characters in the pattern and words in the string. 🧠 Approach: To solve this problem efficiently, I focused on: ✔️ Using a hashmap to map pattern characters to words ✔️ Ensuring a bijection (one-to-one mapping) between pattern and words ✔️ Validating consistency throughout the traversal This approach ensures correctness while maintaining simplicity. ⚡ Key Takeaways: Hashmaps are powerful for mapping relationships Ensuring bijection is crucial in pattern problems Clean validation logic avoids edge-case errors 📊 Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) Building strong fundamentals one problem at a time 🚀 #LeetCode #100DaysOfCode #DSA #HashMap #ProblemSolving #CodingJourney #SoftwareDevelopment #InterviewPrep
To view or add a comment, sign in
-
-
Day 92/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 347 – Top K Frequent Elements(Medium) 🧠 Approach: Count the frequency of each element using a hashmap, then sort the elements based on frequency in descending order and pick the top k. 💻 Solution: class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: freq = {} for num in nums: freq[num] = freq.get(num, 0) + 1 sorted_items = sorted(freq.items(), key=lambda x: x[1], reverse=True) return [item[0] for item in sorted_items[:k]] ⏱ Time | Space: O(n log n) | O(n) 📌 Key Takeaway: Hashmaps combined with sorting provide a simple way to solve frequency-based problems, though heaps or bucket sort can optimize performance further. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 12 of #LeetCode Top Interview 150 Just solved LeetCode 380 – Insert Delete GetRandom O(1) 💻 This problem really tested my understanding of data structures + optimization. The challenge was to design a system that supports insert, delete, and random access — all in constant time O(1). 🔑 Key Learnings: Combining HashMap + Dynamic Array (vector) for efficiency Smart use of index mapping to handle deletions in O(1) Understanding how to balance time vs space complexity Writing clean and optimized logic under constraints ⚡ Result: ✅ All test cases passed ⏱ Runtime: 32 ms (Beats 91.12%) 💾 Memory optimized Every day I’m getting better at breaking down problems and thinking in terms of optimal solutions, not just working ones. Consistency is slowly turning into confidence 💪 #Day12 #LeetCode #DSA #CodingJourney #100DaysOfCode #ProblemSolving #Cpp #TechGrowth #WomenInTech
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 90 of #100DaysOfCode Today I solved "Path Sum III" on LeetCode using a DFS + Recursion approach. Key Idea: We need to count all paths where the sum of node values equals the target. The path doesn’t have to start from the root — it can start from any node! Approach: • For every node, treat it as a starting point • Use DFS to explore all downward paths • Reduce the target at each step (target - node->val) • If a node matches the remaining target → count it • Repeat the process for left and right subtrees Why this works: Every node gets a chance to act as the starting point, and DFS ensures we explore all possible paths efficiently. Concepts Used: • Binary Trees • Depth First Search (DFS) • Recursion • Backtracking (implicit) Time Complexity: O(n²) in worst case Space Complexity: O(h) This problem helped me understand how to explore all possible paths in a tree, not just root-based ones — a big step forward in mastering tree problems From single path problems → to handling multiple dynamic paths… growing every day #Day90 #100DaysOfCode #LeetCode #BinaryTree #DFS #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
-
-
🚀 Day 43 | 100 Days of Coding Challenge #DrGViswanathanChallenge 📘 Problem Solved: LFU Cache (LeetCode - Hard) 🔧 Approach Used (HashMap + Doubly Linked List + Frequency Mapping): • Stored {key → (value, frequency)} using hashmap • Maintained freq → list of keys to track LRU within same frequency • Used another hashmap to store iterators for O(1) deletion • On every get/put, updated frequency and moved key accordingly • Removed Least Frequently Used and Least Recently Used key when capacity exceeded 📌 Key Idea: Combine frequency tracking + LRU policy to maintain correct eviction order in O(1). ⏳ Complexity: Time: O(1) for both get & put Space: O(n) 🧠 Key Learning: Design problems require combining multiple data structures efficiently — here hashmap + list + frequency mapping. 💡 Optimization Insight: Maintaining a minFreq variable helps quickly identify which keys to evict. 📂 Topics Covered: Design, HashMap, Doubly Linked List, LRU, LFU Cache 📊 Example Insight: When two keys have same frequency → remove the least recently used among them. 🔥 One of the toughest design problems — great learning on writing optimized real-world systems! #100DaysOfCode #DSA #CPP #LeetCode #CodingJourney #SystemDesign #CompetitiveProgramming
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