- 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
- 100 lines of Java from the credited upstream file 432.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- No explicit loop blocks 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 int count;3 public Set<String> keys = new HashSet<>();4 public Node prev = null;5 public Node next = null;6 public Node(int count) {7 this.count = count;8 }9 public Node(int count, String key) {10 this.count = count;11 keys.add(key);12 }13}14 15class AllOne {16 public AllOne() {17 head.next = tail;18 tail.prev = head;19 }20 21 public void inc(String key) {22 if (keyToNode.containsKey(key))23 incrementExistingKey(key);24 else25 addNewKey(key);26 }27 28 public void dec(String key) {29 30 31 decrementExistingKey(key);32 }33 34 public String getMaxKey() {35 return tail.prev == head ? "" : tail.prev.keys.iterator().next();36 }37 38 public String getMinKey() {39 return head.next == tail ? "" : head.next.keys.iterator().next();40 }41 42 private Map<String, Node> keyToNode = new HashMap<>();43 private Node head = new Node(0);44 private Node tail = new Node(0);45 46 47 private void addNewKey(final String key) {48 if (head.next.count == 1)49 head.next.keys.add(key);50 else51 insertAfter(head, new Node(1, key));52 keyToNode.put(key, head.next);53 }54 55 56 private void incrementExistingKey(final String key) {57 Node node = keyToNode.get(key);58 node.keys.remove(key);59 60 if (node.next == tail || node.next.count > node.count + 1)61 insertAfter(node, new Node(node.count + 1));62 63 node.next.keys.add(key);64 keyToNode.put(key, node.next);65 66 if (node.keys.isEmpty())67 remove(node);68 }69 70 71 private void decrementExistingKey(final String key) {72 Node node = keyToNode.get(key);73 node.keys.remove(key);74 75 if (node.count > 1) {76 if (node.prev == head || node.prev.count != node.count - 1)77 insertAfter(node.prev, new Node(node.count - 1));78 node.prev.keys.add(key);79 keyToNode.put(key, node.prev);80 } else {81 keyToNode.remove(key);82 }83 84 if (node.keys.isEmpty())85 remove(node);86 }87 88 private void insertAfter(Node node, Node newNode) {89 newNode.prev = node;90 newNode.next = node.next;91 node.next.prev = newNode;92 node.next = newNode;93 }94 95 private void remove(Node node) {96 node.prev.next = node.next;97 node.next.prev = node.prev;98 }99}100