Finding Duplicates in Array with HashMap

🚀 DSA Journey Day 8 — LeetCode :Finding Duplicates in an Array Today’s problem looked simple at first… but the approach made all the difference 👀 🔍 Problem Understanding Given an integer array nums, return all elements that appear exactly twice. ⚡ Brute Force Approach For every element, traverse the entire array Count occurrences Time Complexity: O(n²) ❌ (Not efficient) 🚀 Optimized Approach (Using HashMap) Used a HashMap to store frequency of each element First pass → store counts Second pass → collect elements with frequency = 2 👉 Steps: Traverse the array Store frequency using map.getOrDefault() Iterate over the map If value == 2 → add to result list 🧠 Example Walkthrough Input: [4,3,2,7,8,2,3,1] Map: {1=1, 2=2, 3=2, 4=1, 7=1, 8=1} Output: [2,3] ⏱️ Complexity Analysis Time: O(n) ✅ Space: O(n) 💡 Key Learning Sometimes the problem isn’t hard… choosing the right data structure is what makes it efficient 🔥 ✅ Result ✔️ Accepted (29/29 test cases) ⚡ Runtime: 30 ms 🙏 Staying consistent and improving every day 📌 Consistency beats motivation #DSA #Java #CodingJourney #LeetCode #ProblemSolving #HashMap #100DaysOfCode #PlacementPreparation

  • text

To view or add a comment, sign in

Explore content categories