EasyNo. 2215

Find the Difference of Two Arrays — LeetCode 2215 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table
On a study list
LeetCode 75
Reading time
2 min

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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0389Find the DifferenceEasy
2206Divide Array Into Equal PairsEasy
2225Find Players With Zero or One LossesMedium
0001Two SumEasy
0036Valid SudokuMedium
0037Sudoku SolverHard

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.