Find the Difference of Two Arrays — LeetCode 2215 Python Solution
- Problem
- #2215
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: answer[0] is a list of all distinct integers in nums1 which are not present in nums2. answer[1] is a list of all distinct integers in nums2 which are not present in nums1.
Example
- Input
- nums1 = [1,2,3], nums2 = [2,4,6]
- Output
- [[1,3],[4,6]]
- Explanation
- For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].
Python solution
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
s1, s2 = set(nums1), set(nums2)
return [list(s1 - s2), list(s2 - s1)]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2215. Find the Difference of Two Arrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 2215. Find the Difference of Two Arrays?
- LeetCode 2215. Find the Difference of Two Arrays is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2215. Find the Difference of Two Arrays?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2215. Find the Difference of Two Arrays?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2215. Find the Difference of Two Arrays cover?
- LeetCode 2215. Find the Difference of Two Arrays is tagged Array and Hash Table on LeetCode.