Knowledge Guide
HomeDSACompany Practice

easy Find the Difference of Two Arrays

Problem Statement

Given two integer arrays nums1 and nums2, return an answer list of size where:

You may return the integers in the list in any order.

Examples

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 a list of all unique integers in nums1 that are not present in nums2.
  • answer[1] is a list of all unique integers in nums2 that are not present in nums1.

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 2 is common in both arrays. 3 and 4 are unique to nums1, and 1 is unique to nums2.
  • 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 nums1 and nums2.
  • Example 3:

    • Input: nums1 = [10, 20, 20, 30, 90], nums2 = [20, 30, 40, 50]
    • Expected Output: [[10, 90], [40, 50]]
    • Justification: The numbers 20 and 30 are present in both arrays, so they are excluded. 10 and 90 are unique to nums1, and 40, 50 are unique to nums2. Duplicates in the input are ignored.

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

  1. Initialize Collections: Create two HashSet<Integer> objects: one to store elements from nums2 (named existsInNums2) for quick existence checks, and another (onlyInNums1) to store unique elements found in nums1 but not in nums2.

  2. Fill existsInNums2: Iterate through each element in nums2, adding each element to existsInNums2. This set will be used to check if an element from nums1 exists in nums2.

  3. 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 to onlyInNums1.
  4. Convert to List: Convert onlyInNums1, which is a Set<Integer>, to List<Integer> for the required output format.

  5. Repeat for nums2: Perform steps 1 to 4 for nums2 against nums1 to find elements unique to nums2.

  6. Compile Results: Combine the lists of unique elements from both nums1 and nums2 into 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 getElementsOnlyInFirstList method twice: once with nums1 and nums2 as arguments to find elements unique to nums1, and a second time with their roles reversed to find elements unique to nums2.

First Execution (nums1 against nums2):

  1. Initialize existsInNums2:

    • existsInNums2 is populated with elements from nums2 = [20, 30, 40, 50].
    existsInNums2 = {20, 30, 40, 50}
    
  2. Identify Unique Elements for nums1:

    • Iterate through nums1 = [10, 20, 20, 30, 90].
    • Check each element against existsInNums2.
      • 10 is not in existsInNums2, so add 10 to onlyInNums1.
      • 20 is in existsInNums2, skip.
      • 30 is in existsInNums2, skip.
      • 90 is not in existsInNums2, so add 90 to onlyInNums1.
    onlyInNums1 after first execution = {10, 90}
    
  3. Convert and Compile Results:

    • Convert onlyInNums1 to a list and prepare for return.

Second Execution (nums2 against nums1):

  1. Initialize existsInNums1:

    • existsInNums1 is populated with elements from nums1 = [10, 20, 20, 30, 90].
    existsInNums1 = {10, 20, 30, 90}
    
  2. Identify Unique Elements for nums2:

    • Iterate through nums2 = [20, 30, 40, 50].
    • Check each element against existsInNums1.
      • 20 is in existsInNums1, skip.
      • 30 is in existsInNums1, skip.
      • 40 is not in existsInNums1, so add 40 to onlyInNums2.
      • 50 is not in existsInNums1, so add 50 to onlyInNums2.
    onlyInNums2 after second execution = {40, 50}
    
  3. Convert and Compile Results:

    • Convert onlyInNums2 to a list and prepare for return.

Final Compilation:

  • After both executions, compile the results into a list of lists:
    • For nums1 against nums2, we found [10, 90] as unique to nums1.
    • For nums2 against nums1, we found [40, 50] as unique to nums2.
  • Final Result: [[10, 90], [40, 50]]

Code

java
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 nums2 to create a set, which is where (n) is the length of nums2.
  • Then, iterates over each element in nums1 to check against the set, which is where (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 nums1 and nums2, which in the worst case (no overlap) would require space.
  • The output list will have at most space complexity, considering all elements are unique between nums1 and nums2.
  • 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.

🪜 Hint ladder (no spoilers)

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.
🎨 Explain the approach visually

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.
🔍 Review my solution

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.
🔁 Drill the pattern

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.

📝 My notes