Problem 379404 · medium · Phase 03 Linear Management & Searching

Merge Into the Spare Slots

two pointers · in-place · merging

List a holds m sorted integers followed by len(b) placeholder slots containing None. List b holds len(b) sorted integers. Merge b into a in place so that a ends up fully sorted, and return None.

Tests call (merge_back(a := [...], m, [...]), a)[1] and inspect a.

Examples

Input:  a = [1, 4, 7, None, None, None], m = 3, b = [2, 3, 8]
Output: a becomes [1, 2, 3, 4, 7, 8]

Input:  a = [None, None], m = 0, b = [5, 6]
Output: a becomes [5, 6]

Constraints

  • 0 <= m <= 10**5, 0 <= len(b) <= 10**5, len(a) == m + len(b)
  • Target: O(m + len(b)) time, O(1) extra space (do not build a merged copy and do not sort).

Goals

  • Merge from the back so no unread value is overwritten
  • Handle leftovers from the second list when the first runs out
Starting Python…