KatInterview

Greedy Tile Placement Across Parallel Lanes

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapgreedysimulation

Last updated

Simulate placing items one by one into the currently lowest lane, breaking ties by lowest index, and report each lane's final total using a min-heap.

Greedy Tile Placement Across Parallel Lanes

A gallery page displays tiles in several vertical lanes. You receive the tiles in the order they arrive, and each tile has a positive or zero height. The number of lanes is fixed and every lane starts empty with a total height of 0.

Place the tiles one at a time, in the given order, using this rule:

  • Put the tile into the lane whose current total height is the smallest.
  • If several lanes share that smallest total, choose the one with the smallest lane index (lanes are numbered from 0).
  • Adding a tile increases that lane's total height by the tile's height.

Once every tile has been placed, report the total height of each lane.

Task

Implement a function that takes the list of tile heights (in arrival order) and the number of lanes, and returns a list of length num_lanes where the entry at position i is the final total height of lane i.

Notes

  • If there are no tiles, every lane has total 0.
  • If there are more lanes than tiles, lanes that never receive a tile stay at 0.
  • A tile of height 0 leaves its lane's total unchanged, but it is still assigned according to the rules above.
  • The result must be ordered by lane index, not in any other order.

Constraints

  • 0 <= len(tile_heights) <= 10^5
  • 1 <= num_lanes <= 10^5
  • 0 <= tile_heights[i] <= 10^9
  • Aim for better than scanning every lane for every tile.

Examples

Example 1

Input: lane_totals_after_placement([5, 2, 4, 7, 1], 3)

Output: [5, 9, 5]

Hints

Hint 1

Placing a tile means repeatedly asking for the lane with the minimum total, updating it, and putting it back. Which data structure supports this efficiently?

Hint 2

Store each lane as a pair (total_height, lane_index) in a min-heap. Pair comparison already handles the tie-break by smaller index.

Hint 3

A heap's internal array is not in lane order. After processing all tiles, write each lane's total into the result at its own lane index.