Problem 399111 · easy · Phase 03 Linear Management & Searching

Common Elements of Two Sorted Lists

two pointers · sorted arrays · merging

Given two lists of integers a and b, each sorted in non-decreasing order, return the sorted list of values that appear in both, with multiplicity: a value appearing x times in a and y times in b appears min(x, y) times in the answer.

Examples

Input:  a = [1, 2, 2, 3], b = [2, 2, 3, 4]
Output: [2, 2, 3]

Input:  a = [1, 5, 9], b = [2, 6, 10]
Output: []

Constraints

  • 0 <= len(a), len(b) <= 10**5
  • Target: O(len(a) + len(b)) time, O(1) extra space beyond the output; no sets or counters.

Goals

  • Advance the pointer that is behind
  • Preserve multiplicity: a value that appears twice in both lists is reported twice
Starting Python…