Intersection of Two Arrays Solution in Java

Most people would return this answer: [2, 2] But the correct answer is: [2] Why? 🚀 Day 64/365 — DSA Challenge Solved: Intersection of Two Arrays The task: Given two arrays, return their intersection. But there are two conditions: • The element must exist in both arrays • The result must contain only unique values Example: nums1 = [1,2,2,1] nums2 = [2,2] Output: [2] Even though 2 appears multiple times, it should appear only once in the result. 💡 My Approach (Simple Logic) Step 1 Loop through every element of nums1. Step 2 Check if that number exists in nums2. Step 3 Before adding it to the result, make sure it hasn't already been added. To keep the code clean, I used three methods: intersection() Main method that loops through nums1 and builds the result. existsInArray(num, arr) Checks if a number exists in another array. existsInArray(num, arr, length) Checks duplicates only inside the filled part of the result array. Example walkthrough: 1 -> not in nums2 -> skip 2 -> exists -> add 2 -> already added -> skip 1 -> skip Final output: [2] ⏱ Time Complexity: O(n × m) 📦 Space Complexity: O(n) Day 64/365 complete. Code 👇 https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #LearningInPublic #ProblemSolving #Consistency

  • text

To view or add a comment, sign in

Explore content categories