progress

~/problems / Heaps / Heaps and priority queues

Balance pins across columns

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 Pinterest

A masonry-style feed shows pins in k columns, numbered 0 .. k-1 from left to right. A column's height is the sum of its pins' heights.

Pins arrive in the order of heights, and each one drops into the currently shortest column; on a tie, the leftmost.

Write layout(heights: list[int], k: int) -> list[list[int]]: for each column, the pin indices placed in it, top to bottom.

layout([30, 10, 20, 15, 5], 2)   # [[0, 3], [1, 2, 4]]
layout([4, 4, 4], 5)             # [[0], [1], [2], [], []]
layout([], 3)                    # [[], [], []]

Tracing the first call (column heights after each pin):

pin height goes to heights
0 30 column 0 (both 0, leftmost wins) 30, 0
1 10 column 1 30, 10
2 20 column 1 30, 30
3 15 column 0 (both 30, leftmost wins) 45, 30
4 5 column 1 45, 35
Two columns drawn to scale: column 0 holds pin 0 (30) and pin 3 (15) for a height of 45, column 1 holds pins 1 (10), 2 (20) and 4 (5) for a height of 35

Constraints: 1 <= k <= 10**5, len(heights) <= 2 * 10**5, 1 <= heights[i] <= 10**4.

⭐ Bonus: a speed test with 200,000 pins and 100,000 columns earns a star in O((n + k) log k). Scanning all k columns for every pin is O(n·k).

Show hint

Each pin needs the column with the smallest (height, column number). Keep the columns in a structure that hands you that minimum quickly.

Topic: Heaps and priority queues. heapq: top-k, k-way merge, two heaps for a running median.

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