✅ C++ | BEATS 98.74% | SET
Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(\log{n})\n- Space complexity:\n Add your space complexity here, e.g. O(n) \nO(n)\n
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(\\log{n})$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass ExamRoom {\nprivate:\n    int N;\n    struct Inv {\n        int l, r, n;\n        Inv(int l, int r, int n) : l{l}, r{r}, n{n} {}\n        int getDistance() const {\n            if (l == -1) return r;\n            if (r == n) return n - l - 1;\n            return (r - l) / 2;\n        }\n        int getSeat() const {\n            if (l == -1) return 0;\n            if (r == n) return n - 1;\n            return (l + r) / 2;\n        }\n        bool operator < (const Inv& inv) const {\n            int d1 = this->getDistance(), d2 = inv.getDistance();\n            if (d1 == d2) return this->l < inv.l;\n            return d1 > d2;\n        }\n    };\n\npublic:\n    set<Inv> s;\n    set<int> seats;\n\n    ExamRoom(int n) {\n        seats.insert(-1);\n        seats.insert(n);\n        N = n;\n        s.insert(Inv(-1, n, n));\n    }\n    \n    int seat() {\n        Inv inv = *s.begin();\n        s.erase(s.begin());\n        int seat = inv.getSeat();\n        s.insert(Inv(inv.l, seat, N));\n        s.insert(Inv(seat, inv.r, N));\n        seats.insert(seat);\n        return seat;\n    }\n    \n    void leave(int p) {\n        auto it = seats.find(p);\n        int l = *prev(it), r = *next(it);\n        s.erase(Inv(l, p, N));\n        s.erase(Inv(p, r, N));\n        s.insert(Inv(l, r, N));\n    }\n};\n```\n**Please upvote if u like the solution :)**
['C++']