All problems
0076EasyLinked ListRecursion

Splice Index Card Chains

Tracked in this browser only
Write code

Trains the technique from

LeetCode 21Merge Two Sorted Lists

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Two archive drawers each hold a chain of index cards. Every card carries one signed shelf offset and points at the next card in the same drawer, so a drawer is a single file of cards. Walking a drawer from its front card, the offsets already run from smallest to largest, and a drawer may hold no cards at all.

Card pointers cannot be handed over directly, so each chain arrives as a plain JSON list of its offsets in walking order, front card first: [-4, 0, 7] is a front card holding -4, behind it a card holding 0, and behind that a card holding 7. Give your answer back in the same form.

Weave the two chains into one file of cards whose offsets still run from smallest to largest. Every card is kept, so an offset held in both drawers shows up twice in the answer. Reuse the cards you were handed: compare the two front cards, detach the one holding the smaller offset, attach it behind the growing answer, and carry on. Do not pool the offsets and sort them. Walk each chain once, in O(m + n) steps, with only a constant amount of bookkeeping beyond the chain you hand back. When both drawers are bare, hand back an empty chain.

Examples

Example 1

Input
chain1 = [-4, 0, 7], chain2 = [-9, 0, 1]
Output
[-9, -4, 0, 0, 1, 7]

The front cards hold -4 and -9, so the -9 card is detached first; the offset 0 sits in both drawers and is therefore kept twice.

Example 2

Input
chain1 = [], chain2 = []
Output
[]

Neither drawer holds a card, so there is nothing to attach anywhere.

Example 3

Input
chain1 = [], chain2 = [-100, 3]
Output
[-100, 3]

One drawer is bare, so the surviving file is exactly the other drawer's cards in their existing walking order.

Constraints

  • 0 <= chain1.length <= 50
  • 0 <= chain2.length <= 50
  • -100 <= chain1[i], chain2[i] <= 100
  • Both chain1 and chain2 are already in non-decreasing order

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def splice_chains(chain1: list[int], chain2: list[int]) -> list[int]:
Java
public int[] spliceChains(int[] chain1, int[] chain2)
September 7
Apply