↓Skip to main content
  1. LeetCode/

LeetCode 349: Intersection of Two Arrays

·1 min· ·
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted (first try)

Approach
#

Each value appears once in the result, so a set intersection does it (Hash Table). Sorting one array and binary searching each value of the other also works.

My Solution
#

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1) & set(nums2))

Complexity
#

Time O(m + n), space O(m + n).

Mistakes to Avoid
#

  • No duplicates in the result; keeping multiplicity is LC 350.

Interview Explanation
#

I intersect the two arrays as sets, which naturally removes duplicates. Time O(m + n).

Related

LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 283: Move Zeroes
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 283 note: the write pointer advances only on non-zero values, swapping with them, which pushes zeros to the back
LeetCode 202: Happy Number
·1 min
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 202 note: repeatedly take the sum of squared digits, which reaches 1 or enters a cycle; detect it with a set of seen numbers or fast and slow pointers
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 219: Contains Duplicate II
·2 mins
LeetCode Easy Array Hash-Table Sliding-Window
LeetCode 219 note: a hash map stores each value’s last index; only the most recent occurrence needs a distance check