Shortest-Stack Block Placement Order
Heaps, Sorting & SearchAuto-graded · 25 test casesLast updated
Simulate placing blocks one at a time onto the currently lowest of k stacks, with ties going to the lowest index, and report each chosen stack; tests heap-based greedy simulation.
Shortest-Stack Block Placement
You have num_stacks stacks, numbered 0 to num_stacks - 1. All of them start empty, so each has total height 0.
You are also given a list blocks, where blocks[i] is the height of the i-th block. The blocks arrive in the order given, and each one must be placed on exactly one stack immediately.
For each block, use this rule:
- Look at the current total height of every stack.
- Choose the stack with the smallest total height.
- If several stacks share that smallest height, choose the one with the smallest index.
- Add the block's height to the chosen stack's total.
Return a list with the same length as blocks, where entry i is the index of the stack that received block i.
The rule is evaluated on the totals as they stand when the block arrives, so earlier placements affect later choices.
Constraints
1 <= num_stacks <= 1000000 <= len(blocks) <= 1000000- Each block height is a positive integer.
- Stack totals may grow large, so do not assume they fit in 32 bits (Python integers are unbounded).
- Aim for roughly
O((num_stacks + n) log num_stacks)time, wheren = len(blocks). - If
blocksis empty, return an empty list.
Examples
Example 1
Input: place_blocks(3, [2, 4, 3, 1, 5])
Output: [0, 1, 2, 0, 0]
Example 2
Input: place_blocks(2, [5, 2, 3, 1])
Output: [0, 1, 1, 0]
Example 3
Input: place_blocks(1, [7, 2, 9])
Output: [0, 0, 0]
Hints
Hint 1
Each step needs two operations: find the stack with the lowest (total, index) and then increase that stack's total. Which data structure supports both efficiently?
Hint 2
Store one entry per stack as the pair (total_height, stack_index) in a min-heap. Lexicographic comparison of the pair already encodes the 'lowest index wins ties' rule.
Hint 3
For every block, pop the smallest entry, record its stack index, then push the same stack back with its total increased by the block's height. The heap size stays constant at num_stacks.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every block requires the same two steps:
- Find the stack with the smallest
(total height, index)pair. - Increase that stack's total by the block's height.
A min-heap handles both in O(log k), where k = num_stacks. We keep exactly one entry per stack, of the form (total, index). Python compares tuples lexicographically, so the smallest entry is the stack with the lowest total, and among equal totals the lowest index. This is exactly the placement rule, so no custom comparator is needed.
For each block:
- Read the root
(total, stack)of the heap and appendstackto the answer. - Replace the root with
(total + height, stack)usingheapreplace, which does a pop and a push in a single sift.
Why it is correct
Invariant: before each block is processed, the heap holds exactly one entry (T_s, s) for every stack s, where T_s is that stack's true current total.
- At the start, every stack has total 0 and the heap is built from
(0, s)for alls, so the invariant holds. - The root is the lexicographically smallest pair, which is the stack the rule selects. After recording it, we replace its entry with the updated total, so the invariant is restored. No stale entries ever exist.
By induction, every choice matches the rule, so the output is correct. The tie-break is part of the key, so it does not depend on the heap's internal behavior.
Complexity
- Time:
O(k)to build the heap, thenO(log k)per block, forO(k + n log k)overall. - Space:
O(k)for the heap plusO(n)for the output.
Reference solution
import heapq
from typing import List
def place_blocks(num_stacks: int, blocks: List[int]) -> List[int]:
# One heap entry per stack: (current total height, stack index).
heap = [(0, s) for s in range(num_stacks)]
heapq.heapify(heap)
result = []
for h in blocks:
total, stack = heap[0]
result.append(stack)
heapq.heapreplace(heap, (total + h, stack))
return result