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