Approach
Sorting and greedy selection
For Closest Room, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 37 lines of Python from the credited upstream file 1847.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from sortedcontainers import SortedList2 3 4class Solution:5 def closestRoom(6 self,7 rooms: list[list[int]],8 queries: list[list[int]],9 ) -> list[int]:10 ans = [0] * len(queries)11 qs = [[*q, i] for i, q in enumerate(queries)]12 roomIds = SortedList()13 14 rooms.sort(key=lambda x: -x[1])15 qs.sort(key=lambda x: -x[1])16 17 def searchClosestRoomId(roomIds: SortedList, preferred: int):18 if not roomIds:19 return -120 21 candIds = []22 i = roomIds.bisect_right(preferred)23 if i > 0:24 candIds.append(roomIds[i - 1])25 if i < len(roomIds):26 candIds.append(roomIds[i])27 return min(candIds, key=lambda x: abs(x - preferred))28 29 i = 0 30 for preferred, minSize, index in qs:31 while i < len(rooms) and rooms[i][1] >= minSize:32 roomIds.add(rooms[i][0])33 i += 134 ans[index] = searchClosestRoomId(roomIds, preferred)35 36 return ans37