Intersection of Two Arrays

Easy

Topics
ArrayHash TableTwo PointersBinary SearchSorting

Given two integer arrays a and b, return the values that appear in both. Each value appears once in the result, however many times it occurs in the inputs.

Return the values in ascending order.

LeetCode names the arguments nums1 and nums2 and accepts any order. The harness here calls them a and b, and asks for ascending order so the judge has a single answer to compare against.

Example 1

a10212213
b2021
answer2
appears in both
Across these two arrays 1 value appears in both, and the answer lists them ascending. The shading marks every occurrence, and there are more shaded cells than answer entries — a value is reported once however often it occurs, which is what separates this from the variant that keeps multiplicities.
The two arrays have independent lengths and neither is sorted.
Input:  a = [1,2,2,1], b = [2,2]
Output: [2]
Explanation: 2 is the only shared value, and it appears once in the result despite occurring twice in both inputs.

Example 2

a409152
b9041928344
answer49
appears in both
Across these two arrays 2 values appear in both, and the answer lists them ascending.
Input:  a = [4,9,5], b = [9,4,9,8,4]
Output: [4,9]
Explanation: Both 4 and 9 are shared, returned ascending.

Example 3

a102132
b405162
answer
empty array
Across these two arrays nothing is shared, and the answer lists nothing. Each shared value happens to occur once per array here, so the shaded count matches the answer length; that is a coincidence of this input and not the rule.
Input:  a = [1,2,3], b = [4,5,6]
Output: []
Explanation: Nothing is shared, so the result is empty.

Constraints

  • 1 <= a.length, b.length <= 1000
  • 0 <= a[i], b[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

Membership is the only question being asked of b, so turn b into something that answers membership in constant time and then filter a through it. Scanning b once per element of a works and is quadratic, which the limits here tolerate but the habit does not deserve.

The word unique is doing real work. Filtering a directly would emit 2 twice for a = [1,2,2,1], so the duplicates have to be removed — either by collecting results into a set, or by reducing a to a set before filtering.

Making both inputs sets first is the clearest statement of the problem: the answer is the intersection of two sets, and the uniqueness falls out instead of being patched in.

The ascending order asked for here is a sort at the end. If the inputs were already sorted, two cursors advancing through them together would produce the answer in order with no extra memory — which is the version worth knowing, since it generalises to inputs too large to hold.

Approach

  1. Put the values of b into a set.
  2. Walk a, keeping the values that are in that set, and collect them into a second set so each is kept once.
  3. Sort the collected values ascending and return them.
  4. For the sorted-input variant: sort both arrays, run a cursor through each, advance the smaller one, and on a match record the value and advance both past all copies of it.

Walkthrough

a = [4,9,5], b = [9,4,9,8,4]

set of b: {4, 8, 9}

walk a
   4  in set  -> keep
   9  in set  -> keep
   5  not in set

kept {4, 9}, sorted -> [4, 9]

why a set and not a list of kept values
a = [1,2,2,1], b = [2,2]
   set of b: {2}
   walk a: 1 no, 2 YES, 2 YES, 1 no
   a list would hold [2, 2]; the answer is [2].

Complexity

  • Time — O(m + n log n): both arrays are scanned once; the sort is over the shared values only.
  • Space — O(m + n): a set for b and a set for the shared values.

Common Pitfalls

  • Emitting a value once per occurrence in a. The result holds each value once.
  • Returning in input order. This statement asks for ascending.
  • Confusing this with Intersection of Two Arrays II, where multiplicities are kept and the answer for [1,2,2,1] and [2,2] is [2,2].
  • Mutating an input array by sorting it when the caller still needs the original order.
  • Using a list for the membership test, which turns a linear scan into a quadratic one.

Full Solution — all languages

class Solution:
    def intersection(self, a, b):
        in_b = set(b)

        # Collecting into a set is what makes each value appear once, however
        # many times it occurs in a.
        shared = {x for x in a if x in in_b}

        return sorted(shared)
SensAI
Beta
Tap the mic to stop voice mode