Closest Room - Problem
You're managing a luxury hotel booking system where guests have specific room preferences. Your hotel has n rooms, each with a unique room number and size. You need to efficiently handle k guest queries, where each guest specifies their preferred room number and minimum room size requirement.
For each query, find the room that:
- Has a size of at least the guest's minimum requirement
- Has a room number closest to their preferred number
- In case of ties in distance, choose the room with the smaller room number
If no suitable room exists, return -1 for that query.
Example: If rooms are [[2,130],[3,120],[4,110]] and a guest queries [3,125], only room 2 meets the size requirement (130 โฅ 125), so return 2.
Input & Output
example_1.py โ Basic Hotel Query
$
Input:
rooms = [[2,130],[3,120],[4,110]], queries = [[3,125]]
โบ
Output:
[2]
๐ก Note:
Guest prefers room 3 with minimum size 125. Only room 2 (size 130) meets the requirement. Distance from 3 to 2 is |2-3| = 1.
example_2.py โ Multiple Queries
$
Input:
rooms = [[1,100],[2,200],[3,150]], queries = [[2,100],[2,180]]
โบ
Output:
[2,2]
๐ก Note:
Query 1: Rooms 1,2,3 all meet size 100. Room 2 is exact match for preferred 2. Query 2: Only rooms 2,3 meet size 180. Room 2 (distance 0) is closer than room 3 (distance 1).
example_3.py โ No Valid Room
$
Input:
rooms = [[1,50],[2,60]], queries = [[3,100]]
โบ
Output:
[-1]
๐ก Note:
No room has size โฅ 100, so return -1 for this query.
Constraints
- 1 โค n โค 105
- 1 โค k โค 104
- 1 โค roomIdi, preferredj โค 107
- 1 โค sizei, minSizej โค 107
- All room IDs are unique
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
Sort rooms by size and queries by minimum size requirement (descending)
2
Process High Requirements First
Start with queries needing largest rooms, building valid room set incrementally
3
Binary Search Magic
For each query, binary search the sorted valid rooms to find closest room number
4
Optimal Result
Return the best room for each guest with minimal computational overhead
Key Takeaway
๐ฏ Key Insight: By processing queries in descending order of size requirement and maintaining a sorted set of valid rooms, we transform an O(kรn) problem into an O(n log n) solution using the power of binary search!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code