↓Skip to main content
  1. LeetCode/

LeetCode 350: Intersection of Two Arrays II

·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 ×4

Approach
#

Each value appears as many times as its smaller count. Counter’s & takes the smaller count per key (Hash Table). With sorted arrays, two pointers also work.

My Solution
#

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list((Counter(nums1) & Counter(nums2)).elements())

Complexity
#

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

Mistakes to Avoid
#

  • Unlike LC 349, duplicates are kept here.

Interview Explanation
#

Each value’s count is the smaller of its two counts, so I intersect Counters and expand the result. Time O(m + n).

Related

LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
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