Ctrl K

Shared Values With Repeats

Easy
You are given two integer lists left and right. Return their common part with repeats taken into account: each value must appear in the answer as many times as it appears in both lists, that is, the smaller of its two counts. The answer may be in any order. Think about what changes if the lists are already sorted, or if one of them is much shorter than the other.
Example 1
left=[5, 1, 5, 5, 2], right=[5, 5, 3, 1] → [5, 5, 1]

left has three 5s and right has two, so two 5s are shared. Each list has one 1. The answer is [5, 5, 1] in any order.

Example 2
left=[7, 7], right=[7, 7, 7, 4] → [7, 7]

The number of shared 7s is the smaller of the two counts: two.

Example 3
left=[0], right=[9] → []
Constraints
  • 1 ≤ len(left), len(right) ≤ 10⁵
  • 0 ≤ elements ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsValues in Both Lists EasyTwice as Much EasyPairs With a Fixed Gap MediumSpells Without Neighbors MediumThe Lost Ticket Easy
loading Python…
Input
left=[5, 1, 5, 5, 2], right=[5, 5, 3, 1]
Expected
[5, 5, 1]

Run checks the first 3 tests in your browser. Submit checks all 138 tests on the server, hidden ones included.