LeetCode 2215: Find the Difference of Two Arrays Solution

Master LeetCode problem 2215 (Find the Difference of Two Arrays), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2215. Find the Difference of Two Arrays

Problem Explanation

Explanation

To find the difference of two arrays, we can iterate through each element in both arrays and keep track of elements that are present in one array but not in the other. We can use sets to efficiently check for presence of elements. After processing both arrays, we can return the distinct elements found in each array.

  • Time complexity: O(n), where n is the total number of elements in both arrays.
  • Space complexity: O(n), where n is the total number of distinct elements found.

Solution Code

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Solution {
    public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();

        for (int num : nums1) {
            set1.add(num);
        }

        for (int num : nums2) {
            set2.add(num);
        }

        List<Integer> diff1 = new ArrayList<>();
        List<Integer> diff2 = new ArrayList<>();

        for (int num : set1) {
            if (!set2.contains(num)) {
                diff1.add(num);
            }
        }

        for (int num : set2) {
            if (!set1.contains(num)) {
                diff2.add(num);
            }
        }

        List<List<Integer>> result = new ArrayList<>();
        result.add(diff1);
        result.add(diff2);

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2215 (Find the Difference of Two Arrays)?

This page provides optimized solutions for LeetCode problem 2215 (Find the Difference of Two Arrays) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2215 (Find the Difference of Two Arrays)?

The time complexity for LeetCode 2215 (Find the Difference of Two Arrays) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2215 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2215 in Java, C++, or Python.

Back to LeetCode Solutions