Implement a min-heap column allocator
Company: Pinterest
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's competency in data structures (priority queues/min-heaps), online algorithm design for stream processing, and complexity and memory analysis.
Constraints
- 1 <= k <= 100000
- 0 <= len(posts) <= 1000000
- 1 <= posts[i] (each post height is a positive integer)
- Column total heights can grow large; use 64-bit integers to avoid overflow when sums approach 2^63.
Examples
Input: (3, [1, 2, 3, 4, 5])
Expected Output: [0, 1, 2, 0, 1]
Explanation: Round-robin fills the three empty columns first (indices 0,1,2), then index 0 (total 1) is smallest, then index 1 (total 2).
Input: (1, [5, 3, 8])
Expected Output: [0, 0, 0]
Explanation: With a single column, every post goes to index 0.
Input: (4, [])
Expected Output: []
Explanation: No posts to place, so the result is empty regardless of k.
Input: (2, [10, 10, 10, 10])
Expected Output: [0, 1, 0, 1]
Explanation: Equal heights keep tie-breaking to the smaller index, alternating 0,1,0,1 as columns stay balanced.
Input: (3, [5, 5, 5])
Expected Output: [0, 1, 2]
Explanation: All columns start at 0; ties go to the smallest index, filling 0 then 1 then 2.
Input: (2, [1, 100, 1, 1, 1])
Expected Output: [0, 1, 0, 0, 0]
Explanation: After post 2 (h=100) lands in column 1, column 0 stays far lighter, so the remaining small posts all go to column 0.
Input: (5, [7])
Expected Output: [0]
Explanation: Single post with all columns empty picks the smallest index, 0.
Input: (3, [2, 1, 1, 1])
Expected Output: [0, 1, 2, 1]
Explanation: Posts 1-3 fill columns 0,1,2 (heights 2,1,1). The 4th post sees columns 1 and 2 tied at 1, so it picks the smaller index, 1.
Hints
- You only ever need the column with the smallest current total height — a structure that supports fast extract-min is the natural fit. A binary min-heap gives O(log k) per operation.
- Store each heap entry as a pair (currentHeight, columnIndex). Because tuples/pairs compare lexicographically, equal heights automatically break ties toward the smaller column index — no extra logic needed.
- For each post: pop the minimum to learn the chosen column, record that index, then push the same column back with its height increased by the post's height.
- Initialize the heap with all k columns at height 0 up front (heapify is O(k)), rather than inserting them one at a time.