The Closest Room coding problem involves a set of hotel rooms, each with an ID and a size. You are given multiple queries, each with a preferred_id and a min_size. For each query, you must find a room that has a size at least min_size and whose ID is as close as possible to the preferred_id. If there's a tie in ID distance, choose the room with the smaller ID.
Amazon uses the Closest Room interview question to test your ability to use offline query processing and advanced data structures. Since there are many queries, a brute-force search for each query would be O(N * Q). The challenge is to process queries in a specific order so that you only ever consider rooms that meet the size requirement.
This problem uses the Offline Queries + Sorting + Ordered Set pattern.
min_size in descending order.preferred_id.Rooms: [(1, 10), (2, 20), (3, 15)] (ID, Size)
Query: pref_id=2, min_size=12
(2, 20), (3, 15), (1, 10).(2, 20) and (3, 15).{2, 3} to an ordered set.2 in {2, 3} is 2.
Result: Room ID 2.bisect in Python on a sorted list, or TreeSet in Java)."Offline processing" is a key technique to mention when queries have multiple constraints. By sorting both the data and the queries by one constraint, you can focus on the other constraint using an efficient data structure.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Absolute Sum Difference | Medium | Solve | |
| Find Right Interval | Medium | Solve | |
| Most Beautiful Item for Each Query | Medium | Solve | |
| Minimum Absolute Difference Between Elements With Constraint | Medium | Solve | |
| Magnetic Force Between Two Balls | Medium | Solve |