Given two slices of integers, return their multiset intersection: each value appears in the result the minimum number of times it appears in the two slices. Return the values sorted ascending (repeats allowed).
intersectionWithDupes(a, b)
Input format: a | b. Output the values, sorted, space-separated (empty line
if none).
intersectionWithDupes([]int{1, 2, 2, 3}, []int{2, 2, 2}) // → [2, 2]
intersectionWithDupes([]int{1, 1}, []int{1}) // → [1]
intersectionWithDupes([]int{1, 2}, []int{3, 4}) // → []
This is a step up from plain intersection: you need to respect how many times each value appears, and only report it as many times as it can be matched between the two lists. A plain set only knows "present" or "absent," not "present three times" — so this needs a hash map (value to count), not a hash set.
If a value appears three times in the first list and twice in the second, it can only be matched twice — the second list runs out after that. So the right output count for each value is the smaller of its two counts.
Without the decrement, you'd just be checking "is this value present at all" — that collapses back into plain intersection and loses the count entirely, over-reporting values that appear many times in the second list. Treating the map's count as a spendable budget means each occurrence in the first list can only be consumed by one occurrence in the second — exactly the pairing multiset intersection needs.
Building the count map costs time proportional to the first list's size; walking the second list with constant-time lookups and decrements costs time proportional to its size. Total work is linear in the combined size — a big win over a brute-force search-and-mark approach between the two lists.
def intersection_with_dupes(a, b):
count = {}
for v in a:
count[v] = count.get(v, 0) + 1
res = []
for v in b:
if count.get(v, 0) > 0:
res.append(v)
count[v] -= 1
res.sort()
return res
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.