- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 75 lines of Java from the credited upstream file 855.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- 1 loop block detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Node {2 public Node prev;3 public Node next;4 public int value;5 6 public Node(int value) {7 this.value = value;8 }9}10 11class ExamRoom {12 public ExamRoom(int n) {13 this.n = n;14 join(head, tail);15 }16 17 public int seat() {18 if (head.next == tail) {19 Node node = new Node(0);20 join(head, node);21 join(node, tail);22 map.put(0, node);23 return 0;24 }25 26 int prevStudent = -1;27 int maxDistToClosest = 0;28 int val = 0; 29 Node pos = null; 30 31 for (Node node = head; node != tail; node = node.next) {32 if (prevStudent == -1) { 33 maxDistToClosest = node.value; 34 pos = node;35 } else if ((node.value - prevStudent) / 2 > maxDistToClosest) {36 maxDistToClosest = (node.value - prevStudent) / 2;37 val = (node.value + prevStudent) / 2;38 pos = node;39 }40 prevStudent = node.value;41 }42 43 if (n - 1 - tail.prev.value > maxDistToClosest) {44 pos = tail;45 val = n - 1;46 }47 48 Node insertedNode = new Node(val);49 join(pos.prev, insertedNode);50 join(insertedNode, pos);51 52 map.put(val, insertedNode);53 return val;54 }55 56 public void leave(int p) {57 Node removedNode = map.get(p);58 join(removedNode.prev, removedNode.next);59 }60 61 private int n;62 private Node head = new Node(-1);63 private Node tail = new Node(-1);64 private Map<Integer, Node> map = new HashMap<>(); 65 66 private void join(Node node1, Node node2) {67 node1.next = node2;68 node2.prev = node1;69 }70 71 private void remove(Node node) {72 join(node.prev, node.next);73 }74}75