KatInterview

Shortest-Stack Block Placement Order

Heaps, Sorting & SearchAuto-graded · 25 test cases
MediumAuto-gradedHeaps, Sorting & Searchheappriority-queuegreedy

Last 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:

  1. Look at the current total height of every stack.
  2. Choose the stack with the smallest total height.
  3. If several stacks share that smallest height, choose the one with the smallest index.
  4. 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 <= 100000
  • 0 <= 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, where n = len(blocks).
  • If blocks is 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.