- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 54 lines of Python from the credited upstream file exam-room.py.
- The implementation visibly relies on work queue.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 5import heapq6 7 8class ExamRoom(object):9 10 def __init__(self, N):11 """12 :type N: int13 """14 self.__num = N15 self.__seats = {-1: [-1, self.__num], self.__num: [-1, self.__num]}16 self.__max_heap = [(-self.__distance((-1, self.__num)), -1, self.__num)]17 18 def seat(self):19 """20 :rtype: int21 """22 while self.__max_heap[0][1] not in self.__seats or \23 self.__max_heap[0][2] not in self.__seats or \24 self.__seats[self.__max_heap[0][1]][1] != self.__max_heap[0][2] or \25 self.__seats[self.__max_heap[0][2]][0] != self.__max_heap[0][1]:26 heapq.heappop(self.__max_heap) 27 28 _, left, right = heapq.heappop(self.__max_heap)29 mid = 0 if left == -1 \30 else self.__num-1 if right == self.__num \31 else (left+right) 232 self.__seats[mid] = [left, right]33 heapq.heappush(self.__max_heap, (-self.__distance((left, mid)), left, mid))34 heapq.heappush(self.__max_heap, (-self.__distance((mid, right)), mid, right))35 self.__seats[left][1] = mid36 self.__seats[right][0] = mid37 return mid38 39 def leave(self, p):40 """41 :type p: int42 :rtype: void43 """44 left, right = self.__seats[p]45 self.__seats.pop(p)46 self.__seats[left][1] = right47 self.__seats[right][0] = left48 heapq.heappush(self.__max_heap, (-self.__distance((left, right)), left, right))49 50 def __distance(self, segment):51 return segment[1]-segment[0]-1 if segment[0] == -1 or segment[1] == self.__num \52 else (segment[1]-segment[0]) 253 54