progress

~/problems / Linked lists / Linked lists

Shunt the extra wagons onto a siding

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A freight train is a linked list of ListNode wagons whose val is the load in tonnes; the locomotive pulls at most limit.

Keep the longest front part whose total load is <= limit. The rest is shunted backwards onto a siding, which reverses it. Write shunt(head, limit) returning (train, siding) heads (None if empty), relinking the original nodes.

train 4 -> 2 -> 5 -> 1 -> 3,  limit 7
  4 + 2 = 6 fits, adding 5 would be 11
  train:  4 -> 2
  siding: 3 -> 1 -> 5

train 8 -> 1,  limit 5      train: None      siding: 1 -> 8
train 1 -> 1,  limit 10     train: 1 -> 1    siding: None

Up to 2 * 10^5 wagons; head may be None. Work iteratively and don't copy the wagons into a Python list.

⭐ Bonus: a speed test with 200,000 wagons earns a star in one O(n) pass.

Show hint

add loads until the next wagon would go over, cut there, then reverse the rest with prev, cur, nxt.

Topic: Linked lists. Dummy heads, pointer rewiring, fast/slow pointers.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc