Runway Reservation System
- Airport with single runway
- Reservations for future landings
- Reserve request specifies landing time t
- Add t to the set R if no other landings are scheduled within k minutes
- Remove from set R after plane lands
Algorithm (Keep R as a sorted list)
init: R = [ ]
req(t): if t < now: return "error"
for i in range (len(R)):
if abs(t-R[i]) < k: return "error"
R.append(t)
R = sorted(R)
land: t = R[0]
if (t != now) return error
R = R[1: ] (drop R[0] from R)
Can we do better?
- Sorted list: Appending and sorting takes Θ(n lg n) time. However, it is possible to insert new time/plane rather than append and sort but insertion takes Θ(n) time. A k minute check can be done in O(1) once the insertion point is found.
- Sorted array: It is possible to do binary search to find place to insert in O(lg n) time. Using binary search, we find the smallest i such that R[i] ≥ t, i.e., the next larger element. We then compare R[i] and R[i − 1] against t. Actual insertion however requires shifting elements which requires Θ(n) time.
- Unsorted list/array: k minute check takes O(n) time.
- Min-Heap: It is possible to insert in O(lg n) time. However, the k minute check will require O(n) time.
- Dictionary or Python Set: Insertion is O(1) time. k minute check takes Ω(n) time
BST
Properties
Each node x in the binary tree has a key key(x). Nodes other than the root have a parent p(x). Nodes may have a left child lef t(x) and/or a right child right(x). These are pointers unlike in a heap.
The invariant is: for any node x, for all nodes y in the left subtree of x, key(y) ≤ key(x). For all nodes y in the right subtree of x, key(y) ≥ key(x).
Operations:
- insert(x)
- find_min()
- next_larger(x)
next_larger(x):
if right child not nil, return minimum(right)
else y = parent(x)
while y not nil and x = right(y)
x = y;
y = parent(y)
return y
- rank(t): How many planes are scheduled to land at times ≤ t? The new requirement necessitates a design amendment.
1. walk down the tree to find desired time
2. Add in the nodes that are smaller
3. Add in the subtrees size to the left