algoadvance

2215. Find the Difference of Two Arrays

Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:

Note that the integers in the lists may be returned in any order.

Example:

Input: nums1 = [1,2,3], nums2 = [2,4,6]
Output: [[1,3],[4,6]]
Explanation:
For nums1, nums1[1]=2 is present in nums2, so it is removed. Remaining items are [1, 3].
For nums2, nums2[0]=2 is present in nums1, so it is removed. Remaining items are [4, 6].

Clarifying Questions

  1. Question: Can the arrays have duplicate elements?
    • Answer: The problem statement does not specify that, but since we are looking for distinct integers, we will treat each input as a set of integers for the purpose of difference calculation.
  2. Question: Can either of the arrays be empty?
    • Answer: Yes, either of the arrays can be empty, and the result should be computed accordingly. If one array is empty, the entire content of the other array should be displayed in its corresponding result list.
  3. Question: Are the integers in the arrays within any particular range?
    • Answer: There is no specified range in the problem statement, so we will assume the integers fit within typical bounds used in Python integer computations.

Strategy

The goal is to find distinct integers in one array but not in the other array. Here are the step-by-step procedures:

  1. Convert Both Arrays to Sets: This will allow us to have unique elements, making the difference calculation straightforward.
  2. Set Difference Operation:
    • Compute set1 - set2 to get elements present in nums1 but not in nums2.
    • Compute set2 - set1 to get elements present in nums2 but not in nums1.
  3. Convert Resulting Sets to Lists and Return Them:
    • Convert the results of differences back to lists since the return type is specified as lists in the problem statement.

Time Complexity

Here is the implementation in Python:

def findDifference(nums1, nums2):
    set1 = set(nums1)
    set2 = set(nums2)
    
    diff1 = list(set1 - set2)
    diff2 = list(set2 - set1)
    
    return [diff1, diff2]

Example Run

Let’s run an example:

nums1 = [1, 2, 3]
nums2 = [2, 4, 6]
print(findDifference(nums1, nums2))  # Output should be [[1, 3], [4, 6]]

This correctly computes the distinct elements in each list according to the described strategy.

Try our interview co-pilot at AlgoAdvance.com