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
Top K Frequent Elements in Array
More Relevant Posts
-
Day 15 of being consistent with DSA Today’s problem: 𝗦𝘂𝗯𝗮𝗿𝗿𝗮𝘆 𝗦𝘂𝗺 𝗘𝗾𝘂𝗮𝗹𝘀 𝗞 The goal is to count the number of continuous subarrays whose sum equals k. I solved it using the prefix sum + hashmap pattern, keeping track of running sums and checking if a previous sum exists that helps form k. Instead of checking all subarrays, the idea is to reuse previously seen sums to count valid subarrays efficiently. One thing I learned:- Storing intermediate results (like prefix sums) can reduce a brute force O(n²) solution to O(n). 𝗧𝗶𝗺𝗲 𝗰𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 -> 𝗢(𝗻) 𝗦𝗽𝗮𝗰𝗲 𝗰𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 -> 𝗢(𝗻) Neetcode Link:- https://lnkd.in/eRCy5_VA Github Link:- https://lnkd.in/eqnHgyHM #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
-
-
Day 6: LeetCode - 540. Single Element in a Sorted Array Today’s problem looked simple at first, but it turned into a really good lesson in pattern observation and binary search. The challenge was to find the single element in a sorted array where every other element appears exactly twice — and do it in O(log n) time. My first instinct was straightforward: compare elements in pairs and return the one that doesn’t match. That works, but it takes O(n) time. The real breakthrough came from observing the pattern: Before the single element, pairs start at even indices After the single element, this pattern shifts Using this idea, I applied binary search: Always check from an even index If a pair is valid → move right If the pattern breaks → move left Takeaway: Binary search is not just about searching values — it’s about identifying and exploiting patterns in the data. Day 6 completed. #DSA #Leetcode
To view or add a comment, sign in
-
-
Day 21 of my Data Structures & Algorithms Journey 🚀 Solved: Flatten a Multilevel Doubly Linked List (LeetCode 430) 💡 Key Insight: Whenever a node has a child, treat it like a detour — go deep into the child list first, flatten it completely, and then reconnect back to the main list. 🧠 What I learned: • Depth First Search (DFS) approach in linked lists • Handling multiple pointers (next, prev, child) carefully • Importance of saving the next pointer before modifying links • How recursion helps simplify complex structures ⚡ Core Idea: Insert the child list in between the current node and its next node, then reconnect everything smoothly. 🔥 This problem really improved my understanding of pointer manipulation and recursive thinking! #LeetCode #DSA #LinkedList #Recursion #CodingJourney #ProblemSolving
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 172 of My LeetCode Journey Problem 129: Sum Root to Leaf Numbers 💡 Problem Insight: Today’s problem was about forming numbers from root-to-leaf paths in a binary tree and returning their total sum. Each path represents a number, so the challenge is building that number correctly while traversing. 🧠 Concept Highlight: The solution uses DFS with path accumulation: At each node, update the current value → current = current * 10 + node.val Traverse left and right When you reach a leaf, add the formed number to the total No need to store paths explicitly, just carry the value forward. 💪 Key Takeaway: Instead of storing full paths, carry forward the computed state. This keeps the solution clean, memory-efficient, and easy to reason about. ✨ Daily Reflection: This problem reinforced how tree traversal, combined with simple math, can solve seemingly complex problems. Understanding flow matters more than storing data. #Day172 #LeetCode #BinaryTree #DFS #PathSum #ProblemSolving #DSA #CodingJourney #Consistency
To view or add a comment, sign in
-
-
#claudecode I am not a coder by any stretch of imagination — this was built using Claude Code for generation and NotebookLLM for troubleshooting in designated data set ( copied Hermes troubleshooting dataset into NotebookLM). Update: it is now built and tested: Dream state for local memory implementation. Yesterday I posted that the Consolidate + Prune loop was the missing piece. It is now running. The full memory loop is live: → Extract — every 6 hours, reads conversations, pulls new facts → Store — saves to local SQLite immediately → Consolidate — monthly, merges related facts into single cleaner statements → Prune — monthly, applies confidence decay and clears stale facts automatically First run pruned 6 stale facts and merged 2 into 1. Memory is already cleaner. Fully model agnostic — Gemma 4, Qwen, Llama, Mistral. Works with any local model via Ollama. Tested in a real environment. The screenshot is the implementation guide that gets sent on request. Three Python files, setup instructions, fully local LLM option included for teams that cannot use any external API. DM me ‘MEMORY’ for the full documentation. 👇 #AIAgents #FinanceAI #LocalLLM #BuildInPublic #DataPrivacy #IFRS
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🧩 Problem: Minimum Distance Between Three Equal Elements I You are given an integer array nums. 🎯 Goal Find three indices i < j < k such that: nums[i] == nums[j] == nums[k] And minimize the value: |i - j| + |j - k| + |k - i| If no such triplet exists, return -1. 🧠 Key Intuition First, group all indices of the same value together. For each number: If it appears at least 3 times, we can form a valid triplet. Now the key observation: For minimizing the distance we will take the consecutive triplets. 🛠 Approach 1️⃣ Store indices of each number using a hash map 2️⃣ For each number: If frequency ≥ 3: Iterate through indices in order Consider every consecutive triplet 3️⃣ Compute: distance = |i - j| + |j - k| + |k - i| 4️⃣ Track the minimum distance 5️⃣ If no valid triplet found → return -1 📈 Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) 🔗 Problem https://lnkd.in/dFRkixe5 💻 Solution https://lnkd.in/diUjhYnr #LeetCode #Cpp #DSA #Algorithms #HashMap #Arrays #ProblemSolving #CodingChallenge #LeetCodeDailyChallenge #CompetitiveProgramming #CodingJourney 🚀
To view or add a comment, sign in
-
Day 37 Today I solved: Subarray Sum Equals K (LeetCode 560) 💡 Problem: Given an array and an integer k, find the total number of subarrays whose sum equals k. 💡 My Approach: I used Prefix Sum + HashMap for an optimal solution: 1️⃣ Compute running prefix sum while traversing the array 2️⃣ Use a HashMap to store frequency of prefix sums 3️⃣ At each index, check: 👉 If (currentSum - k) exists in map → we found subarrays 4️⃣ Add its frequency to the count 5️⃣ Update the map with current prefix sum 💡 Key Insight: If prefixSum[j] - prefixSum[i] = k 👉 Then prefixSum[i] = prefixSum[j] - k So instead of checking all subarrays ❌ We use previously seen sums to get result in O(n) ✅ ⚡ Complexity: Time: O(n) Space: O(n) 🔥 Takeaway: Prefix Sum + HashMap is a powerful combo for subarray problems 🚀 #LeetCode #DSA #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
Day 52 of My #100DaysOfDSA Challenge Today I solved one of the most important design problems in DSA: • LRU Cache (Least Recently Used Cache) Approach: I implemented the LRU Cache using a combination of: Doubly Linked List to maintain the order of usage (most recent ↔ least recent) HashMap to get O(1) access to nodes Whenever a key is accessed or updated, I move it to the front (most recently used). If the cache exceeds capacity, I remove the least recently used node from the back. Key Learnings: Strong understanding of data structure design How to combine multiple data structures efficiently Achieving O(1) time complexity for both get() and put() operations Importance of pointer manipulation in linked lists This problem helped me improve my problem-solving and system design thinking. #100DaysOfCode #DSA #LinkedList #HashMap #LRUCache #LeetCode #Cpp #CodingJourney #LearningInPublic
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
Good comparison between heap and bucket sort. The O(n) optimization is the best. Counting frequency with this approach definitely helps instead of using O(n log n).