Minimum Transfers to Rebalance a Four-Zone Warehouse
Greedy & IntervalsAuto-graded · 22 test casesLast updated
Tests whether you can compute the minimum number of item relocations to rebalance inventory across four warehouse zones using surplus/deficit reasoning.
Minimum Transfers to Rebalance a Four-Zone Warehouse
A warehouse is divided into exactly four zones, numbered 1 through 4. Each zone holds some number of inventory units. You are given the current unit counts across the four zones and a target distribution you need to reach.
In a single transfer, you pick one unit from any zone and move it to any other zone. Units are interchangeable — only the count per zone matters, not which specific unit goes where.
Write a function that computes the minimum number of transfers needed to reach the target distribution, and returns one valid sequence of transfers that achieves it.
A transfer is represented as a two-element list [from_zone, to_zone], where both values are zone numbers (1–4).
Output format
Return a dictionary with exactly two keys:
"min_moves": an integer, the minimum number of transfers required."moves": a list of[from_zone, to_zone]pairs, one per transfer, in the order they are applied.
When multiple optimal sequences exist, output the canonical one: build the sequence by pairing zones with excess units against zones with missing units, processing both groups in ascending zone order.
Precondition
The total number of units is the same in both current and target. You may assume this holds for all inputs.
Constraints
- Both
currentandtargetare lists of exactly 4 non-negative integers. sum(current) == sum(target)for all valid inputs.- Each element of
currentandtargetsatisfies0 ≤ value ≤ 10^5. - If the distribution is already correct, return
{"min_moves": 0, "moves": []}.
Examples
Example 1
Input: rebalance_warehouse([3, 2, 1, 0], [1, 2, 2, 1])
Output: {'min_moves': 2, 'moves': [[1, 3], [1, 4]]}
Example 2
Input: rebalance_warehouse([1, 1, 1, 1], [1, 1, 1, 1])
Output: {'min_moves': 0, 'moves': []}
Example 3
Input: rebalance_warehouse([0, 5, 0, 0], [2, 0, 1, 2])
Output: {'min_moves': 5, 'moves': [[2, 1], [2, 1], [2, 3], [2, 4], [2, 4]]}
Example 4
Input: rebalance_warehouse([4, 0, 3, 1], [2, 3, 1, 2])
Output: {'min_moves': 4, 'moves': [[1, 2], [1, 2], [3, 2], [3, 4]]}
Hints
Hint 1
For each zone, compute how many units it has in excess or in deficit relative to the target. What does the sum of all excesses tell you?
Hint 2
The minimum number of transfers equals the total excess across all over-stocked zones (which equals the total deficit across all under-stocked zones). Think about why no single transfer can do better than reduce this total by 1.
Hint 3
To build the move sequence, expand each over-stocked zone into a list of individual source slots and each under-stocked zone into a list of destination slots, then pair them up in zone order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key observation: only surpluses and deficits matter
Because units are interchangeable, the only thing that distinguishes the current state from the target is how many units each zone has too many or too few. For each zone, compute:
surplus[zone] = current[zone] - target[zone]
A zone with a positive surplus has units to give away; a zone with a negative surplus needs to receive units.
Why the minimum transfer count equals the total surplus
Let P be the sum of all positive surpluses. Every transfer removes one unit from some zone and adds it to another, so it can reduce P by at most 1. The problem is solved exactly when P reaches 0, which means at least P transfers are necessary — that is the lower bound.
A construction that achieves P transfers: for every unit of surplus in an over-stocked zone, create one "source slot"; for every unit of deficit in an under-stocked zone, create one "destination slot". Because totals are equal, both lists have the same length P. Pair them one-to-one and execute each pair as a transfer. Every transfer moves a unit from a zone that genuinely has too many to a zone that genuinely has too few, so it reduces P by exactly 1. After P transfers the distribution matches the target.
Lower bound and construction both give P, so P is optimal.
Canonical sequence
Many pairings are valid. To produce a deterministic result, both lists are built by iterating zones 1 → 4, so the first source slot belongs to the lowest-numbered over-stocked zone, and likewise for destinations. Zipping them in this order gives the canonical sequence the problem asks for.
Edge cases
- If
current == target, all surpluses are 0, both lists are empty, and the function returns{"min_moves": 0, "moves": []}without any special handling. - A zone that already matches its target contributes nothing to either list and is never touched.
Complexity
- Time: O(F + M), where F = 4 (fixed number of zones) and M =
min_moves. Computing surpluses is O(F); expanding the lists and building the output each take O(M). If only the count is needed, the whole thing is O(F) = O(1). - Space: O(M) for the source list, destination list, and output. With two pointers walking the surplus array directly, the working space drops to O(F), but the output itself still requires O(M).
Reference solution
from typing import List, Dict
def rebalance_warehouse(current: List[int], target: List[int]) -> Dict[str, object]:
# Compute per-zone surplus: positive means too many units, negative means too few.
surplus = [current[i] - target[i] for i in range(4)]
sources = [] # one entry per excess unit, in ascending zone order
destinations = [] # one entry per missing unit, in ascending zone order
for zone in range(4):
if surplus[zone] > 0:
sources.extend([zone + 1] * surplus[zone])
elif surplus[zone] < 0:
destinations.extend([zone + 1] * (-surplus[zone]))
# Pair each source slot with a destination slot in the order they were built.
# Because both lists are built in ascending zone order, this yields the
# canonical sequence required by the problem.
moves = []
for from_zone, to_zone in zip(sources, destinations):
moves.append([from_zone, to_zone])
return {"min_moves": len(moves), "moves": moves}