commit 631b49f2e2031626a19f7c9e74f1294ed84cb4bb
parent c2b48d325baa1eb01391be3ad89a1f7b5891f94b
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date: Sun, 29 Sep 2024 11:49:05 +0200
Daily Problem
Diffstat:
2 files changed, 83 insertions(+), 0 deletions(-)
diff --git a/Problems/0432.cpp b/Problems/0432.cpp
@@ -0,0 +1,82 @@
+class AllOne {
+ struct Node {
+ int freq = 0;
+ Node *prev = nullptr;
+ Node *next = nullptr;
+ unordered_set<string> keys;
+ };
+
+ unordered_map<string, Node *> map;
+ Node head = {0, nullptr, &tail};
+ Node tail = {0, &head, nullptr};
+
+ public:
+ void inc(const string &key) {
+ if (map.find(key) != map.end()) {
+ Node *node = map[key];
+ int freq = node->freq;
+ node->keys.erase(key);
+
+ Node *nnode = node->next;
+ if (nnode == &tail || nnode->freq != freq + 1) {
+ map[key] = node->next = nnode->prev = new Node(freq + 1, node, nnode, {key});
+ } else {
+ nnode->keys.insert(key);
+ map[key] = nnode;
+ }
+
+ if (node->keys.empty()) {
+ removeNode(node);
+ }
+ } else {
+ Node *firstNode = head.next;
+ if (firstNode == &tail || firstNode->freq > 1) {
+ map[key] = head.next = firstNode->prev = new Node(1, &head, firstNode, {key});
+ } else {
+ firstNode->keys.insert(key);
+ map[key] = firstNode;
+ }
+ }
+ }
+
+ void dec(const string &key) {
+ if (map.find(key) == map.end()) {
+ return;
+ }
+
+ Node *node = map[key];
+ node->keys.erase(key);
+
+ int freq = node->freq;
+ if (freq == 1) {
+ map.erase(key);
+ } else {
+ Node *pnode = node->prev;
+ if (pnode == &head || pnode->freq != freq - 1) {
+ map[key] = pnode->next = node->prev = new Node(freq - 1, pnode, node, {key});
+ } else {
+ pnode->keys.insert(key);
+ map[key] = pnode;
+ }
+ }
+
+ if (node->keys.empty()) {
+ removeNode(node);
+ }
+ }
+
+ string getMaxKey() const { return tail.prev == &head ? "" : *(tail.prev->keys.begin()); }
+
+ string getMinKey() const { return head.next == &tail ? "" : *(head.next->keys.begin()); }
+
+ private:
+ void removeNode(Node *node) {
+ Node *pnode = node->prev;
+ Node *nnode = node->next;
+
+ pnode->next = nnode;
+ nnode->prev = pnode;
+
+ delete node;
+ }
+};
diff --git a/README.md b/README.md
@@ -329,6 +329,7 @@ for solving problems.
| 0427 | Medium | [Construct Quad Tree](Problems/0427.cpp) |
| 0429 | Medium | [N-ary Tree Level Order Traversal](Problems/0429.cpp) |
| 0430 | Medium | [Flatten a Multilevel Doubly Linked list](Problems/0430.cpp) |
+| 0432 | Hard | [All O`one Data Structure](Problems/0432.cpp) |
| 0433 | Medium | [Minimum Genetic Mutation](Problems/0433.cpp) |
| 0435 | Medium | [Non-overlapping Intervals](Problems/0435.cpp) |
| 0436 | Medium | [Find Right Interval](Problems/0436.cpp) |