#2215

Find the Difference of Two Arrays

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using sets allows us to efficiently find distinct elements and check for membership in constant time, significantly improving performance.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert nums1 and nums2 into sets to eliminate duplicates.
  2. 2Step 2: Use set difference to find elements in nums1 not in nums2 and vice versa.
  3. 3Step 3: Return the results as lists.
solution.py4 lines
1def findDifference(nums1, nums2):
2    set1 = set(nums1)
3    set2 = set(nums2)
4    return [list(set1 - set2), list(set2 - set1)]

Complexity note: The time complexity is O(n) because we traverse each array once to create sets and then perform set operations which are efficient.

  • 1Using sets can significantly reduce the time complexity for membership checks.
  • 2Distinct elements can be easily managed with sets, avoiding duplicates automatically.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.