Intersection of Two Arrays II with Duplicates

🚀 Day 19 of Consistency – Optimized “Intersection of Two Arrays II” (LeetCode) Today I pushed one step further and solved a variation where duplicates also matter — making it slightly more challenging and interesting. 🔍 Problem Understanding Given two arrays, return their intersection including duplicates. Each element should appear as many times as it shows in both arrays. 🧠 Initial Thought (Brute Force) Compare each element of one array with another Track used elements manually ⛔ Inefficient due to nested loops → O(n × m) ⚡ Optimized Approach (HashMap – Frequency Count) 👉 This time, I used a smarter strategy: Store frequency of elements from nums1 in a HashMap Traverse nums2 If element exists in map and count > 0: Add to result Decrease frequency 💡 Example nums1 = [1,2,2,1] nums2 = [2,2] Output → [2,2] ⏱ Complexity Analysis Time Complexity: O(n + m) Space Complexity: O(n) 📊 Result ✔️ All test cases passed (61/61) ⚡ Runtime: 3 ms 🔥 Beats 95.42% submissions 🧩 Key Learning HashMap is extremely useful for frequency-based problems Handling duplicates = tracking counts properly Small optimization can drastically improve performance 🙏 Grateful for the journey and learning every single day 🔥 Consistency + Optimization = Growth mindset #DSA #Java #LeetCode #CodingJourney #HashMap #ProblemSolving #100DaysOfCode #SoftwareDeveloper

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories