File: intersection-of-two-arrays-ii/solution.py

Date: 2026-06-06

Time: 17:06

intersection-of-two-arrays-ii/solution.py

Purpose

Solves LeetCode 350 — Intersection of Two Arrays II. Unlike the simpler "Intersection of Two Arrays" (problem 349) which returns distinct common elements, this variant preserves duplicate counts: if 1 appears three times in nums1 and twice in nums2, the result includes 1 twice.

Key Components

intersect(nums1, nums2) -> list[int] — The sole public function. Takes two integer lists, returns their multiset intersection.

Contract: each element in the output appears exactly min(countinnums1, countinnums2) times. Output order follows nums2's iteration order.

Patterns

Counter-decrement pattern. Rather than building two Counters and taking the minimum (which Counter._and_ supports), this builds a single Counter from nums1, then walks nums2 while decrementing counts. This is a streaming consumption pattern — it processes nums2 in one pass without materializing a second frequency map.

This is idiomatic for the follow-up question LeetCode poses: "What if nums2 is streamed from disk?" Only nums1 needs to fit in memory; nums2 can be read element-by-element.

Dependencies

Imports: collections.Counter — used to build the frequency map of nums1.

Imported by: intersection-of-two-arrays-ii/test_solution.py. The long "Imported By" list in the prompt is misleading — those are test files across the entire repo that happen to import Counter from collections, not files that import this solution.

Flow

1. Build a Counter from nums1 — O(n) time, O(n) space where n = len(nums1).

2. Iterate nums2. For each element, check if the counter has remaining capacity (counts[num] > 0). If yes, append to result and decrement. If no, skip.

3. Return result.

Total: O(n + m) time, O(min(n, m)) space for the result (though the counter always uses O(n) — an optimization would be to always counter the smaller array).

Invariants

Error Handling

None. The function trusts its inputs are lists of integers per the LeetCode contract. Empty lists produce an empty result naturally — the Counter is empty or the loop has nothing to iterate.

Topics to Explore

Beliefs