easy Find the Difference of Two Arrays
Problem Statement
Given two integer arrays nums1 and nums2, return an answer list of size where:
answer[0]is alistof allunique integersinnums1that are not present innums2.answer[1]is alistof allunique integersinnums2that are not present innums1.
You may return the integers in the list in any order.
Examples
-
Example 1:
- Input:
nums1 = [2, 3, 4], nums2 = [1, 2] - Expected Output:
[[3, 4], [1]] - Justification: The number
2is common in both arrays.3and4are unique tonums1, and1is unique tonums2.
- Input:
-
Example 2:
- Input:
nums1 = [0, 2, 4, 6], nums2 = [1, 3, 5, 7] - Expected Output:
[[0, 2, 4, 6], [1, 3, 5, 7]] - Justification: All numbers in both arrays are unique to their respective array as there's no overlap between
nums1andnums2.
- Input:
-
Example 3:
- Input:
nums1 = [10, 20, 20, 30, 90], nums2 = [20, 30, 40, 50] - Expected Output:
[[10, 90], [40, 50]] - Justification: The numbers
20and30are present in both arrays, so they are excluded.10and90are unique tonums1, and40,50are unique tonums2. Duplicates in the input are ignored.
- Input:
Try it yourself
Try solving this question here:
✅ Solution Find the Difference of Two Arrays
Problem Statement
Given two integer arrays nums1 and nums2, return an answer list of size where:
answer[0]is alistof allunique integersinnums1that are not present innums2.answer[1]is alistof allunique integersinnums2that are not present innums1.
You may return the integers in the list in any order.
Examples
-
Example 1:
- Input:
nums1 = [2, 3, 4], nums2 = [1, 2] - Expected Output:
[[3, 4], [1]] - Justification: The number
2is common in both arrays.3and4are unique tonums1, and1is unique tonums2.
- Input:
-
Example 2:
- Input:
nums1 = [0, 2, 4, 6], nums2 = [1, 3, 5, 7] - Expected Output:
[[0, 2, 4, 6], [1, 3, 5, 7]] - Justification: All numbers in both arrays are unique to their respective array as there's no overlap between
nums1andnums2.
- Input:
-
Example 3:
- Input:
nums1 = [10, 20, 20, 30, 90], nums2 = [20, 30, 40, 50] - Expected Output:
[[10, 90], [40, 50]] - Justification: The numbers
20and30are present in both arrays, so they are excluded.10and90are unique tonums1, and40,50are unique tonums2. Duplicates in the input are ignored.
- Input:
Solution
To solve this problem, we'll use a set-based approach because sets efficiently handle uniqueness and membership checks. Initially, we'll convert both input arrays into sets to eliminate any duplicate elements and enable faster lookups. Then, we'll find the difference between these sets in both directions: elements in the first set that are not in the second, and vice versa. This process directly yields the unique elements as per our problem statement.
Using sets is advantageous because set operations like difference and union are highly optimized and concise, making our solution straightforward and efficient. This method also simplifies handling distinct elements, as sets inherently eliminate duplicates.
Step-by-step Algorithm
-
Initialize Collections: Create two
HashSet<Integer>objects: one to store elements fromnums2(namedexistsInNums2) for quick existence checks, and another (onlyInNums1) to store unique elements found innums1but not innums2. -
Fill
existsInNums2: Iterate through each element innums2, adding each element toexistsInNums2. This set will be used to check if an element fromnums1exists innums2. -
Identify Unique Elements for
nums1:- Iterate through each element in
nums1. - For each element, check if it exists in
existsInNums2. - If it does not exist, it means the element is unique to
nums1. Add this element toonlyInNums1.
- Iterate through each element in
-
Convert to List: Convert
onlyInNums1, which is aSet<Integer>, toList<Integer>for the required output format. -
Repeat for
nums2: Perform steps 1 to 4 fornums2againstnums1to find elements unique tonums2. -
Compile Results: Combine the lists of unique elements from both
nums1andnums2into a single list of lists and return this as the final result.
Algorithm Walkthrough
Let's consider the Input: nums1 = [10, 20, 20, 30, 90], nums2 = [20, 30, 40, 50]
Initial Setup:
- We will be executing the
getElementsOnlyInFirstListmethod twice: once withnums1andnums2as arguments to find elements unique tonums1, and a second time with their roles reversed to find elements unique tonums2.
First Execution (nums1 against nums2):
-
Initialize
existsInNums2:existsInNums2is populated with elements fromnums2=[20, 30, 40, 50].
existsInNums2 = {20, 30, 40, 50} -
Identify Unique Elements for
nums1:- Iterate through
nums1=[10, 20, 20, 30, 90]. - Check each element against
existsInNums2.10is not inexistsInNums2, so add10toonlyInNums1.20is inexistsInNums2, skip.30is inexistsInNums2, skip.90is not inexistsInNums2, so add90toonlyInNums1.
onlyInNums1 after first execution = {10, 90} - Iterate through
-
Convert and Compile Results:
- Convert
onlyInNums1to a list and prepare for return.
- Convert
Second Execution (nums2 against nums1):
-
Initialize
existsInNums1:existsInNums1is populated with elements fromnums1=[10, 20, 20, 30, 90].
existsInNums1 = {10, 20, 30, 90} -
Identify Unique Elements for
nums2:- Iterate through
nums2=[20, 30, 40, 50]. - Check each element against
existsInNums1.20is inexistsInNums1, skip.30is inexistsInNums1, skip.40is not inexistsInNums1, so add40toonlyInNums2.50is not inexistsInNums1, so add50toonlyInNums2.
onlyInNums2 after second execution = {40, 50} - Iterate through
-
Convert and Compile Results:
- Convert
onlyInNums2to a list and prepare for return.
- Convert
Final Compilation:
- After both executions, compile the results into a list of lists:
- For
nums1againstnums2, we found[10, 90]as unique tonums1. - For
nums2againstnums1, we found[40, 50]as unique tonums2.
- For
- Final Result:
[[10, 90], [40, 50]]
Code
import java.util.*;
public class Solution {
// Returns the elements in the first arg nums1 that don't exist in the second arg nums2.
List<Integer> getElementsOnlyInFirstList(int[] nums1, int[] nums2) {
Set<Integer> onlyInNums1 = new HashSet<>();
// Store nums2 elements in an unordered set.
Set<Integer> existsInNums2 = new HashSet<>();
for (int num : nums2) {
existsInNums2.add(num);
}
// Iterate over each element in the list nums1.
for (int num : nums1) {
if (!existsInNums2.contains(num)) {
onlyInNums1.add(num);
}
}
// Convert to vector.
return new ArrayList<>(onlyInNums1);
}
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
return Arrays.asList(
getElementsOnlyInFirstList(nums1, nums2),
getElementsOnlyInFirstList(nums2, nums1)
);
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
int[] nums1 = { 2, 3, 4 };
int[] nums2 = { 1, 2 };
System.out.println(solution.findDifference(nums1, nums2));
// Example 2
int[] nums1Example2 = { 0, 2, 4, 6 };
int[] nums2Example2 = { 1, 3, 5, 7 };
System.out.println(solution.findDifference(nums1Example2, nums2Example2));
// Example 3
int[] nums1Example3 = { 10, 20, 20, 30, 90 };
int[] nums2Example3 = { 20, 30, 40, 50 };
System.out.println(solution.findDifference(nums1Example3, nums2Example3));
}
}
Complexity Analysis
Time Complexity
For each of the two function calls to getElementsOnlyInFirstList in findDifference, the method:
- Iterates over each element in
nums2to create a set, which iswhere (n) is the length of nums2. - Then, iterates over each element in
nums1to check against the set, which iswhere (m) is the length of nums1. - Since these operations are done for both input arrays (swapping roles), the total time complexity is
for each call, resulting in which simplifies to .
Space Complexity
The space complexity is primarily due to the storage of elements in sets and the result list:
- Two sets are used to store elements from
nums1andnums2, which in the worst case (no overlap) would requirespace. - The output list will have at most
space complexity, considering all elements are unique between nums1andnums2. - Hence, the total space complexity is
.
🤖 Don't fully get this? Learn it with Claude
Stuck on Find the Difference of Two Arrays? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Find the Difference of Two Arrays** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Find the Difference of Two Arrays** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Find the Difference of Two Arrays**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Find the Difference of Two Arrays**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.