← Pinterest Interview Insights
My first instinct was to sort both arrays and just greedily match, but the constraint that boxes push through all prior rooms tripped me up.
First, compute the prefix minimum array of room heights to determine the maximum allowable box height for each room. Then, sort the box heights and greedily assign the smallest possible box to each room from left to right, counting how many boxes can be placed. This greedy strategy maximizes the number of boxes because it preserves larger boxes for later rooms that might have higher constraints.
Pro tip: Clarify that each room can hold at most one box and boxes cannot be reused; this ensures the greedy assignment is valid. Mention that the algorithm runs in O(n log n + m log m) time due to sorting, which is optimal for this problem.
Restate the problem: boxes enter from the left, each room can hold at most one box, and a box can only be placed in room j if its height ≤ the minimum height of rooms 0..j. The goal is to maximize the number of boxes placed.
Create an array where each element represents the minimum room height from the start up to that index. This gives the maximum allowable box height for each room.
Sort the box heights in ascending order. The prefix minimum array is already non-increasing, but we can process rooms in order without sorting them separately.
Iterate through the rooms from left to right. For each room, assign the smallest box that fits (i.e., height ≤ prefix minimum at that room). If no box fits, skip the room. Count the number of assignments.
Explain that sorting takes O(m log m) and the greedy pass takes O(n + m), where n is number of rooms and m is number of boxes. Argue correctness by exchange argument: assigning the smallest possible box never reduces the ability to place boxes in later rooms.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.