LeetCode 2215: Find Difference of Two Arrays with Java HashSet

🚀Day 20 of #75DaysOfLeetCode LeetCode 2215 – Find the Difference of Two Arrays | Java | HashSet Approach Today I solved an interesting array + hashing problem that focuses on finding distinct elements between two arrays. 🔹 Problem Statement Given two integer arrays nums1 and nums2, return: answer[0] → all distinct integers in nums1 not present in nums2 answer[1] → all distinct integers in nums2 not present in nums1 The order of elements in the result does not matter. 📌 Example Input: nums1 = [1,2,3] nums2 = [2,4,6] Output: [[1,3], [4,6]] ✔️ 1 and 3 are in nums1 but not in nums2 ✔️ 4 and 6 are in nums2 but not in nums1 💡 Approach Instead of using nested loops (which would be inefficient), we can use HashSet: 1️⃣ Convert both arrays into sets to remove duplicates. 2️⃣ Check elements of set1 that are not in set2. 3️⃣ Check elements of set2 that are not in set1. 4️⃣ Store results in a list of lists. ⏱ Time Complexity: O(n + m) 📦 Space Complexity: O(n + m) 💻 Java Solution import java.util.*; class Solution { public List<List<Integer>> findDifference(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for(int n : nums1) set1.add(n); for(int n : nums2) set2.add(n); List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); for(int n : set1){ if(!set2.contains(n)){ list1.add(n); } } for(int n : set2){ if(!set1.contains(n)){ list2.add(n); } } List<List<Integer>> result = new ArrayList<>(); result.add(list1); result.add(list2); return result; } } 🔑 Key Takeaway: Using HashSet simplifies the problem by removing duplicates and providing O(1) lookup time. #LeetCode #Java #DSA #CodingPractice #HashSet #Arrays #ProblemSolving #SoftwareDevelopment

  • text

To view or add a comment, sign in

Explore content categories