Problem Description
We are given a list of hotel rooms where each room is represented by an id and a size. For each query consisting of a preferred id and a minimum room size requirement, we must pick the room with size at least the minimum such that the absolute difference between its id and the preferred id is minimized. In the event of a tie, the room with the smaller id is chosen. If no room meets the minimum size requirement, return -1.
Key Insights
- Sort the rooms based on their sizes in descending order.
- Sort the queries in descending order by the required minSize so that we progressively add qualified rooms.
- Use an ordered (balanced) set keyed by room id (or a sorted array with binary search) to quickly find the room id closest to the preferred value.
- For each query, binary search in the ordered set for the closest candidate on both sides (predecessor and successor) and then pick the one with the smallest absolute difference.
Space and Time Complexity
Time Complexity: O((n + k) log n) where n is the number of rooms and k is the number of queries
Space Complexity: O(n + k) for storing the rooms, queries, and the ordered data structure.
Solution
We can solve the problem offline by processing queries in decreasing order of minSize and simultaneously adding all the rooms that satisfy the size requirement into an ordered set (or sorted list). For each query, after inserting all eligible rooms, we use binary search on the ordered set to locate the closest room id to the preferred id. We then check the neighbor keys (if available) to determine which room yields the smallest absolute difference to the preferred id, ensuring that ties are resolved by the smaller room id.