question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
exam-room
I think this is a hard problem
i-think-this-is-a-hard-problem-by-yituoz-26ln
This really is a hard problem, there are so many tricky things to handle.
yituozong
NORMAL
2022-06-24T21:21:05.324630+00:00
2022-06-24T21:21:05.324666+00:00
763
false
This really is a hard problem, there are so many tricky things to handle.
8
0
[]
0
exam-room
[Python3] heap & hash table
python3-heap-hash-table-by-ye15-m8ue
\n\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.pq = [(-n, -1, n)]\n self.nei = {-1: [None, n], n: [-1, None]} #
ye15
NORMAL
2021-07-23T20:35:39.786417+00:00
2021-07-23T20:35:50.497408+00:00
1,240
false
\n```\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.pq = [(-n, -1, n)]\n self.nei = {-1: [None, n], n: [-1, None]} # dummy head & tail \n\n def seat(self) -> int:\n while self.nei.get(self.pq[0][1], [None]*2)[1] != self.pq[0][2] or self.pq[0][1] != self.nei.get(self.pq[0][2], [None]*2)[0]: heappop(self.pq)\n _, lo, hi = heappop(self.pq)\n if lo == -1: \n x = 0 \n if hi == self.n: heappush(self.pq, (1-hi, x, hi))\n else: heappush(self.pq, ((x-hi+1)//2, x, hi))\n elif hi == self.n: \n x = self.n-1\n heappush(self.pq, ((lo-x+1)//2, lo, x))\n else: \n x = (lo + hi)//2\n heappush(self.pq, ((lo-x+1)//2, lo, x))\n heappush(self.pq, ((x-hi+1)//2, x, hi))\n self.nei[x] = [lo, hi]\n self.nei[lo][1] = self.nei[hi][0] = x\n return x\n\n def leave(self, p: int) -> None:\n if self.nei[p][0] == -1: \n heappush(self.pq, (-self.nei[p][1], -1, self.nei[p][1]))\n elif self.nei[p][1] == self.n: \n heappush(self.pq, (-self.n+1+self.nei[p][0], self.nei[p][0], self.n))\n else: \n heappush(self.pq, ((self.nei[p][0] - self.nei[p][1] + 1)//2, self.nei[p][0], self.nei[p][1]))\n self.nei[self.nei[p][0]][1] = self.nei[p][1]\n self.nei[self.nei[p][1]][0] = self.nei[p][0]\n self.nei.pop(p)\n```
6
0
['Python3']
1
exam-room
Python heap solution with idea explanation
python-heap-solution-with-idea-explanati-jts7
The basic idea is to use a heap to give access to the largest distance.\nThe item in the heap is [-distance, left, right, valid]\nleft and right are the most le
hongsenyu
NORMAL
2020-04-13T09:22:39.313564+00:00
2020-04-13T09:36:01.482301+00:00
510
false
The basic idea is to use a heap to give access to the largest distance.\nThe item in the heap is [-distance, left, right, valid]\nleft and right are the most left and the most right empty space for a empty segment.\nUse a dict to support the random access to items in heap, (left, right):[-distance, left, right, valid]\nthe distance is right-left if either left or right is the left boundary or right boundary of the class room\notherwise the distance is (right-left)//2\nthe valid is a flag to denote if this item is valid or not. Later in leave(), we do not delete items in heap, but set the flag to False.\nDuring seat(), we will continues to heappop if the heap top is not valid.\nDuring leave(), we try to find the two segments adjacent to p. And then create a merged segment.\n```\nimport heapq\nclass ExamRoom:\n def __init__(self, N: int):\n self.heap_dict = {(0,N-1):[-N, 0, N-1, True]} # By this dict we have direct access to any items in heap\n self.my_heap = [self.heap_dict[(0,N-1)]]\n self.last = N-1\n \n def seat(self) -> int:\n left = right = 0\n while self.my_heap:\n _, left, right, valid = heappop(self.my_heap)\n if valid:\n break\n pos = self.helper(left, right)\n if pos > left:\n dis = (pos - 1 - left)//2\n self.heap_dict[(left, pos-1)] = [-dis, left, pos-1, True]\n heappush(self.my_heap, self.heap_dict[(left, pos-1)])\n if pos < right:\n dis = (right - (pos+1))//2\n self.heap_dict[(pos+1, right)] = [-dis, pos+1, right, True]\n heappush(self.my_heap, self.heap_dict[(pos+1, right)])\n return pos\n \n def helper(self, left, right):\n if left == 0:\n return left\n if right == self.last:\n return right\n return left + (right-left)//2\n \n def leave(self, p: int) -> None:\n left = right = p\n for obj in self.my_heap:\n if obj[2] == p-1 and obj[3]:\n left = obj[1]\n self.heap_dict[(obj[1], obj[2])][3] = False # find the left segment to merge\n if obj[1] == p+1 and obj[3]:\n right = obj[2]\n self.heap_dict[(obj[1], obj[2])][3] = False # find the right segment to merge\n dis = (right - left)//2\n if left == 0 or right == self.last:\n dis = right - left\n self.heap_dict[(left, right)] = [-dis, left, right, True]\n heappush(self.my_heap, self.heap_dict[(left, right)])\n```
6
0
[]
1
exam-room
Java TreeSet both operation O(log n)
java-treeset-both-operation-olog-n-by-ch-88kh
Some people use PriorityQueue to slove this problem, storing interval with descending dist order.\nBut priority queue takes O(n) to delete element.\nSo i wonder
chriszzt
NORMAL
2018-11-24T01:56:27.756854+00:00
2018-11-24T01:56:27.756897+00:00
494
false
Some people use PriorityQueue to slove this problem, storing interval with descending dist order.\nBut priority queue takes O(n) to delete element.\nSo i wonder if we could use treeSet that could take advantage of sorting and deleting by O(logn)\n\nWe need two treeSet, one is for storing Interval called heap\none is for storing occupied seat.\n\nWhen seat(), we find interval with largest dist and divide it by half, return mid point as seat.\n\nWhen leave(int p), we find occupied seats before p and after p, and reconstruct two intervals, delete them from heap, add merged Interval into it, and also delete p from occupied seats.\n\nNote: for seat at 0 and at N-1, we add dummy seat -1 and N, and for Interval class, if we get start as -1, we know the dist should be end. If we get end as N, we know the dist should be N - 1 - s.\n\nWe also need to override equals insde interval class for deleting purpose.\n```\nclass ExamRoom {\n TreeSet<Interval> heap;\n TreeSet<Integer> seats;\n int N;\n public ExamRoom(int N) {\n heap = new TreeSet<>((a, b) -> {\n if (a.dist == b.dist) {\n return a.s - b.s;\n }\n return b.dist - a.dist;\n });\n seats = new TreeSet<>();\n this.N = N;\n heap.add(new Interval(-1, N));\n seats.add(-1);\n seats.add(N);\n }\n \n public int seat() {\n Interval in = heap.first();\n heap.remove(in);\n int div = (in.s + in.e) / 2;\n if (in.s == -1) {\n div = 0;\n } else if (in.e == N) {\n div = N - 1;\n }\n \n Interval left = new Interval(in.s, div);\n Interval right = new Interval(div, in.e);\n heap.add(left);\n heap.add(right);\n seats.add(div);\n return div;\n }\n \n public void leave(int p) {\n int left = seats.lower(p);\n int right = seats.higher(p);\n heap.remove(new Interval(left, p));\n heap.remove(new Interval(p, right));\n seats.remove(p);\n \n heap.add(new Interval(left, right));\n }\n \n private class Interval {\n int s;\n int e;\n int dist;\n \n public Interval(int s, int e) {\n this.s = s;\n this.e = e;\n if (s == -1) {\n this.dist = e;\n } else if (e == N) {\n this.dist = N - 1 - s;\n } else {\n this.dist = (this.e - this.s) / 2;\n }\n }\n \n @Override \n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof Interval)) {\n return false;\n }\n Interval in = (Interval) o;\n return this.s == in.s && this.e == in.e;\n }\n }\n \n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(N);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```
6
0
[]
2
exam-room
c++ | Explain | Set
c-explain-set-by-chirag1293-w0zu
Upvote if you liked the solution\n\nI commented the code for better understanding\n\nIdea:\nThere can be 3 possible ways to position a person\n1. At the 0th ind
chirag1293
NORMAL
2022-07-25T11:39:03.985685+00:00
2022-07-25T11:39:03.985728+00:00
1,007
false
***Upvote if you liked the solution***\n\nI commented the code for better understanding\n\nIdea:\nThere can be 3 possible ways to position a person\n1. At the 0th index\n2. Somewhere in between\n3. At the end\n\nSo first check if 0th position is not present in the set? is yes place the person and return\nfor in between, take every consequetive pair of positions filled, calculate their middle and check if that is bigger than what we got \nfor end position check it after all this and if the closest distance is less than return\n\n```\nclass ExamRoom {\n int n;\n set<int>seats;\npublic:\n ExamRoom(int N) {\n n=N;\n }\n \n int seat() {\n // cur is the current empty position initialised with zero and will be updated in this function\n // dist is the current maximum distance\n int dist=0;\n int cur=0;\n \n // is the seats is empty we can position the person on 0 seat\n if(!seats.empty()){\n auto it=seats.begin();\n \n // calculating initial \n dist=*it;\n \n // doing this because we dont have any previous element to calculate the middle position\n if(dist==0){\n it++;\n }\n \n // calculating the middle position for every pair of positioned person\n while(it!=seats.end()){\n \n // calculating middle position\n int mid=(*it-*(prev(it)))/2;\n \n // if the mid is grater than current grater distance than we found our new answer\n // update dist and cur\n if(dist<mid){\n dist=mid;\n \n // the new position will be mid steps away from prev(it)\n cur=*prev(it)+dist;\n }\n \n // doing this till end\n it++;\n }\n \n // checking for the end position\n if(dist<((n-1)-*(seats.rbegin()))){\n cur=n-1;\n }\n }\n\n // finally insert the cur into set\n // return cur\n seats.insert(cur);\n return cur;\n }\n \n void leave(int p) {\n seats.erase(p);\n }\n};\n```
5
0
['C', 'Ordered Set']
0
exam-room
C++ Set, O(n) seat and O(log(n)) leave
c-set-on-seat-and-ologn-leave-by-mcglam-3r2l
\nclass ExamRoom {\npublic:\n ExamRoom(int N) {\n n = N;\n }\n \n int seat() {\n //If seats are all availble, just seat at 0\n
mcglam
NORMAL
2018-09-25T19:05:53.307896+00:00
2018-10-08T22:35:05.857429+00:00
738
false
```\nclass ExamRoom {\npublic:\n ExamRoom(int N) {\n n = N;\n }\n \n int seat() {\n //If seats are all availble, just seat at 0\n if (seats.empty()) {\n seats.insert(0);\n return 0;\n }\n \n //Consider middle seats \n int res;\n auto it = seats.begin();\n //If no one seats at 0, initialize position 0 as result\n if (*it != 0) {\n res = 0;\n }\n int diff = *it - 0; //diff is the maximum distance to its closest neighbor\n it++; //Here it++, because we should calculate from second postion\n while (it != seats.end()) {\n int dis = *it - *prev(it);\n if (dis / 2 > diff) { //If dis is greater than diff, just update res and diff\n res = *prev(it) + dis / 2;\n diff = dis / 2;\n }\n it++;\n }\n //Consider last seats\n if (n - 1 - *prev(it) > diff) {\n res = n - 1;\n }\n seats.insert(res);\n return res;\n }\n \n void leave(int p) {\n seats.erase(p);\n }\nprivate:\n set<int> seats;\n int n;\n};\n\n```
5
0
[]
2
exam-room
[Java/C++] Short TreeSet PriorityQueue Lambda O(logn) solution with explanation
javac-short-treeset-priorityqueue-lambda-83zq
define a triplet(dist, pre, suc) as a gap. dist = (suc - pre) / 2\n- only put gap with dist >= 1 to the pq. dist == 0 means there is no gap\n- when poll from pq
bitcoinevangelist
NORMAL
2018-06-17T03:45:47.495727+00:00
2018-08-12T20:07:32.220823+00:00
1,732
false
- define a triplet(dist, pre, suc) as a gap. dist = (suc - pre) / 2\n- only put gap with dist >= 1 to the pq. dist == 0 means there is no gap\n- when poll from pq, check the pre and suc of this gap exist and next to each other in the TreeSet or not. If not, discard this gap.\n```java\nclass ExamRoom {\n\n int N;\n TreeSet<Integer> set = new TreeSet<>();\n PriorityQueue<int[]> pq;\n \n public ExamRoom(int N) {\n this.N = N;\n pq = new PriorityQueue<int[]>(Comparator.comparing((int[] v) -> -v[0]).thenComparing((int[] v) -> v[1]));\n }\n \n public int seat() {\n if (set.size() == 0){\n set.add(0);\n return 0;\n } \n int first = set.first();\n int len = first - 0;\n int can = 0;\n int last = set.last();\n if (N - 1 - last > len){\n len = N - 1 - last;\n can = N - 1;\n }\n boolean found = false;\n while (!found && pq.size() > 0){\n int[] arr = pq.poll();\n if (set.contains(arr[1])){\n Integer higher = set.higher(arr[1]);\n if (higher != null && higher.equals(arr[2])){\n found = true;\n if (arr[0] > len || (arr[0] == len && arr[0] + arr[1] < can)){\n can = arr[0] + arr[1];\n set.add(can);\n if (arr[2] - can > 1){\n pq.offer(new int[]{(arr[2] - can) / 2, can, arr[2]});\n }\n if (can - arr[1] > 1){\n pq.offer(new int[]{(can - arr[1]) / 2, arr[1], can});\n }\n return can;\n } else {\n pq.offer(arr);\n }\n }\n }\n }\n set.add(can);\n if (first - can > 1){\n pq.offer(new int[]{(first - can) / 2, can, first});\n } \n if (can - last > 1){\n pq.offer(new int[]{(can - last) / 2, last, can});\n }\n return can;\n }\n \n public void leave(int p) {\n Integer lower = set.lower(p);\n Integer higher = set.higher(p);\n if (lower != null && higher != null){\n pq.offer(new int[]{(higher - lower) / 2, lower, higher});\n }\n set.remove(p);\n }\n}\n```\n\n```c++\nclass mycompare{\npublic:\n bool operator() (const vector<int> & lhs, const vector<int> & rhs){\n if (lhs[0] != rhs[0]){\n return lhs[0] < rhs[0];\n } else {\n return lhs[1] > rhs[1];\n }\n }\n};\n\nclass ExamRoom {\nprivate:\n set<int> st;\n priority_queue<vector<int>, vector<vector<int>>, mycompare> pq;\n int N;\npublic:\n ExamRoom(int N) {\n this->N = N;\n }\n \n int seat() {\n if (st.size() == 0){\n st.insert(0);\n return 0;\n }\n int first = *st.begin();\n int last = *st.rbegin();\n int can = 0;\n int len = first - 0;\n if (N - 1 - last > len){\n len = N - 1 - last;\n can = N - 1;\n }\n bool found = false;\n while (!found && pq.size() > 0){\n auto cur = pq.top();\n // check valid\n auto it = st.find(cur[1]);\n if (it != st.end() && ++it != st.end() && *it == cur[2]){\n // check if it\'s a candidate\n found = true;\n if (cur[0] > len || (cur[0] == len && cur[0] + cur[1] < can)){\n can = cur[0] + cur[1];\n len = cur[0];\n \n if (cur[2] - can > 1){\n pq.push({(cur[2] - can) / 2, can, cur[2]});\n }\n if (can - cur[1] > 1){\n pq.push({(can - cur[1]) / 2, cur[1], can});\n }\n st.insert(can);\n pq.pop();\n return can;\n }\n } else {\n pq.pop();\n }\n }\n st.insert(can);\n if (first - can > 1){\n pq.push({(first - can) / 2, can, first});\n } \n if (can - last > 1){\n pq.push({(can - last) / 2, last, can});\n }\n return can;\n }\n \n void leave(int p) {\n auto cur = st.find(p);\n if (--cur != st.end()){\n int pre = *cur;\n auto suc = st.upper_bound(p);\n if (suc != st.end() && *suc - pre > 1){\n pq.push({(*suc - pre) / 2, pre, *suc});\n }\n }\n st.erase(st.find(p));\n }\n};\n```
5
0
[]
0
exam-room
Best Explanation in whole of solutions 💯 | Don't Miss
best-explanation-in-whole-of-solutions-d-992k
Intuition\nThe problem requires us to seat students in such a way that they are seated as far as possible from the already seated students . \nThe challenge lie
Uday__01
NORMAL
2024-09-29T17:34:34.005087+00:00
2024-09-29T17:44:08.448043+00:00
293
false
# Intuition\nThe problem requires us to seat students in such a way that they are seated as far as possible from the already seated students . \nThe challenge lies in efficiently finding the optimal seat given potentially many occupied seats while ensuring that we can update our data structure when a student leaves. \nThe key observation is that we can treat the empty seats as segments/gaps and determine the best seat to occupy in those segments based on the distance from the occupied seats.\n\n# Approach\n1. **Data Structures**:\n - **Set**: We use a `set<int>` to maintain a list of occupied seats. This allows us to quickly check which seats are taken and to remove seats efficiently when students leave.\n\n2. **Seating Logic**:\n - If the room is empty, the first student sits at seat 0.\n - If there are already occupied seats, we:\n - Calculate the distance from the start of the row (seat 0) to the first occupied seat.\n - Check the gaps between each pair of occupied seats to find the maximum distance.\n - Finally, calculate the distance from the last occupied seat to the end of the row (seat n-1).\n - The seat that provides the maximum distance from the occupied seats among all empty segments is chosen .\n\n3. **Leaving Logic**:\n - When a student leaves, we simply remove their seat from the set of occupied seats. \n\n\n# Complexity\n- **Time complexity**: The `seat` operation involves checking each occupied seat, making it $$O(k)$$ where $$k$$ is the number of occupied seats and also it inserts a new ```best_seat``` which takes $$O(logk)$$. Hence the total time complexity of ```seat``` operation is ```O(k+logk)``` \n\n In worst case ```k``` could go up to ```N``` , so average final time complexity would be $$O(N)$$ ( logN can be ignored )\n\n The `leave` operation runs in $$O(logN)$$ - since it\'s a ordered set\n\n \n \n- **Space complexity**: The space complexity is $$O(k)$$ as we store the occupied seats in a set. This also in worst case can go up to $$O(N)$$\n\n# Code\n```cpp []\nclass ExamRoom {\nprivate:\n int n;\n set<int> seats; // To store occupied seats\n\npublic:\n ExamRoom(int n) : n(n) {}\n\n int seat() {\n if (seats.empty()) {\n seats.insert(0);\n return 0;\n }\n\n // Calculate the largest gap\n int max_dist = -1;\n int best_seat = 0;\n\n // Check the first seat (0 to first occupied seat)\n int first = *seats.begin();\n if (first > 0) {\n int dist = first; // distance from seat 0 to first\n if (dist > max_dist) {\n max_dist = dist;\n best_seat = 0;\n }\n }\n\n // Check gaps between occupied seats\n int prev = -1; // previous occupied seat\n for (int seat : seats) {\n if (prev != -1) {\n int dist = (seat - prev) / 2; // distance to the nearest seat\n if (dist > max_dist) {\n max_dist = dist;\n best_seat = prev + dist;\n }\n }\n prev = seat;\n }\n\n // Check the last seat (last occupied seat to n-1)\n if (prev != -1 && prev < n - 1) {\n int dist = n - 1 - prev; // distance from last occupied seat\n if (dist > max_dist) {\n best_seat = n - 1;\n }\n }\n\n seats.insert(best_seat);\n return best_seat;\n }\n\n void leave(int p) {\n seats.erase(p);\n }\n};\n```\n\n***Upvote if you found it helpful , So it can help many more people ...***\n***And comment if you have any doubts.***\n
4
0
['C++']
0
exam-room
Java simple one TreeSet solution with O(N) seat and O(logN) leave
java-simple-one-treeset-solution-with-on-rrwp
Code\n\nclass ExamRoom {\n int N;\n TreeSet<Integer> seats;\n public ExamRoom(int n) {\n seats = new TreeSet<>(); // ordered set to keep track o
space_cat
NORMAL
2022-11-17T17:05:41.574158+00:00
2022-11-17T17:06:57.996668+00:00
1,746
false
# Code\n```\nclass ExamRoom {\n int N;\n TreeSet<Integer> seats;\n public ExamRoom(int n) {\n seats = new TreeSet<>(); // ordered set to keep track of students\n this.N = n;\n }\n \n public int seat() {\n int student = 0;\n \n if (seats.size() > 0) { // if at least one student, otherwise seat at 0\n int dist = seats.first(); // the student at lowest seat \n Integer prev = null; \n for (Integer seat: seats) { \n if (prev != null) { \n int d = (seat - prev)/2; // every time we see a new student we can seat them between 2 other students\n if (d > dist) { // select the max range\n dist = d; \n student = prev + d; \n }\n }\n prev = seat; \n }\n if (N - 1 - seats.last() > dist) {\n student = N-1;\n }\n }\n seats.add(student);\n return student;\n }\n \n public void leave(int p) {\n seats.remove(p);\n }\n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(n);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```
4
0
['Java']
2
exam-room
[JAVA] O(logN) seat/leave - TreeSet solution
java-ologn-seatleave-treeset-solution-by-41z2
\nclass ExamRoom {\n \n private final int max;\n private final TreeSet<Interval> available;\n private final TreeSet<Integer> taken;\n \n publi
yurokusa
NORMAL
2022-05-28T20:58:54.652849+00:00
2022-05-28T20:58:54.652879+00:00
936
false
```\nclass ExamRoom {\n \n private final int max;\n private final TreeSet<Interval> available;\n private final TreeSet<Integer> taken;\n \n public ExamRoom(int n) {\n this.max = n - 1;\n this.available = new TreeSet<>((a, b) -> {\n var distA = getMinDistance(a);\n var distB = getMinDistance(b);\n return distA == distB ? a.s - b.s : distB - distA;\n });\n this.available.add(new Interval(0, max));\n this.taken = new TreeSet<>();\n }\n \n public int seat() {\n var inter = available.pollFirst();\n var idx = getInsertPosition(inter);\n taken.add(idx);\n if ((idx - 1) - inter.s >= 0)\n available.add(new Interval(inter.s, idx - 1));\n if (inter.e - (idx + 1) >= 0)\n available.add(new Interval(idx + 1, inter.e));\n return idx;\n }\n \n public void leave(int p) {\n taken.remove(p);\n var lo = taken.lower(p);\n if (lo == null)\n lo = -1;\n var hi = taken.higher(p);\n if (hi == null)\n hi = max + 1;\n available.remove(new Interval(lo + 1, p - 1));\n available.remove(new Interval(p + 1, hi - 1));\n available.add(new Interval(lo + 1, hi - 1));\n }\n \n private int getInsertPosition(Interval inter) {\n if (inter.s == 0)\n return 0;\n else if (inter.e == max)\n return max;\n else\n return inter.s + (inter.e - inter.s) / 2;\n }\n \n private int getMinDistance(Interval in) {\n return in.s == 0 || in.e == max ? in.e - in.s : (in.e - in.s) / 2;\n }\n \n private final class Interval {\n private final int s;\n private final int e;\n \n Interval(int s, int e) {\n this.s = s;\n this.e = e;\n }\n \n @Override\n public String toString() {\n return "[" + s + "," + e + "]";\n }\n }\n}\n```
4
0
['Java']
0
exam-room
Java TreeSet Solution: Both seat() and leave() in O(log(N)), Beating the Leetcode Solution
java-treeset-solution-both-seat-and-leav-d41a
My idea is to maintain an ordered treeset of intervals rather than students. \nEach seat() will poll the first interval. \n\n\nclass Pair{\n\tInteger start;\n\t
saraband
NORMAL
2020-04-12T05:30:12.104109+00:00
2020-04-12T05:31:22.373634+00:00
1,078
false
My idea is to maintain an ordered treeset of intervals rather than students. \nEach seat() will poll the first interval. \n\n```\nclass Pair{\n\tInteger start;\n\tInteger end;\n\tint N;\n \n\tpublic int seat() {\n\t\tif (start == null) return 0;\n\t\tif (end == null) return N-1;\n\t\treturn (start + end) / 2;\n\t}\n\tpublic int size() {\n\t\tif (start == null && end == null) return N ;\n\t\tif (start == null ) {\n\t\t\treturn end;\n\t\t}\n\t\tif (end == null) {\n\t\t\treturn N - 1 - start;\n\t\t}\n\t\tint mid = (start + end)/2;\n\t\treturn mid - start;\t\t\n\t} \n\t\n\tpublic Pair(int N, Integer start, Integer end) {\n\t\tthis.N = N;\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t}\n\t\n\tpublic List<Pair> split(){\n\t\tList<Pair> list = new ArrayList<>();\n\t\tif (start == null) {\n\t\t\tlist.add( new Pair(N, 0, end) );\n\t\t\treturn list;\n\t\t}\n\t\t\n\t\tif (end == null) {\n\t\t\tlist.add( new Pair (N, start, N-1));\n\t\t\treturn list;\n\t\t}\n\t\t\n\t\t\n\t\tint mid = (start + end)/2;\n\t\tPair a = new Pair(N, start, mid);\n\t\tPair b = new Pair(N, mid, end);\n\t\t\n\t\tlist.add(a) ;\n\t\tlist.add(b) ;\n\t\treturn list;\n\t}\n}\n\nclass MyCom implements Comparator<Pair>{\n\tpublic int compare(Pair a, Pair b) {\n\t\tif (a.size()!= b.size()) {\n\t\t\treturn - a.size() + b.size();\n\t\t}\n\t\tif (a.start == null || b.start == null) {\n\t\t\tif (a.start == null && b.start == null) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (a.start == null) {\n\t\t\t\treturn - 1;\n\t\t\t}\n\t\t\tif (b.start == null) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\treturn a.start - b.start;\n\t}\n}\n\n\nclass ExamRoom {\n\tTreeSet<Pair> tree = new TreeSet<>(new MyCom());\n\tHashMap<Integer , Pair> startMap = new HashMap<>();\n\tHashMap<Integer , Pair> endMap = new HashMap<>();\n\tint N ; \n public ExamRoom(int N) {\n this.N = N;\n Pair p = new Pair(N, null, null);\n tree.add(p);\n startMap.put(null, p);\n endMap.put(null, p); \n }\n \n public int seat() {\n Pair pair = tree.pollFirst();\n int ans = pair.seat();\n startMap.remove(pair.start);\n endMap.remove(pair.end);\n for (Pair p: pair.split()) {\n \ttree.add(p);\n \tstartMap.put(p.start, p);\n \tendMap.put(p.end, p); \t\n }\n return ans;\n }\n \n public void leave(int p) {\n \tif (p == 0) {\n \t\tPair a = startMap.get(0);\n \t\tstartMap.remove(0);\n \t\tendMap.remove(a.end);\n \t\ttree.remove(a);\n \t\t\n \t\tPair c = new Pair(N, null, a.end);\n \t\tstartMap.put(c.start, c);\n \t\tendMap.put(c.end, c);\n \t\ttree.add(c);\n \t\treturn;\n \t}\n \t\n \tif (p == N-1) {\n \t\tPair a = endMap.get(N-1);\n \t\tendMap.remove(N-1);\n \t\tstartMap.remove(a.start);\n \t\ttree.remove(a);\n \t\t\n \t\tPair c = new Pair(N, a.start, null);\n \t\tstartMap.put(c.start, c);\n \t\tendMap.put(c.end, c);\n \t\ttree.add(c);\n \t\treturn;\n \t}\n \t \t\n \t\n \t\n Pair b = startMap.get(p);\n Pair a = endMap.get(p);\n startMap.remove(p);\n endMap.remove(p);\n \n if (a!=null) {\n \tendMap.remove(a.end);\n startMap.remove(a.start);\n }\n if (b!=null) {\n \tstartMap.remove(b.start);\n endMap.remove(b.end);\n }\n \n tree.remove(a);\n tree.remove(b);\n \n Pair c = new Pair(N, a.start, b.end);\n startMap.put(c.start, c);\n endMap.put(c.end, c);\n tree.add(c);\n } \n}\n```
4
0
['Tree', 'Java']
1
exam-room
OOP design simplifies this to log(N) seat + leave. Java code attached.
oop-design-simplifies-this-to-logn-seat-vyy7m
This has better order complexity than the one mentioned in the editorial.\n\n\nclass ExamRoom {\n final int N;\n final IntervalQueue queue;\n public Ex
gauravsen
NORMAL
2019-11-26T07:13:15.934609+00:00
2019-11-26T07:13:15.934645+00:00
395
false
This has better order complexity than the one mentioned in the editorial.\n\n```\nclass ExamRoom {\n final int N;\n final IntervalQueue queue;\n public ExamRoom(int N) {\n queue = new IntervalQueue(N);\n this.N = N;\n }\n \n public int seat() {\n final Interval largestInterval = queue.poll();\n final int partition;\n if(largestInterval.start == 0) {\n partition = 0;\n } else if (largestInterval.end == N - 1) {\n partition = N - 1;\n } else {\n partition = (largestInterval.start + largestInterval.end) / 2;\n }\n if(partition > largestInterval.start) {\n queue.add(largestInterval.start, partition - 1);\n } \n if(partition < largestInterval.end) {\n queue.add(partition + 1, largestInterval.end);\n }\n return partition;\n }\n \n public void leave(int p) {\n queue.add(p, p);\n queue.merge(p);\n queue.merge(p - 1);\n }\n}\n\nclass Interval implements Comparable<Interval> {\n final int start, end, size;\n \n public Interval(int start, int end, int N) {\n this.start = start;\n this.end = end;\n int length = end - start;\n if(start == 0 || end == N - 1) {\n this.size = length;\n } else {\n this.size = length / 2;\n }\n }\n \n public int compareTo(Interval other) {\n final int diff = other.size - this.size;\n if(diff != 0) {\n return diff;\n }\n return this.start - other.start;\n }\n}\n\nclass IntervalQueue {\n final TreeSet<Interval> orderedSet = new TreeSet<>();\n final int N;\n //map interval starting index i to it\'s ending point and vice versa\n final Map<Integer, Integer> startToEnd = new HashMap<>(), endToStart = new HashMap<>();\n \n public IntervalQueue(final int N) {\n this.N = N;\n add(0, N - 1);\n }\n \n public Interval poll() {\n final Interval largestInterval = orderedSet.first();\n remove(largestInterval.start, largestInterval.end);\n return largestInterval;\n }\n \n public void add(final int start, final int end) {\n startToEnd.put(start, end);\n endToStart.put(end, start);\n orderedSet.add(new Interval(start, end, N));\n }\n \n public void remove(int start, int end) {\n endToStart.remove(end);\n startToEnd.remove(start);\n orderedSet.remove(new Interval(start, end, N));\n }\n \n //Merge the two intervals separated at partition ((l , p), (p + 1, r)) -> (l, r)\n public void merge(final int p) {\n if(p >= 0 && p < N - 1 && startToEnd.containsKey(p + 1) && endToStart.containsKey(p)) {\n final int l = endToStart.get(p), r = startToEnd.get(p + 1);\n remove(l, p);\n remove(p + 1, r);\n add(l, r);\n }\n }\n}\n```
4
1
[]
0
exam-room
Pyhton Solution using Heaps
pyhton-solution-using-heaps-by-abishek_9-dwxv
Solution Intuition - \n\nKeep track of the following data structure. A heap of ([ left-right, left,right]) called stack in the code below, where the students ar
abishek_90
NORMAL
2019-03-31T17:20:12.815304+00:00
2019-03-31T17:20:12.815345+00:00
631
false
Solution Intuition - \n\nKeep track of the following data structure. A heap of ([ left-right, left,right]) called stack in the code below, where the students are currently in positions left and right. \n\nOn arrival of a student, sample from this min-heap and place the new student in the middle of left and right. Some care needs to be taken in case of boundary cases.\n\nTo remove a student, observe that each removed position occurs at-most twice in this heap. So, we remove those two entries and replace it by a contiguous single element in the heap. Again, little care is needed to handle the boundary conditions.\n\nPlease comment and let me know if the code is unclear or needs more explanation.\n\n\n```\nclass ExamRoom(object):\n\n def __init__(self, N):\n """\n :type N: int\n """\n self.stack = []\n self.N = N\n \n\n def seat(self):\n """\n :rtype: int\n """\n \n if len(self.stack) == 0:\n heapq.heappush(self.stack,[-int((2*self.N-1)/2),0,2*self.N-1])\n return 0\n else:\n top_width = heapq.heappop(self.stack)\n left = top_width[1]\n right = top_width[2]\n if top_width[0]==0:\n return -1\n if 0 <= left < right <= self.N-1:\n idd = int((left+right)/2)\n heapq.heappush(self.stack,[-int((idd-left)/2),left,idd])\n heapq.heappush(self.stack,[-int((right-idd)/2),idd,right])\n return idd\n if left < 0:\n heapq.heappush(self.stack,[-int((right)/2),0,right])\n return 0\n if right > self.N-1:\n heapq.heappush(self.stack,[-int((self.N-1-left)/2),left,self.N-1])\n return self.N-1\n \n\n def leave(self, p):\n """\n :type p: int\n :rtype: None\n """\n temp = []\n nr = self.N+1\n nl = -1\n while len(self.stack) > 0:\n c_seat = heapq.heappop(self.stack)\n \n if c_seat[1] == p :\n nr = c_seat[2]\n continue\n elif c_seat[2] == p:\n nl = c_seat[1]\n continue\n else:\n heapq.heappush(temp,c_seat)\n \n if nl < 0 and nr < self.N:\n nl = -nr\n elif nl >=0 and nr > self.N-1:\n nr = (2*(self.N-1))-nl\n \n n_seat = [-int((nr-nl)/2),nl,nr]\n heapq.heappush(temp,n_seat)\n while len(temp) > 0:\n c_node = heapq.heappop(temp)\n heapq.heappush(self.stack,c_node)\n \n```
4
0
[]
2
exam-room
Python PriorityQueue solution
python-priorityqueue-solution-by-pl04351-grvr
Same idea with https://leetcode.com/problems/exam-room/discuss/148595/Java-PriorityQueue-with-customized-object.-seat:-O(logn)-leave-O(n)-with-explanation. \n\n
pl04351820
NORMAL
2018-10-27T22:46:10.020001+00:00
2018-10-27T22:46:10.020066+00:00
742
false
Same idea with https://leetcode.com/problems/exam-room/discuss/148595/Java-PriorityQueue-with-customized-object.-seat:-O(logn)-leave-O(n)-with-explanation. \n\n```\nfrom heapq import heappush, heappop, heapify\nclass Interval:\n def __init__(self, l, r, N):\n self.l = l\n self.r = r\n if l == -1:\n self.dist = r\n elif r == N:\n self.dist = N - 1 - l\n else:\n self.dist = abs(l -r) // 2\n \n def __lt__(self, other): \n if self.dist == other.dist:\n return self.l < other.l\n else:\n return self.dist >= other.dist\n\nclass ExamRoom:\n def __init__(self, N):\n self.N = N\n self.heap = []\n heappush(self.heap, Interval(-1, N, N))\n\n def seat(self):\n """\n :rtype: int\n """\n seat = 0\n interval = heappop(self.heap)\n if interval.l == -1: seat = 0\n elif interval.r == self.N: seat = self.N - 1\n else: seat = (interval.l + interval.r) // 2\n \n heappush(self.heap, Interval(interval.l, seat, self.N))\n heappush(self.heap, Interval(seat, interval.r, self.N)) \n\n return seat\n \n def leave(self, p):\n head, tail = None, None\n for interval in self.heap:\n if interval.l == p:\n head = interval\n elif interval.r == p:\n tail = interval\n if head != None and tail != None:\n break\n \n self.heap.remove(head)\n self.heap.remove(tail)\n \n self.heap.append(Interval(tail.l , head.r, self.N))\n heapify(self.heap)\n```
4
0
[]
2
exam-room
O(logn) for both seat and leave. Easy and well commented solution with approach.
ologn-for-both-seat-and-leave-easy-and-w-r88x
The idea is that whenever we seat a student, the student divides the interval between the next available left and right students into two parts. \n2. Have a Pri
usn001
NORMAL
2021-09-07T10:10:36.523770+00:00
2021-09-07T10:12:12.302928+00:00
446
false
1. The idea is that whenever we seat a student, the student divides the interval between the next available left and right students into two parts. \n2. Have a PriorityQueue(TreeSet here) that gives you the largest interval where a new student can sit at any point\n3. Whenever a student leaves merge the left and right interval and add it back to the queue.\n\n```\n // Interval class to give the length and mid point of the interval\n class Interval implements Comparable<Interval> {\n int start;\n int end;\n Interval(int start, int end) {\n this.start = start;\n this.end = end;\n }\n \n // gives the mid point of the interval\n int mid() {\n return (start + end)/2;\n }\n \n // gives the interval length. handles cases for first and last element\n // if first or last seat and it is empty then return the closest student. else return the closest student on either side\n int diff() {\n if (this.start == 0 && !set.contains(0)) {\n return this.end;\n }\n if (this.end == n-1 && !set.contains(n-1)) {\n return n-1 - this.start;\n }\n return (this.end-this.start)/2;\n }\n \n // sort by length first. If they are the same, then sort by start index\n public int compareTo(Interval a) {\n if (this.diff() == a.diff()) {\n return Integer.compare(a.start, this.start);\n } else {\n return Integer.compare(this.diff(), a.diff());\n }\n }\n }\n \n TreeSet<Interval> q;\n \n TreeSet<Integer> set;\n \n int n;\n \n public ExamRoom(int n) {\n set = new TreeSet<>();\n q = new TreeSet<>();\n q.add(new Interval(0, n-1));\n this.n = n;\n }\n \n public int seat() {\n // get intervals by highest length\n Interval in = q.pollLast();\n // cases for ends of the array\n if (in.start == 0) {\n if (!set.contains(0)) {\n set.add(0);\n q.add(new Interval(in.start, in.end));\n return 0;\n }\n }\n if (in.end == this.n-1) {\n if (!set.contains(n-1)) {\n set.add(n-1);\n q.add(new Interval(in.start, in.end));\n return n-1;\n }\n }\n int mid = in.mid();\n set.add(mid);\n \n // get the left interval and right interval\n Interval left = new Interval(in.start, mid);\n Interval right = new Interval(mid, in.end);\n // if the interval has more empty seats, add it\n if (left.diff() > 0) {\n q.add(left);\n }\n if (right.diff() > 0) {\n q.add(right);\n }\n return mid;\n }\n \n public void leave(int p) {\n // get the next and previous closest student\n Integer lower = set.lower(p);\n Integer higher = set.higher(p);\n \n // cases for ends of array\n if (higher != null) {\n q.remove(new Interval(p, higher));\n }\n if (lower != null) {\n q.remove(new Interval(lower, p));\n }\n\n set.remove(p);\n \n //merge the left and right intervals\n if (lower == null && higher == null) {\n q.add(new Interval(0, n-1));\n } else if (lower == null) {\n q.add(new Interval(0, higher));\n } else if (higher == null) {\n q.add(new Interval(lower, n-1));\n } else {\n q.add(new Interval(lower, higher)); \n }\n \n }\n\n```
3
5
[]
0
exam-room
[C++] O(logn) for both leave and seat using hash map and set
c-ologn-for-both-leave-and-seat-using-ha-12g0
First let\'s define a segment to be a tuple of {start, end} indicating that the seats between start and end (inclusive) are available. When a student is taking
hoangnhat
NORMAL
2021-07-27T07:12:22.276588+00:00
2021-07-27T07:13:20.771141+00:00
458
false
First let\'s define a segment to be a tuple of `{start, end}` indicating that the seats between `start` and `end` (inclusive) are available. When a student is taking a seat, in order to maximize the distance to the closest student, we must find the **largest** available segment. Initially, all seats are empty, so the starting segment is simply `{0, n - 1}`.\n\nSo for `seat()`, the problem comes down to how we can efficiently compute the largest available segment, then we can easily figure out the seat index by taking the middle seat of the segment. Binary search tree is a suitable data structure here because it lets us find largest / smaller element in `O(logn)`.\n\n`leave()` is trickier, since by leaving a seat `p`, we need to merge any existing segments that are adjacent to `p`:\n\nWhen a student leaves seat `p`, we need to merge *at most* two segments that are adjacent to `p` :\n+ if there is a segment ending at `p - 1` (`first half`) and another starting at `p + 1` (`second half`), our resulting segment is the `{start of first half, end of second half}`\n+ if there is only the first half, then it is `{start of first half, p}`\n+ if there is only the second half, then it is `{p, end of second half}`\n+ if there aren\'t any adjacent segments, simply use `{p, p}`\n\nTo keep track of adjacent segments, we can use two `unordered_maps` that map from the either the start or end of a segment to its corresponding iterator in the `set`. This allows us to merge adjacent segments and update the `set` in `O(logn)` time as well.\n\n```c++\nstruct cmp {\n \n const int n;\n \n cmp(int n): n(n) {}\n \n int getMid(pair<int, int> p1) const {\n if (p1.first == 0 || p1.second == n - 1) {\n return p1.second - p1.first;\n } else {\n return (p1.second - p1.first) / 2;\n }\n }\n \n bool operator()(pair<int, int> p1, pair<int, int> p2) const {\n int m1 = getMid(p1);\n int m2 = getMid(p2);\n \n if (m1 == m2) {\n return p1.first < p2.first;\n }\n \n return m1 > m2;\n }\n};\n\nclass ExamRoom {\n \n using iterator = set<pair<int, int>, cmp>::iterator;\n set<pair<int, int>, cmp> s;\n unordered_map<int, iterator> starts;\n unordered_map<int, iterator> ends;\n \n const int n;\n \n void insert(pair<int, int> p) {\n auto [start, end] = p;\n auto [it, inserted] = s.insert({start, end});\n starts[start] = it;\n ends[end] = it;\n }\n \n void erase(pair<int, int> p) {\n auto [start, end] = p;\n s.erase({start, end});\n starts.erase(start);\n ends.erase(end);\n }\n \npublic:\n ExamRoom(int n): s(cmp(n)), n(n) {\n s.insert({0, n - 1});\n }\n \n int seat() {\n auto [start, end] = *s.begin();\n erase(*s.begin());\n \n int mid;\n \n if (start == 0) {\n mid = 0;\n } else if (end == n - 1) {\n mid = n - 1;\n } else {\n mid = start + (end - start) / 2;\n }\n\n if (mid > start) {\n insert({start, mid - 1});\n }\n\n if (mid < end) {\n insert({mid + 1, end});\n }\n \n return mid;\n }\n \n void leave(int p) {\n int start = p;\n int end = p;\n\n if (ends.count(p - 1)) {\n auto firstHalf = ends[p - 1];\n auto [firstHalfStart, firstHalfEnd] = *firstHalf;\n erase(*firstHalf);\n start = firstHalfStart;\n }\n\n if (starts.count(p + 1)) {\n auto secondHalf = starts[p + 1];\n auto [secondHalfStart, secondHalfEnd] = *secondHalf;\n erase(*secondHalf);\n end = secondHalfEnd;\n }\n\n insert({start, end});\n }\n};\n```
3
0
[]
0
exam-room
C# O(1) Leave O(n) Seat
c-o1-leave-on-seat-by-jakobwwilson-hfko
\nVery similar to other solutions, but since no two people will ever sit in the same place at the same time, we can store our linked list nodes in a dictionary
jakobwwilson
NORMAL
2021-06-19T17:56:05.436123+00:00
2021-06-19T17:56:51.898699+00:00
248
false
\nVery similar to other solutions, but since no two people will ever sit in the same place at the same time, we can store our linked list nodes in a dictionary for quick lookup to remove them. Since we store the linked list node instead of just the value, we can do a O(1) removal because the linked list does not have to find the node. \n\nIt seems like a small improvement. But it beat ~94% of others for time in C#. \n\n```\npublic class ExamRoom {\n\n private Dictionary<int, LinkedListNode<int>> map = new Dictionary<int, LinkedListNode<int>>();//Pointers to the linked list nodes in the list below\n private LinkedList<int> seats = new LinkedList<int>();//A sorted list of the seats taken\n private int n;\n \n public ExamRoom(int n) {\n this.n = n;\n }\n \n public int Seat() {\n \n if(seats.Count < 1)//Handle empty edge case\n {\n map[0] = seats.AddFirst(0);\n return 0;\n }\n \n int first = seats.First.Value;//the max distance if we seat at 0\n int mid = Int32.MinValue;//Computed below. The max distance for and seat in-between other seats\n int last = n - seats.Last.Value - 1;//the max distance if we seat at n-1\n \n \n LinkedListNode<int> before = null;\n for(LinkedListNode<int> l = seats.First; l != null && l.Next != null; l = l.Next)\n {\n int dist = ComputeMinDist(l, l.Next);\n if(dist > mid)\n {\n before = l;\n mid = dist;\n }\n }\n \n \n if(first >= mid && first >= last)//favor the first spot since it\'s the smallest seat number\n {\n map[0] = seats.AddFirst(0);\n return 0;\n }\n else if(mid >= first && mid >= last)//else favor the middle spots their seat numbers are smaller than the end\n {\n int val = before.Value + ((before.Next.Value - before.Value) / 2);\n map[val] = seats.AddAfter(before, val);\n return val;\n }\n else//last favor the end spot \n {\n map[n-1] = seats.AddLast(n-1);\n return n-1;\n }\n }\n \n\n private int ComputeMinDist(LinkedListNode<int> one, LinkedListNode<int> two)\n {\n int netDist = two.Value - one.Value - 1;//get the empty spaces between\n if(netDist%2 == 0)//if it\'s even, use dist/2 because one side will be shorter\n return (netDist/2);\n else//if it\'s odd, add one since there will be even spacing on either side\n return netDist/2 + 1;\n \n }\n \n\n public void Leave(int p) \n {\n LinkedListNode<int> target = map[p];//get the node from the map\n seats.Remove(target);//remove it from the linked list (this is O(1) since we pass the node in instead of the value)\n map.Remove(p);//remove the node from the map so the space is opened up again\n }\n}\n```
3
0
[]
1
exam-room
[C++] (log n) for both operations. Using two std::sets
c-log-n-for-both-operations-using-two-st-rz7b
The basic idea is we keep current people seating in set "cur" and candidates for seating next in set "cand".\nlet\'s talk a little bit about candidate set, it i
kkgmig29
NORMAL
2020-09-09T02:01:20.893643+00:00
2020-09-09T02:01:20.893697+00:00
460
false
The basic idea is we keep current people seating in set "cur" and candidates for seating next in set "cand".\nlet\'s talk a little bit about candidate set, it is a set of pair<int, int> and the first element is distance from the next person and the second element is the index. We sort this set using greater<pair<int,int>> so the cand.begin() will point out to the candidate with the greatest distance from the next person. We also use the trick of adding indexes in negative format, so they will be sorted from the left.\n```\nclass ExamRoom {\npublic:\n int n;\n set<int> cur;\n set<pair<int, int>, greater<pair<int, int>>> cand;\n ExamRoom(int N) {\n n = N;\n }\n \n void add_candidate(int a, int b) {\n int next_idx = (a + b) / 2;\n if (next_idx != a) {\n cand.emplace(min(abs(b - next_idx), abs(a - next_idx)), -next_idx);\n }\n }\n \n void delete_candidate(int a, int b) {\n int next_idx = (a + b) / 2;\n if (next_idx != a) {\n auto p = make_pair(min(abs(b - next_idx), abs(a - next_idx)), -next_idx);\n cand.erase(p);\n }\n }\n \n int seat() {\n if (cur.empty()) {\n cur.insert(0);\n cand.emplace(n - 1, -(n - 1));\n return 0;\n }\n auto [len, idx] = *cand.begin();\n idx = -idx;\n cand.erase(cand.begin());\n auto next = cur.upper_bound(idx);\n if (next != cur.end()) {\n add_candidate(idx, *next);\n }\n auto prev = cur.upper_bound(idx);\n if (prev != cur.begin()) {\n prev--;\n add_candidate(*prev, idx);\n }\n cur.insert(idx);\n return idx;\n \n }\n \n void leave(int p) {\n cur.erase(p);\n if (cur.empty()) {\n cand.clear();\n return;\n }\n int next_idx = -1, prev_idx = -1;\n auto next = cur.upper_bound(p);\n if (next != cur.end()) {\n next_idx = *next;\n delete_candidate(p, *next);\n }\n auto prev = cur.upper_bound(p);\n if (prev != cur.begin()) {\n prev--;\n prev_idx = *prev;\n delete_candidate(*prev, p);\n }\n if (cur.size() == 1) {\n cand.clear();\n int idx = *cur.begin();\n if (idx != 0)\n cand.emplace(idx, 0);\n if (idx != n - 1)\n cand.emplace(n - 1 - idx, -(n - 1));\n return;\n }\n if (p == 0) {\n cand.emplace(*cur.begin(), 0);\n } else if (p == n - 1) {\n cand.emplace(n - 1 - *cur.rbegin(), -(n - 1));\n } else {\n if (next_idx >= 0 && prev_idx >= 0) {\n add_candidate(prev_idx, next_idx);\n }\n }\n }\n};\n```
3
0
[]
0
exam-room
Confusion in sample example
confusion-in-sample-example-by-foodie_co-xx80
can someone help me understand how student will sit at seat 2, and not at seat 6 at line marked with *****\n\nvim\nInput: ["ExamRoom","seat","seat","seat","seat
foodie_codes
NORMAL
2020-08-31T10:16:36.817167+00:00
2020-08-31T10:16:36.817213+00:00
185
false
can someone help me understand how student will sit at seat 2, and not at seat 6 at line marked with `*****`\n\n```vim\nInput: ["ExamRoom","seat","seat","seat","seat","leave","seat"], [[10],[],[],[],[],[4],[]]\nOutput: [null,0,9,4,2,null,5]\n\nExplanation:\nExamRoom(10) -> null\nseat() -> 0, no one is in the room, then the student sits at seat number 0.\nseat() -> 9, the student sits at the last seat number 9.\nseat() -> 4, the student sits at the last seat number 4.\nseat() -> 2, the student sits at the last seat number 2. *****\nleave(4) -> null\nseat() -> 5, the student sits at the last seat number 5.\n```
3
0
[]
3
exam-room
Java Binary Search O(nlogn) seat() O(1) leave() TLE
java-binary-search-onlogn-seat-o1-leave-7a631
Haven\'t seen any other similar approaches using binary search.\nHeres a solution that tries to leverage the binary search approach, although it TLEs\n\nThe ide
yjin02
NORMAL
2020-08-18T01:55:54.537609+00:00
2020-08-19T03:18:33.717978+00:00
719
false
Haven\'t seen any other similar approaches using binary search.\nHeres a solution that tries to leverage the binary search approach, although it TLEs\n\nThe idea here is we know the max distance between student is N - 1, and the min is 0,\nso we use binary search to optimally guess that optimal seat \n\nWe do this by making a guess and then running a O(N) sliding window to check if it\'s valid\n\n\n```\nclass ExamRoom {\n boolean[] seats;\n int seatsTaken = 0;\n public ExamRoom(int N) {\n seats = new boolean[N];\n }\n \n public int seat() {\n if (seatsTaken == 0) {\n seats[0] = true;\n seatsTaken++;\n return 0;\n }\n if (seatsTaken == seats.length) {\n return -1;\n }\n \n int l = 0;\n int r = seats.length - 1;\n \n int maxDistanced = 0;\n while (l <= r) {\n int m = l + (r - l) / 2;\n int seat = validDistance(m);\n if (seat != -1) {\n maxDistanced = Math.max(seat, maxDistanced);\n l = m + 1;\n } else {\n r = m - 1;\n }\n \n }\n seatsTaken++;\n seats[maxDistanced] = true;\n return maxDistanced;\n }\n // O(N) sliding window to determine if guessed spacing is valid\n public int validDistance(int distance) {\n int left = 0;\n int right = 0;\n int index = 0;\n while (seats[index]) {\n index++;\n }\n \n for (int min = Math.max(0, index - distance); min < index; min++) {\n if (seats[min]) {\n left++;\n }\n }\n \n for (int max = Math.min(seats.length - 1, index + distance); max > index; max--) {\n if (seats[max]) {\n right++;\n }\n }\n \n if (left == 0 && right == 0) {\n return index;\n }\n \n \n for (int i = index + 1; i < seats.length; i++) {\n \n if (i - distance - 1 >= 0 && seats[i - distance - 1]) left--;\n if (seats[i - 1]) {\n left++;\n right--;\n }\n if (i + distance <= seats.length - 1 && seats[i + distance]) right++;\n if (left == 0 && right == 0 && !seats[i]) {\n return i;\n }\n }\n \n return -1;\n }\n \n public void leave(int p) {\n seats[p] = false;\n seatsTaken--;\n }\n}\n\n\n```
3
0
['Binary Search', 'Java']
0
exam-room
Changing TreeMap to PriorityQueue reduced runtime by 10ms [ Java]
changing-treemap-to-priorityqueue-reduce-8czf
This is one of the good examples to understand scenarios where queue would perform better vs treeMap.\n- TreeMap always maintains the sort order in insertions a
shradha1994
NORMAL
2020-05-14T05:40:31.238673+00:00
2020-05-14T05:49:04.594652+00:00
431
false
This is one of the good examples to understand scenarios where queue would perform better vs treeMap.\n- TreeMap always maintains the sort order in insertions and deletions. Hence for every insertion and deletion, the time required would be O(logn) \n- Whereas priority queue only maintains heap property (max heap or min heap)\n\nHence in cases when we have lot of insertions and deletions, queue works better than heap.\n```\nclass ExamRoom {\n\n static Queue<Interval> map;\n static int len;\n\n public ExamRoom(int N) {\n map = new PriorityQueue<>(10,new TreeComparator());\n len = N-1;\n }\n \n public int seat() {\n if (map.isEmpty()) {\n map.add(new Interval(0, -1));\n return 0;\n }\n Interval interval = map.poll();\n int index;\n if (interval.start == -1) {\n index = 0;\n map.add(new Interval(0, interval.end));\n } else if (interval.end == -1) {\n index = len;\n map.add(new Interval(interval.start, len));\n } else {\n index = (interval.start + interval.end) / 2;\n map.add(new Interval(index, interval.end));\n map.add(new Interval(interval.start, index));\n }\n return index;\n }\n \n public void leave(int index) {\n Interval startInterval = new Interval();\n Interval endInterval = new Interval();\n\n for ( Interval interval : map) {\n if (interval.start == index) {\n startInterval = interval;\n }\n if (interval.end == index) {\n endInterval = interval;\n }\n }\n if (index == 0) {\n map.remove(startInterval);\n map.add(new Interval(-1,startInterval.end));\n\n } else if (index == len) {\n map.remove(endInterval);\n map.add(new Interval(endInterval.start,-1));\n } else {\n map.remove(startInterval);\n map.remove(endInterval);\n map.add(new Interval(endInterval.start, startInterval.end));\n }\n}\n \n public int getDifference(int start,int end){\n if(start == -1)\n return end;\n else if(end == -1)\n return len - start;\n else\n return (end - start) / 2;\n }\n\n class TreeComparator implements Comparator<Interval> {\n\n @Override\n public int compare(Interval o1, Interval o2) {\n int diffFirst = getDifference(o1.start,o1.end);\n int diffSecond = getDifference(o2.start,o2.end);\n return (diffFirst == diffSecond) ? (o1.start + diffFirst) - (o2.start + diffSecond) : diffSecond - diffFirst;\n\n }\n }\n\n class Interval {\n int start;\n int end;\n\n Interval(int start, int end) {\n this.start = start;\n this.end = end;\n }\n\n public Interval() {\n\n }\n\n @Override\n public String toString() {\n return this.start + " " + this.end;\n }\n }\n \n}\n```\n
3
0
[]
0
exam-room
Java simple O(logN) for both seat() and leave()
java-simple-ologn-for-both-seat-and-leav-zf8s
Extended the idea of zzzliu\'s solution to make it log(n) for both seat() and leave(). The idea is to basically maintain the gaps or intervals in a treeset and
abhilashv
NORMAL
2020-02-12T08:03:40.626197+00:00
2020-02-12T08:03:40.626247+00:00
495
false
Extended the idea of [zzzliu\'s](https://leetcode.com/problems/exam-room/discuss/193295/My-Elegant-Java-Solution-Beats-99.84) solution to make it log(n) for both seat() and leave(). The idea is to basically maintain the gaps or intervals in a treeset and track their boundaries in a hashmap. Code is self-explanatory. \n\n```\nclass ExamRoom {\n\n int n;\n TreeSet<Interval> availableGaps;\n Map<Integer, Interval> boundaries; // track boundaries of intervals\n \n public ExamRoom (int N) {\n this.n = N;\n availableGaps = new TreeSet<>((i, j) -> {\n if (i.length != j.length) return j.length - i.length;\n return i.start - j.start;\n });\n boundaries = new HashMap<>();\n addInterval(0, N-1);\n }\n \n public int seat() {\n Interval top = availableGaps.pollFirst();\n boundaries.remove(top.start);\n boundaries.remove(top.end);\n // Calculate result\n int result = 0;\n if (top.start == 0) {\n result = 0;\n } else if (top.end == n-1) {\n result = n-1;\n } else {\n result = top.start + top.length;\n }\n // Add intervals\n if (result > top.start) {\n addInterval(top.start, result-1);\n }\n if (result < top.end) {\n addInterval(result+1, top.end);\n }\n return result;\n }\n \n public void leave(int p) {\n Interval prev = boundaries.get(p-1);\n Interval next = boundaries.get(p+1);\n if (prev != null) {\n removeInterval(prev);\n }\n if (next != null) {\n removeInterval(next);\n }\n // Add new interval\n addInterval(prev == null ? p : prev.start, next == null ? p : next.end);\n }\n \n private void addInterval (int start, int end) {\n Interval temp = new Interval(start, end);\n availableGaps.add(temp);\n boundaries.put(start, temp);\n boundaries.put(end, temp);\n }\n \n private void removeInterval (Interval temp) {\n availableGaps.remove(temp);\n boundaries.remove(temp.start);\n boundaries.remove(temp.end);\n }\n \n class Interval {\n int start;\n int end;\n int length;\n public Interval(int start, int end) {\n this.start = start;\n this.end = end;\n if (start == 0 || end == n - 1) {\n this.length = end - start;\n } else {\n this.length = (end - start) / 2;\n }\n }\n }\n}\n```
3
0
[]
0
exam-room
c++ set with lambda logN seat logN leave time
c-set-with-lambda-logn-seat-logn-leave-t-wyea
\ntypedef set<pair<int,int>, function<bool(const pair<int, int>&, const pair<int, int>&)>> customSet;\nclass ExamRoom {\nprivate:\n int N;\n customSet pq;
neal_yang
NORMAL
2019-12-31T06:50:44.319801+00:00
2019-12-31T06:51:00.319617+00:00
339
false
```\ntypedef set<pair<int,int>, function<bool(const pair<int, int>&, const pair<int, int>&)>> customSet;\nclass ExamRoom {\nprivate:\n int N;\n customSet pq;\n unordered_map<int, pair<customSet::iterator, customSet::iterator>> indexes;\npublic:\n ExamRoom(int N) {\n this->N = N;\n auto comp = [N] (const pair<int, int>& a, const pair<int, int>& b) {\n int res1 = (a.first == -1) ? a.second : (a.second == N) ? (a.second - a.first - 1) : ((a.second - a.first) / 2);\n int res2 = (b.first == -1) ? b.second : (b.second == N) ? (b.second - b.first - 1) : ((b.second - b.first) / 2);\n if (res1 != res2)\n return res1 > res2;\n return a.first < b.first;\n };\n pq = customSet(comp);\n pq.insert(make_pair(-1, N));\n }\n \n int seat() {\n int ans = -1;\n auto tmp = *pq.begin();\n pq.erase(pq.begin());\n \n if (tmp.first == -1) {\n ans = 0;\n } else if (tmp.second == N) {\n ans = N-1;\n } else {\n ans = (tmp.first + tmp.second) / 2;\n }\n auto it1 = pq.insert(make_pair(tmp.first, ans)).first;\n auto it2 = pq.insert(make_pair(ans, tmp.second)).first;\n \n indexes[ans] = make_pair(it1, it2);\n indexes[tmp.first].second = it1;\n indexes[tmp.second].first = it2;\n \n return ans;\n }\n \n void leave(int p) {\n auto removal = indexes[p];\n indexes.erase(p);\n auto it = pq.insert(make_pair(removal.first->first, removal.second->second)).first;\n indexes[removal.first->first].second = it;\n indexes[removal.second->second].first = it;\n \n pq.erase(removal.first);\n pq.erase(removal.second);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(N);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n```
3
0
[]
2
exam-room
Simple C++ solution using hashmap
simple-c-solution-using-hashmap-by-emine-tviw
\nclass ExamRoom \n{\n public:\n int n;\n map<int,int> total;\n ExamRoom(int N) \n {\n n=N;\n }\n \n int seat() \n {\n
eminem18753
NORMAL
2019-09-26T16:09:11.973709+00:00
2019-09-26T16:09:11.973746+00:00
351
false
```\nclass ExamRoom \n{\n public:\n int n;\n map<int,int> total;\n ExamRoom(int N) \n {\n n=N;\n }\n \n int seat() \n {\n int index=-1;\n if(total.size()==0)\n {\n total[0]=1;\n return 0;\n }\n else\n {\n int last=-1;\n int M=0;\n for(map<int,int>::iterator it=total.begin();it!=total.end();it++)\n {\n if(last==-1)\n {\n M=it->first;\n index=0;\n }\n else\n {\n if((it->first-last)/2>M)\n {\n M=(it->first-last)/2;\n index=(last+it->first)/2;\n }\n }\n last=it->first;\n }\n if(n-1-last>M)\n {\n total[n-1]=1;\n index=n-1;\n }\n else\n {\n total[index]=1;\n }\n return index;\n }\n }\n \n void leave(int p) \n {\n total.erase(p);\n }\n};\n```
3
0
[]
0
exam-room
c++ STL set
c-stl-set-by-anilnagori-t5im
\n\nclass ExamRoom {\npublic:\n ExamRoom(int N) : N(N) {\n \n }\n \n int seat() {\n // Seat at 0 if all empty\n if (seated.empt
anilnagori
NORMAL
2018-10-30T21:33:41.720020+00:00
2018-10-30T21:33:41.720062+00:00
415
false
```\n\nclass ExamRoom {\npublic:\n ExamRoom(int N) : N(N) {\n \n }\n \n int seat() {\n // Seat at 0 if all empty\n if (seated.empty()) {\n seated.insert(0);\n return 0;\n }\n \n // Choices:\n // Seat at 0 if vacant\n // Seat at N - 1 if vacant\n // Seat at middle of max width range\n \n // Intialize max dist position and max distance\n int maxPos = 0;\n int maxDist = 0;\n \n // Seat at 0\n if (!seated.count(0)) {\n maxPos = 0;\n maxDist = *seated.begin();\n } \n \n // Seat in between occupied seats\n auto last = seated.begin();\n \n for (auto it = next(seated.begin()); it != seated.end(); ++it) {\n if (*it == *last + 1) {\n last = it;\n continue;\n }\n \n // New seating position\n int pos = (*it + *last) / 2;\n \n // New distance\n int dist = pos - *last;\n \n // Select this location if bigger dist\n if (dist > maxDist) {\n maxDist = dist;\n maxPos = pos;\n }\n \n last = it;\n }\n \n // Saet at last postion\n if (!seated.count(N - 1)) {\n int dist = N - 1 - *prev(seated.end());\n \n if (dist > maxDist) {\n maxPos = N - 1;\n maxDist = dist;\n } \n }\n \n // Occupy selected postion\n seated.insert(maxPos);\n \n return maxPos;\n }\n \n void leave(int p) {\n seated.erase(p);\n }\n \nprivate:\n int N;\n set<int> seated;\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(N);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n \n ```
3
1
[]
0
exam-room
it's ugly but it's mine - O(log(n))
its-ugly-but-its-mine-ologn-by-marksman-mbu5
I\'m maintaing a set of pair of available seats. We also have a map of int to set>, which stores size to available ranges of that size. \n\nI specially need to
marksman_
NORMAL
2024-11-12T15:48:37.912066+00:00
2024-11-12T15:48:37.912103+00:00
149
false
I\'m maintaing a set of pair<int, int> of available seats. We also have a map of int to set<pair<int, int>>, which stores size to available ranges of that size. \n\nI specially need to handle the code for first and last seat, rest of it is pretty simple. We will either use the first range from largest size, or the first range from second largest size.\n\nTime complexity: O(log(n)) for each call\n# Code\n```cpp []\nstruct RangeSet {\n int n, INF;\n set<pair<int, int>> ranges;\n map<int, set<pair<int, int>>> sizes;\n\n RangeSet(int n) {\n this->n = n;\n INF = 1e9 + 5;\n ranges.insert({-INF, -INF});\n ranges.insert({INF, INF});\n addRange(0, n - 1);\n }\n\n void addRange(int l, int r) {\n int sz = r - l + 1;\n ranges.insert({l, r});\n sizes[sz].insert({l, r});\n }\n\n set<pair<int, int>>::iterator removeRange(set<pair<int, int>>::iterator& it) {\n int l = it->first, r = it->second, sz = r - l + 1;\n sizes[sz].erase({l, r});\n if (sizes[sz].empty()) {\n sizes.erase(sz);\n }\n return ranges.erase(it);\n }\n\n void insert(int x) {\n int L = x, R = x;\n auto it = ranges.lower_bound({L + 1, L + 1});\n it = prev(it);\n\n if (it->first <= L && L <= it->second + 1) {\n L = it->first;\n it = removeRange(it);\n } else {\n it = next(it);\n }\n if (it->first - 1 <= R && R <= it->second) {\n R = it->second;\n removeRange(it);\n }\n addRange(L, R);\n }\n\n void erase(int x) {\n auto it = ranges.lower_bound({x + 1, x + 1});\n it = prev(it);\n if (it->first <= x && x <= it->second) {\n if (it->first < x) {\n addRange(it->first, x - 1);\n }\n if (x < it->second) {\n addRange(x + 1, it->second);\n }\n removeRange(it);\n return;\n }\n }\n\n pair<int, int> findFirstCandidateRange() {\n auto largest = prev(sizes.end());\n return *largest->second.begin();\n }\n\n pair<int, int> findSecondCandidateRange() {\n auto largest = prev(sizes.end());\n int sz = largest->first;\n auto it = sizes.find(sz - 1);\n if (it == sizes.end()) {\n return {INF, INF};\n }\n return *it->second.begin();\n }\n\n int findBestSeat() {\n map<int, int> cand;\n bool isFirstTaken = next(ranges.begin())->first != 0;\n bool isLastTaken = prev(prev(ranges.end()))->second != n - 1;\n\n if (!isFirstTaken) {\n auto [al, ar] = *next(ranges.begin());\n int dist = ((ar + 1 == n) ? INF : ar + 1);\n cand[0] = dist;\n }\n\n if (!isLastTaken) {\n auto [al, ar] = *prev(prev(ranges.end()));\n int d = n - 1 - (al - 1);\n int dist = (d == n ? INF : d);\n cand[n - 1] = dist; \n }\n\n auto findDist = [](int l, int r) {\n return r - l;\n };\n\n auto [l1, r1] = findFirstCandidateRange();\n auto [l2, r2] = findSecondCandidateRange();\n int seat1 = (l1 + r1) / 2, seat2 = (l2 + r2) / 2;\n int dist1 = min(seat1 - l1 + 1, r1 - seat1 + 1);\n int dist2 = seat2 != INF ? min(seat2 - l2 + 1, r2 - seat2 + 1) : -INF;\n\n int bestSeat = -1;\n if (!cand.count(seat1)) {\n cand[seat1] = dist1; \n }\n if (seat2 != INF && !cand.count(seat2)) {\n cand[seat2] = dist2; \n }\n\n int maxDist = INT_MIN;\n for (auto& [seat, dist] : cand) {\n if (dist > maxDist) {\n maxDist = dist;\n bestSeat = seat;\n }\n }\n erase(bestSeat);\n return bestSeat;\n }\n};\n\nclass ExamRoom {\npublic:\n RangeSet rs;\n\n ExamRoom(int n) : rs(n) {}\n\n int seat() {\n return rs.findBestSeat();\n }\n\n void leave(int p) {\n rs.insert(p);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n```
2
0
['C++']
0
exam-room
Java Double TreeSet the Cleanest Both O(logn) Solution
java-double-treeset-the-cleanest-both-ol-04dl
Intuition\n Describe your first thoughts on how to solve this problem. \nCapture all the "gaps" between occupied seat pairs. With each pair of seat ids we can c
traderqiu
NORMAL
2024-02-08T02:39:28.851532+00:00
2024-02-08T02:39:28.851562+00:00
237
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCapture all the "gaps" between occupied seat pairs. With each pair of seat ids we can compute the minimum distance to neighbouring students after seating as well as the new target seat id.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWith ordered set, sort all intervals by minimum distance to others after seating in descending order. Compare interval start seat id for ties on minimum distance. Implementing Comparable interface along with extracting the getSeatId() in Interval class is the key to clean up the seat() and leave() method.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(logn) for both seat() and leave()\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass ExamRoom {\n\n\tTreeSet<Integer> seated;//ordered by id, needed for leave()\n\tTreeSet<Interval> intervals;//ordered by min distance after seating within the interval\n\tint n;\n public ExamRoom(int n) {\n seated = new TreeSet<Integer>();\n seated.add(-1);seated.add(n);\n intervals = new TreeSet<Interval>();\n intervals.add(new Interval(-1, n, n));\n this.n = n;\n }\n\n public int seat() {\n \tInterval inter = intervals.first();\n \tint id = inter.getSeatId();\n \tseated.add(id);\n \tintervals.remove(inter);\n \tintervals.add(new Interval(inter.left, id,n));\n \tintervals.add(new Interval(id, inter.right,n));\n \treturn id; \n }\n\n public void leave(int p) {\n \tint l = seated.lower(p);\n \tint h = seated.higher(p);\n \tseated.remove(p);\n \tintervals.remove(new Interval(l,p,n));\n \tintervals.remove(new Interval(p,h,n));\n \tintervals.add(new Interval(l,h,n));\n }\n}\n\nclass Interval implements Comparable<Interval>\n{\n\tint n;\n\tint left, right;//seat id of left and right end of interval, both should be seated\n\tpublic Interval(int left, int right, int n)\n\t{\n\t\tthis.left = left;\n\t\tthis.right = right;\n\t\tthis.n = n;\n\t}\n\n\t@Override\n\tpublic int compareTo(Interval that) {\n\t\t//if minD equals, we check id\n\t\tint thisD = this.minD(), thatD = that.minD();\n\t\t\n\t\treturn thisD == thatD? this.left - that.left : thatD - thisD;\n\t}\n\t\n\tint minD()\n\t{\n\t\tif(left == -1 || right == n || right - left == 1)\n\t\t\treturn right - left - 2;\n\t\treturn (right - left - 2) / 2;\n\t}\n\t\n\tint getSeatId()\n\t{\n\t\tif(left == -1)\n\t\t\treturn 0;\n\t\tif(right == n)\n\t\t\treturn n - 1;\n\t\treturn (left + right) / 2;\n\t}\n}\n```
2
0
['Ordered Set', 'Java']
0
exam-room
Solution
solution-by-deleted_user-9deu
C++ []\nclass ExamRoom {\npublic:\n\tstruct gap_t {\n\t\tint get_best_seat(int n) const {\n\t\t\tif (start == 0) {\n\t\t\t\treturn 0;\n\t\t\t} if (start + size
deleted_user
NORMAL
2023-05-07T05:06:14.482179+00:00
2023-05-07T06:05:10.035923+00:00
1,994
false
```C++ []\nclass ExamRoom {\npublic:\n\tstruct gap_t {\n\t\tint get_best_seat(int n) const {\n\t\t\tif (start == 0) {\n\t\t\t\treturn 0;\n\t\t\t} if (start + size == n) {\n\t\t\t\treturn n - 1;\n\t\t\t} return start + size / 2 - (size % 2 ^ 1);\n\t\t}\n\t\tint max_seat_dist(int n) const {\n\t\t\tif (start == 0) {\n\t\t\t\treturn size - 1;\n\t\t\t} if (start + size == n) {\n\t\t\t\treturn size - 1;\n\t\t\t} return size / 2 - (size % 2 ^ 1);\n\t\t}\n\t\ttuple<gap_t, gap_t> split(int n) const {\n\t\t\tint seat = get_best_seat(n);\n\t\t\treturn {{start, seat - start}, {seat + 1, start + size - seat - 1}};\n\t\t}\n\t\tbool empty() const {\n\t\t\treturn size <= 0;\n\t\t}\n bool operator == (const gap_t& another) const {\n return start == another.start && size == another.size;\n }\n bool operator != (const gap_t& another) const {\n return !(*this == another);\n }\n\t\tint start{};\n\t\tint size{};\n\t};\n\tstruct gap_order_compare_t {\n\t\tbool operator() (const gap_t& g1, const gap_t& g2) const {\n\t\t\treturn g1.start < g2.start;\n\t\t}\n\t};\n\tstruct gap_size_compare_t {\n\t\tbool operator() (const gap_t& g1, const gap_t& g2) const {\n\t\t\tint d1 = g1.max_seat_dist(n);\n int d2 = g2.max_seat_dist(n);\n if (d1 != d2) {\n return d1 < d2;\n } return g1.start > g2.start;\n\t\t}\n\t\tint n{};\n\t};\n ExamRoom(int _n) : n{_n} {\n\t\tgaps.push_back({0, n});\n\t\tseats.insert(-1);\n\t\tseats.insert(n);\n\t}\n\tgap_t get_gap(int gap) {\n\t\tauto it = seats.lower_bound(gap);\n\t\tint start = *it + 1;\n\t\t--it;\n\t\tint size = *it - start;\n\t\treturn {start, size};\n\t}\n\tvoid pop_gap() {\n\t\tpop_heap(gaps.begin(), gaps.end(), gap_size_compare_t{n});\n\t\tgaps.pop_back();\n }\n\tvoid push_gap(const gap_t& gap) {\n\t\tgaps.push_back(gap);\n\t\tpush_heap(gaps.begin(), gaps.end(), gap_size_compare_t{n});\n\t}\n int seat() {\n\t\twhile (!gaps.empty()) {\n\t\t\tauto gap = gaps.front();\n\t\t\tauto true_gap = get_gap(gap.start);\n\t\t\tpop_gap();\n\t\t\tif (gap != true_gap) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint new_seat = gap.get_best_seat(n);\n\t\t\tseats.insert(new_seat);\n\n\t\t\tauto [g1, g2] = gap.split(n);\n\t\t\tif (!g1.empty()) {\n\t\t\t\tpush_gap(g1);\n\t\t\t} if (!g2.empty()) {\n\t\t\t\tpush_gap(g2);\n\t\t\t}\n\t\t\treturn new_seat;\n\t\t} return -1;\n }\n void leave(int p) {\n\t\tseats.erase(p);\n\t\tpush_gap(get_gap(p));\n }\n int n{};\n\tset<int, greater<int>> seats;\n\tvector<gap_t> gaps;\n};\n```\n\n```Python3 []\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.heap = []\n\n self.heap.append((-self.dist(0, n - 1), 0, n - 1))\n\n def seat(self) -> int:\n res = 0\n\n curr_dist, l, r = heappop(self.heap)\n curr_dist = -curr_dist\n\n if l == 0:\n res = 0\n elif r == self.n - 1:\n res = self.n - 1\n else:\n res = l + curr_dist\n \n if res > l:\n heappush(self.heap, (-self.dist(l, res - 1), l, res - 1))\n \n if res < r:\n heappush(self.heap, (-self.dist(res + 1, r), res + 1, r))\n\n return res\n\n def leave(self, p: int) -> None:\n prev_interval, next_interval = None, None\n\n for item in self.heap:\n if item[1] - 1 == p:\n next_interval = item\n if item[2] + 1 == p:\n prev_interval = item\n \n start = p\n end = p\n if prev_interval:\n start = prev_interval[1]\n self.heap.remove(prev_interval)\n if next_interval:\n end = next_interval[2]\n self.heap.remove(next_interval)\n\n heappush(self.heap, (-self.dist(start, end), start, end))\n \n def dist(self, l, r):\n if l == 0 or r == self.n - 1:\n return r - l\n else:\n return (r - l) // 2\n```\n\n```Java []\nclass ExamRoom {\n\tprivate int n;\n\tprivate Queue<Interval> queue;\n\tpublic ExamRoom(int n) {\n\t\tthis.queue = new PriorityQueue<>((a, b) -> a.length != b.length ? b.length - a.length : a.start - b.start);\n\t\tthis.n = n;\n\t\tthis.queue.offer(new Interval(n, 0, this.n - 1));\n\t}\n\tpublic int seat() {\n\t\tInterval interval = this.queue.poll();\n\t\tint result;\n\t\tif (interval.start == 0) {\n\t\t\tresult = 0;\n\t\t} else if (interval.end == this.n - 1) {\n\t\t\tresult = this.n - 1;\n\t\t} else {\n\t\t\tresult = interval.start + interval.length;\n\t\t}\n\t\tif (result > interval.start) {\n\t\t\tthis.queue.offer(new Interval(n, interval.start, result - 1));\n\t\t}\n\t\tif (result < interval.end) {\n\t\t\tthis.queue.offer(new Interval(n, result + 1, interval.end));\n\t\t}\n\t\treturn result;\n\t}\n\tpublic void leave(int p) {\n\t\tList<Interval> list = new ArrayList<>(this.queue);\n\t\tInterval prev = null;\n\t\tInterval next = null;\n\t\tfor (Interval interval : list) {\n\t\t\tif (interval.end + 1 == p) {\n\t\t\t\tprev = interval;\n\t\t\t}\n\t\t\tif (interval.start - 1 == p) {\n\t\t\t\tnext = interval;\n\t\t\t}\n\t\t}\n\t\tthis.queue.remove(prev);\n\t\tthis.queue.remove(next);\n\t\tthis.queue.offer(new Interval(n, prev == null ? p : prev.start, next == null ? p : next.end));\n\t}\n}\nclass Interval {\n\tint start;\n\tint end;\n\tint length;\n\tpublic Interval(int n, int start, int end) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tif (start == 0 || end == n - 1) {\n\t\t\tthis.length = end - start;\n\t\t} else {\n\t\t\tthis.length = (end - start) / 2;\n\t\t}\n\t}\n}\n```\n
2
0
['C++', 'Java', 'Python3']
0
exam-room
C# Solution || Easy Solution
c-solution-easy-solution-by-mohamedabdel-rl67
Complexity\n- Time complexity:\nRemove => O(1), Seat => O(N)\n- Space complexity:\nO(N)\n# Code\n\npublic class ExamRoom {\n SortedSet<int> reserved;\n in
mohamedAbdelety
NORMAL
2023-03-12T07:36:02.307844+00:00
2023-03-12T07:36:02.307893+00:00
104
false
# Complexity\n- Time complexity:\nRemove => O(1), Seat => O(N)\n- Space complexity:\nO(N)\n# Code\n```\npublic class ExamRoom {\n SortedSet<int> reserved;\n int N;\n public ExamRoom(int n) {\n reserved = new SortedSet<int>();\n N = n - 1;\n } \n public int Seat() { \n int cur = 0, dis = 0;\n var seats = reserved.ToList();\n if(seats.Count > 0) dis = seats[0];\n for(int i = 1; i < seats.Count;i++)\n {\n int diff = seats[i] - seats[i - 1];\n int mid = (diff / 2) + seats[i - 1];\n if(mid - seats[i - 1] > dis){\n cur = mid;\n dis = mid - seats[i - 1];\n }\n }\n if(seats.Count > 0 && N - seats[seats.Count - 1] > dis)\n cur = N;\n reserved.Add(cur);\n return cur;\n }\n \n public void Leave(int p) {\n reserved.Remove(p);\n }\n}\n\n```
2
0
['Ordered Set', 'C#']
0
exam-room
Python Very Easy solution Using Lists
python-very-easy-solution-using-lists-by-0inv
Runtime: 364 ms, faster than 37.72% of Python3 online submissions for Exam Room.\nMemory Usage: 14.2 MB, less than 98.78% of Python3 online submissions for Exam
reaper_27
NORMAL
2022-03-02T11:22:38.928669+00:00
2022-03-02T11:22:38.928704+00:00
1,301
false
**Runtime: 364 ms, faster than 37.72% of Python3 online submissions for Exam Room.\nMemory Usage: 14.2 MB, less than 98.78% of Python3 online submissions for Exam Room.**\n```\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.lst = []\n\n def seat(self) -> int:\n if self.lst == []:\n self.lst.append(0)\n return 0\n else:\n index = 0 \n diff = self.lst[0]\n for i in range(1,len(self.lst)+1):\n if i == len(self.lst):\n tmp = self.n - 1 - self.lst[i-1]\n else:\n tmp = (self.lst[i] - self.lst[i-1])//2\n if tmp > diff:\n diff = tmp\n index = i\n #print(self.lst,diff,index)\n if index ==0: \n self.lst.insert(0,0)\n return 0\n elif index == len(self.lst):\n self.lst.append(self.n-1)\n return self.n-1\n else:\n self.lst.insert(index,self.lst[index-1]+diff)\n return diff+self.lst[index-1]\n def leave(self, p: int) -> None:\n self.lst.remove(p)\n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```\n
2
0
['Python', 'Python3']
1
exam-room
[Java] Only one TreeSet solution | O(N) for seat() & O(logN) for leave()
java-only-one-treeset-solution-on-for-se-ybh9
\nclass ExamRoom {\n \n TreeSet<Integer> set;\n int n;\n\n public ExamRoom(int n) {\n set = new TreeSet<>();\n this.n = n-1;\n }\n
anandkulkarni147
NORMAL
2022-01-31T10:26:49.513071+00:00
2022-02-05T06:03:51.384378+00:00
899
false
```\nclass ExamRoom {\n \n TreeSet<Integer> set;\n int n;\n\n public ExamRoom(int n) {\n set = new TreeSet<>();\n this.n = n-1;\n }\n \n public int seat() {\n //Add first seat if all seats are empty\n if (set.size() == 0) {\n set.add(0);\n return 0;\n }\n \n //Get first seat and compute difference between 0 and first seat\n int left = set.first();\n int diff = left;\n int max = 0;\n \n int mid;\n \n //Traverse set and the capture two intervals in which seats are empty\n //The max distance would be mid of two intervals in which seats are empty\n for (Integer right : set) {\n if (right == left) continue;\n mid = left + (right-left)/2;\n if (diff < Math.min(mid-left, right-mid) && !set.contains(mid)) {\n diff = Math.min(mid-left, right-mid);\n max = mid;\n }\n left = right;\n }\n \n //Get last seat and compute difference between n and last seat\n int last = set.last();\n if (n-last > diff) max = n;\n \n //Add the captured seat to set\n set.add(max);\n return max;\n }\n \n public void leave(int p) {\n set.remove(p);\n }\n}\n```\n\nPlease **comment** and **upvote** if you like the solution
2
0
['Tree', 'Binary Tree', 'Ordered Set', 'Java']
0
exam-room
C# SortedSet solution
c-sortedset-solution-by-newbiecoder1-aegq
\n\n\npublic class ExamRoom {\n\n private SortedSet<int> seats;\n private int N;\n \n public ExamRoom(int n) {\n \n seats = new Sorted
newbiecoder1
NORMAL
2022-01-17T22:43:57.447116+00:00
2022-01-17T23:03:41.451669+00:00
185
false
![image](https://assets.leetcode.com/users/images/b2326164-b073-497b-84e7-db7d0550976d_1642460586.7792268.png)\n\n```\npublic class ExamRoom {\n\n private SortedSet<int> seats;\n private int N;\n \n public ExamRoom(int n) {\n \n seats = new SortedSet<int>();\n N = n;\n }\n \n // O(n + logn)\n public int Seat() {\n \n if(seats.Count == 0)\n {\n seats.Add(0);\n return 0;\n }\n else\n {\n int maxDistance = seats.First();\n int prev = -1, res = 0;\n foreach(var curr in seats)\n {\n\t\t\t // case1 & case 2\n int currDistance = prev == -1? curr : (curr - prev) / 2;\n if(currDistance > maxDistance)\n {\n maxDistance = currDistance;\n res = prev + maxDistance;\n }\n prev = curr;\n }\n \n\t\t\t// case 3\n if(N - 1 - prev > maxDistance)\n res = N - 1;\n \n seats.Add(res);\n return res;\n }\n }\n \n // log(n)\n public void Leave(int p) {\n \n seats.Remove(p);\n }\n}\n```
2
0
[]
0
exam-room
C++ simple solution using vectors
c-simple-solution-using-vectors-by-maitr-ff1i
You want to simulate an exam room where every next student seats furthest from its closest neighbour. So create a vector that will store all the seats filled un
maitreya47
NORMAL
2021-08-21T20:29:25.163910+00:00
2021-08-21T20:29:25.163961+00:00
923
false
You want to simulate an exam room where every next student seats furthest from its closest neighbour. So create a vector that will store all the seats filled until now. Idea is to find the maximum distance available between any two students and seat the current student in the middle of that gap.\nFor example, students seated at-> [0, 2, 5, 9] max distanct available between 5 and 9, so seat the student at 7.\nIn function ExamRoom, just initialise N.\nIn function seat, first see if no student is seated until now, if that\'s the case seat the current student at seat 0. Else go through the vector and check for all the consecutive student, if the maximum distance is available between the current pair. Update d, in every iteration. If the max distance is still between left extreme (0) and the students[0] (can be whatever index->think of case when 0 leaves), then return 0 directly after inserting 0 in students seat vector. Else again go through the students vector and see if that contained the maxium distance, if so, return the smallest seat available (we return value as soon as we get it). If until last we dont find our max distance, return N-1 and push the same in students. Notice that seats at 0 and N-1 positions need to be handled separately as they dont have any other value on extremes to pair with for calculations.\nIn function leave, just search for seat in the students vector and erase that seat.\n```\nclass ExamRoom {\n vector<int> students;\n int N;\npublic:\n ExamRoom(int n) {\n N = n;\n students.clear();\n }\n \n int seat() {\n if(students.empty())\n {\n students.push_back(0);\n return 0;\n }\n int d = max(students[0] - 0, N-1-students[students.size()-1]);\n for(int i=0; i<students.size()-1; i++)\n d = max(d, (students[i+1]- students[i])/2);\n if(students[0]==d)\n {\n students.insert(students.begin(), 0);\n return 0;\n }\n for(int i=0; i<students.size()-1; i++)\n {\n if((students[i+1]-students[i])/2==d)\n {\n students.insert(students.begin()+i+1, (students[i+1]+students[i])/2);\n return students[i+1];\n }\n }\n students.push_back(N-1);\n return N-1;\n }\n \n void leave(int p) {\n for(int i=0; i<students.size(); i++)\n {\n if(students[i]==p)\n students.erase(students.begin()+i);\n }\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n ```\n Time complexity: O(N * M) Where N is maximum number of seat and leave request and M is the maximum size that vector students can expand to.\n Space complexity: O(M)
2
0
['C', 'C++']
0
exam-room
C++ Solution
c-solution-by-oqaistanvir-jjl2
```\nclass ExamRoom {\nprivate:\n setseats;\n int capacity;\npublic:\n ExamRoom(int n) {\n capacity=n;\n }\n \n int seat() {\n i
oqaistanvir
NORMAL
2021-07-15T10:56:29.142744+00:00
2021-07-15T10:56:29.142785+00:00
224
false
```\nclass ExamRoom {\nprivate:\n set<int>seats;\n int capacity;\npublic:\n ExamRoom(int n) {\n capacity=n;\n }\n \n int seat() {\n if(seats.size()==0){\n seats.insert(0);\n return 0;\n }\n int slow=0,fast=0,mid_dist=0,mid;\n bool first=true;\n for(auto i:seats){\n fast=i;\n if(first==true){\n if(fast-slow>mid_dist){\n mid_dist=fast-slow;\n mid=0; \n }\n }\n first=false;\n if((fast-slow)/2>mid_dist){\n mid_dist=(fast-slow)/2;\n mid=slow+mid_dist;\n }\n slow=fast;\n }\n if(capacity-1-fast>mid_dist){\n mid=capacity-1;\n }\n seats.insert(mid);\n return mid;\n }\n \n void leave(int p) {\n seats.erase(p);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */
2
0
[]
0
exam-room
JavaScript Simple O(n) Seat and Leave Solution With Detailed Comments
javascript-simple-on-seat-and-leave-solu-xkk4
\n/**\n * @param {number} n\n */\nvar ExamRoom = function(n) {\n this.n = n\n this.list = []\n};\n\n/**\n * @return {number}\n */\nExamRoom.prototype.seat
crystallili
NORMAL
2021-06-17T07:04:07.177415+00:00
2021-06-17T07:04:42.122457+00:00
501
false
```\n/**\n * @param {number} n\n */\nvar ExamRoom = function(n) {\n this.n = n\n this.list = []\n};\n\n/**\n * @return {number}\n */\nExamRoom.prototype.seat = function() {\n // if nothing in the list, seat the first student at index 0.\n if(this.list.length === 0){\n this.list.push(0)\n return 0\n }\n \n // find the largest distance between left wall and first student, and right wall and last student\n let distance = Math.max(this.list[0], this.n - 1 - this.list[this.list.length-1])\n // update the largest distance by considering the distance between students\n for(let i=0; i<this.list.length-1; i++){\n distance = Math.max(distance, Math.floor((this.list[i+1] - this.list[i]) / 2))\n }\n \n // in case the largest distance is between left wall and first student, we seat next student at the left wall\n if(distance === this.list[0]){\n this.list.unshift(0)\n return 0\n }\n \n // in case the largest distance is between two student, we seat the next student in between these two students\n for(let i=0; i<this.list.length-1; i++){\n if(distance === Math.floor( (this.list[i+1]-this.list[i])/2 )){\n let insertIndex = Math.floor( (this.list[i+1]+this.list[i]) / 2 )\n this.list.splice(i+1,0, insertIndex)\n return insertIndex\n } \n }\n \n // in case the largest distance is between the last student and the right wall, we seat the next student at the right wall\n this.list.push(this.n-1)\n return this.n - 1\n};\n\n/** \n * @param {number} p\n * @return {void}\n */\nExamRoom.prototype.leave = function(p) {\n // We iterate through the list and find the index where the student p sit at, then remove that index.\n for(let i=0; i<this.list.length; i++){\n if(this.list[i] === p) {\n this.list.splice(i, 1)\n break\n }\n }\n};\n\n/** \n * Your ExamRoom object will be instantiated and called as such:\n * var obj = new ExamRoom(n)\n * var param_1 = obj.seat()\n * obj.leave(p)\n */\n```
2
0
['JavaScript']
1
exam-room
Java TreeSet
java-treeset-by-hero18-ni4b
\nclass ExamRoom {\n private int N;\n private TreeSet<Integer> treeSet;\n public ExamRoom(int N) {\n this.N = N;\n this.treeSet = new Tre
hero18
NORMAL
2020-12-26T20:12:48.378088+00:00
2020-12-26T20:12:48.378121+00:00
222
false
```\nclass ExamRoom {\n private int N;\n private TreeSet<Integer> treeSet;\n public ExamRoom(int N) {\n this.N = N;\n this.treeSet = new TreeSet<>();\n }\n \n public int seat() {\n int p = 0;\n if(treeSet.size() > 0) {\n int dist = treeSet.first();\n Integer prev = null; \n for(int s: treeSet){\n if(prev != null){\n int d = (s - prev)/2;\n if(d > dist) {\n dist = d;\n p = prev + d;\n }\n }\n prev = s;\n }\n if(N - 1 - treeSet.last() > dist) {\n p = N - 1;\n } \n }\n treeSet.add(p);\n return p;\n }\n \n public void leave(int p) {\n treeSet.remove(p);\n }\n}\n```
2
0
[]
0
exam-room
Python heapq solution with comments, seat O(logn) leave O(n)
python-heapq-solution-with-comments-seat-rc5b
\nimport heapq\nclass ExamRoom(object):\n\n def dist(self, x, y):\n # This handles the case when there are 0 or 1 students.\n if x == -1 or y =
csd2592
NORMAL
2020-05-20T23:54:40.416768+00:00
2020-05-20T23:54:40.416801+00:00
338
false
```\nimport heapq\nclass ExamRoom(object):\n\n def dist(self, x, y):\n # This handles the case when there are 0 or 1 students.\n if x == -1 or y == self.N:\n return abs(y - 1 - x)\n else:\n # This will be the min diff when we decide to seat at (y + x) / 2.\n return abs(y-x) /2 \n\n def __init__(self, N):\n """\n :type N: int\n """\n self.N = N\n\n # Min heap - (-dist, x, y)\n # If dist is same, ordering will be based on x (which will handle the\n # clause for smallest possible seat).\n self.h = []\n heapq.heappush(self.h, (-self.dist(-1, N), -1, N))\n \n def seat(self):\n """\n :rtype: int\n """\n\n # Pop the max distance segment from the heap.\n d, x, y = heapq.heappop(self.h)\n\n ans = None\n if x == -1:\n # If x == -1, the furthest seat will be at 0 and not at midpoint.\n ans = 0\n elif y == self.N:\n # If x == N , the furthest seat will be at N-1 and not at midpoint.\n ans = self.N - 1\n else:\n # Furthest seath will be (x + y) / 2\n ans = (x + y) / 2\n\n # Push intervals formed after seating back into the heap.\n heapq.heappush(self.h, (-self.dist(x, ans), x, ans))\n heapq.heappush(self.h, (-self.dist(ans, y), ans, y))\n return ans\n\n def leave(self, p):\n """\n :type p: int\n :rtype: None\n """\n\n # Let\'s say we want to remove 4 when the state of the hall is\n # [0, 2, 4, 6, 9]. There will be two items in the heap - [-1, 2, 4] and\n # [-1, 4, 6]. We need to remove both of these and merge them into a\n # single interval [-2, 2, 6]. Here first=[-1, 2, 4], second=[-1, 4, 6]\n # We need to heapify once we remove this and insert the merged interval.\n first, second = None, None\n for interval in self.h:\n if interval[2] == p:\n first = interval\n if interval[1] == p:\n second = interval\n if first and second:\n break\n self.h.remove(first)\n self.h.remove(second)\n heapq.heapify(self.h)\n heapq.heappush(self.h, (-self.dist(first[1], second[2]), first[1], second[2]))\n```
2
0
[]
0
exam-room
Swift Solution beats 100%
swift-solution-beats-100-by-twho-m27d
swift\nclass ExamRoom {\n var capacity = 0\n var seats = [Int]()\n\n init(_ N: Int) {\n capacity = N\n }\n \n func seat() -> Int {\n
twho
NORMAL
2019-06-14T20:28:09.523891+00:00
2019-06-15T18:30:24.428954+00:00
251
false
```swift\nclass ExamRoom {\n var capacity = 0\n var seats = [Int]()\n\n init(_ N: Int) {\n capacity = N\n }\n \n func seat() -> Int {\n if seats.count == 0 {\n seats.append(0)\n return 0\n } else if seats.count == capacity {\n return -1\n } else {\n var idx = 0\n var pos = 0\n var lastGap = seats[0]\n for i in 0..<seats.count-1 {\n let currentGap = (seats[i+1] - seats[i])/2\n if currentGap > lastGap {\n idx = i + 1\n pos = seats[i] + currentGap\n lastGap = currentGap\n }\n }\n\t\t\t\n if capacity - 1 - seats[seats.count-1] > lastGap {\n pos = capacity - 1\n seats.append(pos)\n } else {\n seats.insert(pos, at: idx)\n }\n \n return pos\n }\n }\n \n func leave(_ p: Int) {\n for i in 0..<seats.count {\n if seats[i] == p {\n seats.remove(at: i)\n break\n }\n }\n }\n}\n```\nMore Swift solutions: https://github.com/twho/LeetCode-Swift
2
0
[]
0
exam-room
JavaScript 100% Solution with Comments
javascript-100-solution-with-comments-by-qu63
\n/**\n * @param {number} N\n */\nvar ExamRoom = function(N) {\n this.len=N;//For Length\n this.seats=new Array();//For Storing Used Seats (Sorted)\n};\n\
prajwalroxman
NORMAL
2019-06-13T14:07:24.095926+00:00
2019-06-13T14:07:24.095958+00:00
348
false
```\n/**\n * @param {number} N\n */\nvar ExamRoom = function(N) {\n this.len=N;//For Length\n this.seats=new Array();//For Storing Used Seats (Sorted)\n};\n\n/**\n * @return {number}\n */\nExamRoom.prototype.seat = function() {\n \n /*If all seats empty*/\n if(this.seats.length<=0){\n this.seats.push(0);\n return 0;\n }\n\n let mx=-1;//for max diff\n let res=-1;//for seat-index\n \n /*\n Compare every 2 closest pairs of seats array\n */\n for(let i=0;i<this.seats.length-1;i++){\n let avg=Math.floor((this.seats[i]+this.seats[i+1])/2);\n let diff=avg-this.seats[i];\n if(diff>mx){\n mx=diff;\n res=avg;\n }\n }\n \n /*Left Boundary*/\n if(this.seats[0]>=mx){\n mx=this.seats[0];\n res=0;\n }\n /*Right Boundary*/\n if((this.len-1)-this.seats[this.seats.length-1]>mx){\n mx=(this.len-1)-this.seats[this.seats.length-1];\n res=(this.len-1);\n }\n \n /*Insert at appropriate index to maintain sorted order*/\n let flag=0;\n for(let i=0;i<this.seats.length;i++){\n if(this.seats[i]>res){\n this.seats.splice(i,0,res);\n flag=1;\n break;\n }\n }\n if(!flag)\n this.seats.push(res);\n \n /*Return result*/\n return res;\n};\n\n/** \n * @param {number} p\n * @return {void}\n */\nExamRoom.prototype.leave = function(p) {\n let ind=this.seats.indexOf(p);\n this.seats.splice(ind,1);\n};\n\n/** \n * Your ExamRoom object will be instantiated and called as such:\n * var obj = new ExamRoom(N)\n * var param_1 = obj.seat()\n * obj.leave(p)\n */\n```
2
0
[]
0
exam-room
Python Bisect Insort
python-bisect-insort-by-infinute-sqvk
Use a sorted list self.occupied to keep track of everyone\'s position. Everytime a new person comes in, find the best location between left and right and seat t
infinute
NORMAL
2019-03-14T04:50:01.856896+00:00
2019-03-14T04:50:01.856966+00:00
847
false
Use a sorted list `self.occupied` to keep track of everyone\'s position. Everytime a new person comes in, find the best location between `left` and `right` and seat the person in `(left + right) // 2` using `bisect.insort()`. Don\'t forget the consider the positions before the first person `self.occupied[0]` and after the last person `self.occupied[-1]`.\n```\nclass ExamRoom:\n def __init__(self, N: int):\n self.occupied = []\n self.N = N\n\n def seat(self) -> int:\n if not self.occupied: \n self.occupied.append(0)\n return 0\n left, right = -self.occupied[0], self.occupied[0]\n maximum = (right - left) // 2\n for start, end in zip(self.occupied, self.occupied[1:] + [2 * self.N - 2 - self.occupied[-1]]):\n if (end - start) // 2 > maximum:\n left, right = start, end\n maximum = (right - left) // 2\n bisect.insort(self.occupied, left + maximum)\n return left + maximum\n \n def leave(self, p: int) -> None:\n self.occupied.remove(p)\n```
2
1
['Python']
0
exam-room
Java clean O(log n) seat O(log n) leave
java-clean-olog-n-seat-olog-n-leave-by-d-h5ss
Use a TreeMap to find longest distance between students\nUse a HashMap to find distance to previous/next student\n\nTreeMap lastKey() is O(long n), no need to t
dancingpizza
NORMAL
2019-01-29T08:01:06.213597+00:00
2019-01-29T08:01:06.213666+00:00
442
false
Use a TreeMap to find longest distance between students\nUse a HashMap to find distance to previous/next student\n\nTreeMap lastKey() is O(long n), no need to traverse the whole tree\n```\nclass ExamRoom {\n private int n,sift=1000_000_000;\n private Map<Integer,int[]>m;\n private TreeMap<Long,Integer>map;\n public ExamRoom(int N) {\n m=new HashMap<>();\n map=new TreeMap<>();\n n=N;\n m.put(-1,new int[]{0,n+1});\n m.put(n,new int[]{n+1,0});\n map.put(hs(n+1,n+1),-1);\n }\n private long hs(int l,int p){\n return (long)l/2*sift+p;\n }\n public int seat() {\n if(m.size()==n+2)return -1;\n long val = map.lastKey();\n int next = map.get(val);\n int[]ra=m.get(next),rn=m.get(ra[1]+next);\n int l=ra[1]/2;\n if(next == -1) l=1;\n else if(ra[1]+next==n) l=ra[1]-1;\n int r=ra[1]-l,newSeat=next+l;\n m.put(newSeat,new int[]{l,r});\n map.remove(val);\n if(l>1) map.put(hs(l,n-next),next);\n if(r>1) map.put(hs(r,n-newSeat),newSeat);\n ra[1]=l;\n rn[0]=r;\n return newSeat;\n }\n \n public void leave(int p) {\n int []ra=m.get(p);\n int prev=p-ra[0],next=p+ra[1];\n int[] l = m.get(prev),r=m.get(next);\n l[1]=ra[0]+ra[1];\n r[0]=ra[0]+ra[1];\n if(l[0]==0) map.remove(hs((ra[0]-1)*2,n-prev));\n else if(ra[0]>1) map.remove(hs(ra[0],n-prev));\n if(r[1]==0) map.remove(hs((ra[1]-1)*2,n-p));\n else if(ra[1]>1) map.remove(hs(ra[1],n-p));\n m.remove(p);\n if(r[1]==0 || l[0]==0)map.put(hs((ra[0]+ra[1]-1)*2,n-prev),prev);\n else map.put(hs(ra[0]+ra[1],n-prev),prev);\n }\n}\n```\nIn my local benchmark with 100000 ops, priorityQueue solution gets 11547ms\nThis solution gets 73ms\n\nIt tells the time complexity
2
1
[]
1
exam-room
Java TreeSet Solution
java-treeset-solution-by-adw12382-9fv3
\nclass ExamRoom {\n // TreeSet keeps numbers in ascending order\n private TreeSet<Integer> seats = new TreeSet<>();\n private int length;\n \n p
adw12382
NORMAL
2018-10-19T07:17:42.066082+00:00
2018-10-19T07:19:27.716246+00:00
299
false
```\nclass ExamRoom {\n // TreeSet keeps numbers in ascending order\n private TreeSet<Integer> seats = new TreeSet<>();\n private int length;\n \n public ExamRoom(int N) {\n this.length = N;\n }\n \n public int seat() {\n // First student always sits at seats[0]\n if(seats.size() == 0){\n seats.add(0);\n return 0;\n }\n int left = 0, distance = Integer.MIN_VALUE, res = -1, curDistance;\n // This for-loop supposes seats[0] and seats[length - 1] have already been taken,\n // and looks for the seat which has maximum distance to the closest occupied seats at its left and right\n for(int curIndex : seats){\n curDistance = (curIndex - left) / 2;\n if( curDistance > distance ){\n res = left + curDistance;\n distance = curDistance;\n } \n left = curIndex;\n }\n \n // Since the for-loop always supposes that seats[0] and seats[length - 1] are occupied\n // We need to check if the seats[length - 1] is occupied and see if it is the best option\n if(!seats.contains(length - 1)){\n curDistance = length - left - 1;\n if(curDistance > distance){\n res = left + curDistance;\n distance = curDistance;\n }\n }\n // Same here, we need to check whether seats[0] is occupied and see if it\'s the best option\n if(!seats.contains(0)){\n curDistance = seats.ceiling(0);\n if(curDistance >= distance)\n res = 0;\n }\n seats.add(res);\n return res;\n }\n \n public void leave(int p) {\n seats.remove(p);\n }\n}\n```
2
0
[]
0
exam-room
[Java] Clean code
java-clean-code-by-postyfranky-7frs
Clean Code means clear mind. I love clean code.\n\nclass ExamRoom {\n \n private static class Interval implements Comparable<Interval> {\n private
PostyFranky
NORMAL
2018-10-06T00:29:11.229743+00:00
2018-10-08T16:25:02.900178+00:00
490
false
Clean Code means clear mind. I love clean code.\n```\nclass ExamRoom {\n \n private static class Interval implements Comparable<Interval> {\n private final int start;\n private final int end;\n private final int length;\n private Interval(int start, int end, int length) {\n this.start = start;\n this.end = end;\n this.length = length;\n }\n @Override\n public int compareTo(Interval that) {\n if (this.length == that.length) {\n return this.start - that.start;\n } else {\n return that.length - this.length;\n }\n }\n }\n \n private final PriorityQueue<Interval> intervals;\n private final int slotCount;\n\n public ExamRoom(int N) {\n this.intervals = new PriorityQueue<>();\n this.slotCount = N;\n intervals.offer(new Interval(-1, N, N));\n }\n \n public int seat() {\n if (intervals.isEmpty()) {\n return -1;\n }\n Interval curr = intervals.poll();\n if (curr.start == -1) {\n intervals.offer(new Interval(0, curr.end, curr.length - 1));\n return 0;\n } else if (curr.end == slotCount) {\n intervals.offer(new Interval(curr.start, slotCount - 1, curr.length - 1));\n return slotCount - 1;\n } else {\n int seat = curr.start + (curr.end - curr.start) / 2;\n intervals.offer(new Interval(curr.start, seat, (seat - curr.start) / 2));\n intervals.offer(new Interval(seat, curr.end, (curr.end - seat) / 2));\n return seat;\n }\n }\n \n public void leave(int p) {\n Interval prev = null;\n Interval curr = null;\n for (Interval interval : intervals) {\n if (interval.end == p) {\n prev = interval;\n }\n if (interval.start == p) {\n curr = interval;\n }\n }\n if (prev == null && curr != null) {\n intervals.remove(curr);\n intervals.offer(new Interval(-1, curr.end, curr.end - curr.start));\n } else if (prev != null && curr == null) {\n intervals.remove(prev);\n intervals.offer(new Interval(prev.start, slotCount, prev.end - prev.start));\n } else {\n intervals.remove(curr);\n intervals.remove(prev);\n if (prev.start == -1 || curr.end == slotCount) {\n intervals.offer(new Interval(prev.start, curr.end, curr.end - prev.start));\n } else {\n intervals.offer(new Interval(prev.start, curr.end, (curr.end - prev.start) / 2));\n }\n }\n }\n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(N);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```
2
0
[]
3
exam-room
C++ set solution with detailed comments
c-set-solution-with-detailed-comments-by-p8az
\nclass ExamRoom {\npublic:\n \n set<int> locations;\n int numOfStudents;\n \n ExamRoom(int N):numOfStudents(N){\n }\n \n int seat() {\n
galster
NORMAL
2018-10-05T19:00:38.217583+00:00
2018-10-05T19:00:38.217648+00:00
257
false
```\nclass ExamRoom {\npublic:\n \n set<int> locations;\n int numOfStudents;\n \n ExamRoom(int N):numOfStudents(N){\n }\n \n int seat() {\n int dist = 0;\n int studentToSit = 0;\n \n //no students - just insert 0\n if(!locations.empty()){\n \n //get the location of the first student\n auto beg = locations.begin();\n \n //if this location is not 0\n //first "attempt" to sit the student at 0\n //we will record this for later and use this information when comparing other locations\n if(*beg != 0){\n dist = *beg;\n studentToSit = 0;\n }\n \n //go through all the students starting from the second seated student\n for(auto i = next(beg); i != locations.end(); i = next(i)){\n //get the distance between pair of students\n int currDist = (*i - *beg)/2;\n\n //if the distance is greater than the recorded distance thus far\n //update the recorded distance and attempt to sit the student in the middle\n if(currDist > dist){\n dist = currDist;\n studentToSit = *beg + dist;\n }\n \n beg = i;\n }\n \n \n beg = prev(locations.end());\n \n //we also need to check the distance between the last student and\n //the row size. If that distance is greater than the already recorded distance\n //update the sit to be the last sit in the row\n if(numOfStudents - *beg - 1 > dist){\n studentToSit = numOfStudents - 1;\n }\n }\n \n //insert the new studen\'t sit\n locations.insert(studentToSit);\n return studentToSit;\n }\n \n void leave(int p) {\n locations.erase(p);\n }\n};\n```
2
0
[]
0
exam-room
log(n) for both seat and leave in c++
logn-for-both-seat-and-leave-in-c-by-sil-8hdr
The basic idea is we build a tree set in which distance means that the seat\'s distance to its cloest seat(which already be taken), and pos means the seat\'s po
silvernarcissus
NORMAL
2018-06-17T03:25:37.127247+00:00
2018-06-17T03:25:37.127247+00:00
559
false
The basic idea is we build a tree set<distance, pos> in which distance means that the seat\'s distance to its cloest seat(which already be taken), and pos means the seat\'s position. When we insert a seat what we should do is add 2 new candidate seat in to the tree. When we remove a seat what we should do is remove 2 candidate seat and add 1 candidate seat. Quiet complex? Let me use an example to illustrate:\nif N = 10 and 0, 9 already be taken, the tree should have (4, 4) \nthen we request a seat, we return 4 and the content in the tree should be change to (2, 2), (2, 6)\nthen we leave 4, we should remove (2, 2) and (2, 6) then we put (4, 4) into the tree\nThere are quit a lot conner case so the code is long, be patient please~\n```\nclass compare{\npublic:\n bool operator()(pair<int, int> p1, pair<int, int> p2){\n if(p1.first != p2.first){\n return p1.first > p2.first;\n }\n \n return p1.second < p2.second;\n }\n};\n\nclass ExamRoom {\npublic:\n set<pair<int, int>, compare> s;\n set<int> taken;\n int n;\n \n ExamRoom(int N) {\n pair<int, int> first(N, 0);\n s.insert(first);\n n = N;\n }\n \n int seat() {\n auto it = s.begin();\n int result = it -> second;\n s.erase(it);\n \n auto lower = taken.lower_bound(result);\n auto higher = taken.upper_bound(result);\n if(lower != taken.begin()){\n lower--;\n int left = *lower;\n int cur_pos = (result + left) >> 1;\n if(cur_pos != left){\n int cur_dist = cur_pos - left;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.insert(new_p);\n }\n }\n else{\n if(result != 0){\n int cur_pos = 0;\n int cur_dist = result;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.insert(new_p);\n }\n }\n \n if(higher != taken.end()){\n int right = *higher;\n int cur_pos = (right + result) >> 1;\n if(cur_pos != result){\n int cur_dist = cur_pos - result;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.insert(new_p);\n }\n }\n else{\n if(result != n - 1){\n int cur_pos = n - 1;\n int cur_dist = cur_pos - result;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.insert(new_p);\n }\n }\n \n taken.insert(result);\n \n return result;\n }\n \n void leave(int p) {\n taken.erase(p);\n auto lower = taken.lower_bound(p);\n auto higher = taken.upper_bound(p);\n \n \n if(lower != taken.begin()){\n lower--;\n int left = *lower;\n int cur_pos = (p + left) >> 1;\n if(cur_pos != left){\n int cur_dist = cur_pos - left;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.erase(new_p);\n }\n lower++;\n }\n else{\n if(p != 0){\n int cur_pos = 0;\n int cur_dist = p;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.erase(new_p);\n }\n }\n \n if(higher != taken.end()){\n int right = *higher;\n int cur_pos = (right + p) >> 1;\n if(cur_pos != p){\n int cur_dist = cur_pos - p;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.erase(new_p);\n }\n }\n else{\n if(p != n - 1){\n int cur_pos = n - 1;\n int cur_dist = cur_pos - p;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.erase(new_p);\n }\n }\n \n if(taken.size() == 0){\n pair<int, int> first(n, 0);\n s.insert(first);\n return;\n }\n \n if(lower == taken.begin()){\n int right = *higher;\n int cur_pos = 0;\n int cur_dist = right;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.insert(new_p);\n return;\n }\n \n if(higher == taken.end()){\n int left = *lower;\n int cur_pos = n - 1;\n int cur_dist = cur_pos - left;\n pair<int, int> new_p(cur_dist, cur_pos);\n s.insert(new_p);\n return;\n }\n \n lower--;\n int left = *lower;\n int right = *higher;\n int cur_pos = (left + right) >> 1;\n int cur_dist = cur_pos - left;\n pair<int, int> new_p(cur_dist, cur_pos);\n // cout << taken.size() << endl;\n // cout << left << "," << right;\n s.insert(new_p);\n }\n};\n```\n
2
0
[]
0
exam-room
Simple TreeSet solution with reasoning
simple-treeset-solution-with-reasoning-b-pclr
Intuition\n Describe your first thoughts on how to solve this problem. \nTreeSet can give us lower and higher elements in log n time. We utilise the same data s
b23karali
NORMAL
2024-11-02T08:56:31.324300+00:00
2024-11-02T08:56:31.324321+00:00
86
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTreeSet can give us lower and higher elements in log n time. We utilise the same data structure here.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. If no seats are occupied sit at 0\n2. Else find all compute the mid point between every consecutive occupied seat and check if distance is max or not.\n3. If there is an elemnt already at position 0, the next round of seating should be at position N-1.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nIteration for each position takes : O(m) where m is size of occupied seats\nAnd then we add the element to seats set. 0(log m).\nSo total: O(m+log(m))\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(m) where m is total occupied seats\n\n# Code\n```java []\nclass ExamRoom {\n TreeSet<Integer> seats;\n int n;\n public ExamRoom(int n) {\n this.seats = new TreeSet<>();\n this.n = n;\n }\n \n public int seat() {\n if(seats.size() == 0){\n seats.add(0);\n return 0;\n }\n \n int seatToSit = 0;\n int maxDist = seats.first();\n int prev = Integer.MIN_VALUE;\n for(int curr : seats){\n if(prev != Integer.MIN_VALUE){\n int newElementDist = (curr - prev) / 2;\n if(newElementDist > maxDist){\n maxDist = newElementDist;\n int newSeat = prev + newElementDist;\n seatToSit = newSeat;\n }\n }\n prev = curr;\n }\n if(n-1-seats.last() > maxDist){\n seatToSit = n-1;\n }\n seats.add(seatToSit);\n return seatToSit;\n }\n \n public void leave(int p) {\n seats.remove(p);\n }\n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(n);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```
1
0
['Java']
0
exam-room
log(n)
logn-by-ayush2375-avkf
Intuition\n Describe your first thoughts on how to solve this problem. \n- Maintain occupied pos and interval in the set. \n- Add a very large interval in the s
ayush2375
NORMAL
2024-08-15T13:47:16.149488+00:00
2024-08-15T13:47:16.149518+00:00
36
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Maintain occupied pos and interval in the set. \n- Add a very large interval in the starting to handle edge cases. \n- If an interval lower or higher boundary does not exist, person will be placed on either of the boundary otherwise in the middle of interval. \n- Add this handling in the comparator as well.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: logn\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass ExamRoom {\n TreeSet<int[]> intervals;\n TreeSet<Integer> pos;\n int n;\n public ExamRoom(int n) {\n intervals = new TreeSet<int[]>((a,b)->compare(a,b));\n pos = new TreeSet<>();\n pos.add(Integer.MIN_VALUE);\n pos.add(Integer.MAX_VALUE);\n intervals.add(new int[]{Integer.MIN_VALUE,Integer.MAX_VALUE});\n this.n = n;\n }\n int[] getInterval(int[]a){\n int low = Math.max(a[0],0);\n int high = Math.min(a[1],n-1);\n if(a[0]==Integer.MIN_VALUE || a[1]==Integer.MAX_VALUE){\n return new int[]{(high-low),low};\n }\n return new int[]{(high-low)/2,low};\n }\n int compare(int[]a, int b[]){\n int [] r1 = getInterval(a);\n int [] r2 = getInterval(b);\n if(r1[0]!=r2[0]){\n return r2[0] - r1[0];\n }\n return r1[1] - r2[1];\n }\n \n public int seat() {\n int [] interval = intervals.first();\n int seat = seatPos(interval);\n intervals.remove(interval);\n pos.add(seat);\n intervals.add(new int[]{interval[0],seat});\n intervals.add(new int[]{seat,interval[1]});\n return seat;\n }\n \n public void leave(int p) {\n int lower = pos.lower(p);\n int upper = pos.higher(p);\n pos.remove(p);\n intervals.remove(new int[]{lower,p});\n intervals.remove(new int[]{p,upper});\n intervals.add(new int[]{lower,upper});\n }\n int seatPos(int[]a){\n if(a[0]==Integer.MIN_VALUE){\n return 0;\n }\n if(a[1]==Integer.MAX_VALUE){\n return n-1;\n }\n return (a[0]+a[1])/2;\n }\n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(n);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```\n
1
0
['Java']
0
exam-room
Prettiest solution
prettiest-solution-by-sheshhh-tpws
Intuition\n Describe your first thoughts on how to solve this problem. \nWe use a treeset to maintain the order of gaps created each time when inserting a perso
sheshhh
NORMAL
2024-07-31T13:56:18.800502+00:00
2024-07-31T13:56:18.800523+00:00
38
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe use a treeset to maintain the order of gaps created each time when inserting a person , in form of arrays those gaps will be sorted in decreasing order with left and right index where left index is sorted in inceasing order because when the gap distance is equal we will return the position with the smallest label .\n\nIitially , we add to the treeMap [-1 ,n] and \nif left==-1=> pos=0 \nelse if right=n => pos=n-1\nelse calculate the mid of the top gap in the treeMap\n\nWhen removing a person at position p we need to remove the 2 gaps created when inserting this person : \ntreeMap.remove( [leftp,p] ) && treeMap.remove( [p,rightp] ) those left and right indexes will be retrieved from 2 maps we created earlier each map defines respecively the nearest left neighbour for p and nearest right neighbour for p . now after removing the 2 gaps we add the new gap [leftp,rightp]\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class ExamRoom {\n private TreeSet<int[]> seatSet = new TreeSet<>(\n (a, b) -> {\n int distanceA = calculateDistance(a);\n int distanceB = calculateDistance(b);\n // Compare by distance, then by starting index if distances are equal\n return distanceA == distanceB ? a[0] - b[0] : distanceB - distanceA;\n }\n );\n // Maps to track the nearest occupied seat to the left and right of each seat\n private Map<Integer, Integer> leftNeighbour = new HashMap<>();\n private Map<Integer, Integer> rightNeighbour = new HashMap<>();\n private int seatCount;\n\n public ExamRoom(int n) {\n this.seatCount = n;\n // Initialize with a dummy seat segment representing the whole row\n add(new int[] {-1, seatCount});\n }\n\n public int seat() {\n // Get the seat segment representing the largest distance between seated students\n int[] segment = seatSet.first();\n int seatPosition = (segment[0] + segment[1]) / 2;\n // Handle cases where we need to seat at the start or the end\n if (segment[0] == -1) {\n seatPosition = 0;\n } else if (segment[1] == seatCount) {\n seatPosition = seatCount - 1;\n }\n // Remove the current segment and add new segments reflecting the new student being seated\n remove(segment);\n add(new int[] {segment[0], seatPosition});\n add(new int[] {seatPosition, segment[1]});\n return seatPosition;\n }\n\n public void leave(int p) {\n // Find the immediate neighbours of the leaving student\n int leftIndex = leftNeighbour.get(p);\n int rightIndex = rightNeighbour.get(p);\n // Remove the segments created by the leaving student\n remove(new int[] {leftIndex, p});\n remove(new int[] {p, rightIndex});\n // Create a new segment reflecting the gap left by the student\n add(new int[] {leftIndex, rightIndex});\n }\n\n private int calculateDistance(int[] segment) {\n int l = segment[0], r = segment[1];\n // For seats at the beginning or end, use the whole distance minus one\n if (l == -1 || r == seatCount) {\n return r - l - 1;\n } else {\n // Else, use the half the distance between l and r\n return (r - l) / 2;\n }\n }\n\n private void add(int[] segment) {\n seatSet.add(segment);\n leftNeighbour.put(segment[1], segment[0]);\n rightNeighbour.put(segment[0], segment[1]);\n }\n\n private void remove(int[] segment) {\n seatSet.remove(segment);\n leftNeighbour.remove(segment[1]);\n rightNeighbour.remove(segment[0]);\n }\n}\n```
1
0
['Hash Table', 'Java']
1
exam-room
Using sorted list O(log n) solution
using-sorted-list-olog-n-solution-by-fan-zpll
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTo solve this problem, we need to implement an ExamRoom class that effect
fangdream
NORMAL
2024-05-27T14:34:19.847436+00:00
2024-05-27T14:34:19.847453+00:00
250
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo solve this problem, we need to implement an ExamRoom class that effectively manages seat assignments to maximize the distance between students and properly handles students leaving. Here\'s how we can achieve that:\n\n### Key Insights:\nMaximize Distance: When a student enters, they should sit in the seat that maximizes the distance to the closest person. If multiple seats have the same distance, the seat with the lower index should be chosen.\n\nEfficient Management: We\'ll use a sorted list to keep track of the positions of occupied seats. This will allow us to efficiently find the seat that maximizes the distance to the closest person.\n\nHandling Leaving: When a student leaves, we need to remove their seat from the occupied seats list and maintain the order of the list.\n\nData Structures:\nSorted List: To maintain the positions of occupied seats in order.\nSet: For O(1) time complexity on checking if a seat is occupied.\n\nHere\'s the implementation:\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport bisect\n\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.students = []\n\n def seat(self) -> int:\n if not self.students:\n student = 0\n else:\n max_dist = self.students[0]\n student = 0\n for i in range(1, len(self.students)):\n prev = self.students[i - 1]\n curr = self.students[i]\n dist = (curr - prev) // 2\n if dist > max_dist:\n max_dist = dist\n student = prev + dist\n \n # Check the last position\n if self.n - 1 - self.students[-1] > max_dist:\n student = self.n - 1\n \n bisect.insort(self.students, student)\n return student\n\n def leave(self, p: int) -> None:\n self.students.remove(p)\n \n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```\n\n\nExplanation:\n\nInitialization: In the constructor (__init__), we initialize the n and an empty list students to keep track of occupied seats.\n\nSeating (seat method):\nIf no students are seated, the first student sits at seat 0.\nFor each pair of adjacent occupied seats, calculate the midpoint and update the seat to maximize the distance.\nCheck the last seat separately because it might offer the largest distance.\nInsert the chosen seat into the sorted list using bisect.insort for maintaining the order.\n\nLeaving (leave method):\nSimply remove the seat from the list of occupied seats.\nThis approach ensures efficient seat assignment and removal with a time complexity of \n\uD835\uDC42(log \uD835\uDC5B) for both seating and leaving operations due to the use of the sorted list.
1
1
['Python3']
2
exam-room
✅ C++ | BEATS 98.74% | SET
c-beats-9874-set-by-minhuchiha-g2ic
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
minhuchiha
NORMAL
2023-10-03T23:32:17.342987+00:00
2023-10-03T23:32:50.540171+00:00
205
false
# 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 :)**
1
0
['C++']
0
exam-room
TreeSet Solution Design
treeset-solution-design-by-shree_govind_-rj2n
\n\n# Code\n\nclass ExamRoom {\n\n int capacity;\n TreeSet<Integer> ts;\n\n//TC:-O(1)\n public ExamRoom(int n) {\n this.capacity = n;\n t
Shree_Govind_Jee
NORMAL
2023-09-30T05:58:23.085931+00:00
2023-09-30T05:58:23.085958+00:00
83
false
\n\n# Code\n```\nclass ExamRoom {\n\n int capacity;\n TreeSet<Integer> ts;\n\n//TC:-O(1)\n public ExamRoom(int n) {\n this.capacity = n;\n this.ts = new TreeSet<>();\n }\n \n\n// TC:- O(N)\n public int seat() {\n int count=0;\n if(ts.size() > 0){\n Integer prev = null;\n int dis = ts.first();\n for(Integer i : ts){\n if(prev != null){\n int d = (i-prev)/2;\n if(dis < d){\n dis = d;\n count = prev +dis;\n }\n }\n prev = i;\n }\n\n if(dis < capacity-1-ts.last()) count = capacity-1;\n } \n ts.add(count);\n return count;\n }\n \n\n// TC:- O(1)\n public void leave(int p) {\n ts.remove(p);\n }\n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(n);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```
1
0
['Design', 'Heap (Priority Queue)', 'Ordered Set', 'Java']
1
exam-room
Python3 Solution
python3-solution-by-kkkkshi-htdn
Intuition\nFirst, initialize the heap with two fake seats, -1 and N. If we hit -1, we get the set 0. If we hit N, we get the set N-1. The main function is to us
KKKKSHI
NORMAL
2023-08-06T02:12:12.249140+00:00
2023-08-06T02:12:12.249160+00:00
121
false
# Intuition\nFirst, initialize the heap with two fake seats, -1 and N. If we hit -1, we get the set 0. If we hit N, we get the set N-1. The main function is to use a heap to organize the distance. We pop the minimum distance between two points each time if we need to add a person. We break the length into half and put this two half length into the heap. If we need to leave a person, we combine two lines into one and put them into the heap.\n\n# Code\n```\nclass ExamRoom:\n \n def dist(self, x, y): # length of the interval (x, y)\n if x == -1: # note here we negate the value to make it maxheap\n return -y\n elif y == self.N:\n return -(self.N - 1 - x)\n else:\n return -(abs(x-y)//2) \n \n def __init__(self, N):\n self.N = N\n self.pq = [(self.dist(-1, N), -1, N)] # initialize heap\n \n def seat(self):\n _, x, y = heapq.heappop(self.pq) # current max interval \n if x == -1:\n seat = 0\n elif y == self.N:\n seat = self.N - 1\n else:\n seat = (x+y) // 2\n heapq.heappush(self.pq, (self.dist(x, seat), x, seat)) # push two intervals by breaking at seat\n heapq.heappush(self.pq, (self.dist(seat, y), seat, y))\n return seat\n \n def leave(self, p):\n head = tail = None\n for interval in self.pq: # interval is in the form of (d, x, y)\n if interval[1] == p: \n tail = interval\n if interval[2] == p: \n head = interval\n if head and tail:\n break\n self.pq.remove(head)\n self.pq.remove(tail)\n heapq.heapify(self.pq)\n heapq.heappush(self.pq, (self.dist(head[1], tail[2]), head[1], tail[2]))\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
1
0
['Python3']
0
exam-room
C++ Map Solution | Detailed Explanation
c-map-solution-detailed-explanation-by-y-h4l7
Intuition\n Describe your first thoughts on how to solve this problem. \nAs the questions asks about longest distance betweeen 2 students, we need to store the
YashGadia36
NORMAL
2023-07-27T11:12:41.995688+00:00
2023-07-27T11:12:41.995718+00:00
652
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the questions asks about longest distance betweeen 2 students, we need to store the indexes where the previous students are currently sitting. So, we can think of `map` data structure.\nWe ierate over the map for each call for `seat` and then find the maximum distance we can achieve.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- If `students == 0` -> place the student at position 0.\n- If `students == 1` -> Check if that 1 student is at position `0`, `n - 1` or in between .\n- Else, iterate over the map and find at what index should the student be placed in order to maximize the closest distance.\n\n# Complexity\n- Time complexity: Seat -> `O(n*log(n))` & Leave -> `O(log(n))`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(min(seats, 1e4))`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass ExamRoom {\nprivate:\n map<int, int> mp;\n int n;\n\npublic:\n ExamRoom(int N) {\n n = N;\n }\n \n int seat() {\n // 0 students:\n if(mp.size() == 0) {\n mp[0] = 1;\n return 0;\n }\n\n // 1 student\n if(mp.size() == 1) {\n int pos = mp.begin()->first;\n if(pos == 0 || (pos < (n - pos))) {\n mp[n-1] = 1;\n return (n - 1);\n }\n if((pos == n - 1) || (pos >= (n - pos))) {\n mp[0] = 1;\n return 0;\n }\n }\n\n int left = mp.begin()->first, right = mp.rbegin()->first;\n int maxi = left, ind = 0;\n auto it = mp.begin();\n while(it != mp.end()) {\n // If rightmost student is encountered and he is not at (n - 1) position, then check if placing the student at (n - 1) will maximize the distance or not.\n if(it->first == right) {\n if(it->first != (n - 1) && (n - 1 - it->first) > maxi) {\n ind = n - 1;\n }\n break;\n }\n\n // Check if student can be placed between current and next placed student.\n ++it;\n int nxt = it->first;\n --it;\n if((nxt - it->first) / 2 > maxi) {\n maxi = (nxt - it->first) / 2;\n ind = it->first + (nxt - it->first) / 2;\n }\n ++it;\n }\n mp[ind] = 1;\n return ind;\n }\n \n void leave(int p) {\n mp.erase(p);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n```
1
0
['Ordered Map', 'C++']
1
exam-room
C++ Using Set -- Basic approach (No optimizations)
c-using-set-basic-approach-no-optimizati-q8tw
Intuition\n Describe your first thoughts on how to solve this problem. \nFirst approach one can think of. No algorithms, just implementation using appropriate D
black_mamba666
NORMAL
2023-05-31T07:05:39.224827+00:00
2023-05-31T07:05:39.224875+00:00
518
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst approach one can think of. No algorithms, just implementation using appropriate DS.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCalculating correct postion iteratively using brute force.\n\n<!-- # Complexity -->\n<!-- Let the number of seats occupied curretnly be m. -->\n<!-- - Time complexity: O(m) -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: O(m) -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass ExamRoom {\nprivate:\n set<int> S;\n int n;\npublic:\n ExamRoom(int n) {\n this->n = n;\n }\n \n int seat() {\n int num_el = S.size();\n if(num_el==n) {\n return -1;\n }\n if(num_el==0) {\n S.insert(0);\n return 0;\n }\n if(num_el==1) { // add 0 or n-1 based on element present\n int el = *S.begin();\n if(el-0>n-1-el) {\n S.insert(0);\n return 0;\n } else {\n S.insert(n-1);\n return n-1;\n }\n }\n \n int res = 0;\n int cur_dif = -1;\n for(auto itr=S.begin(); itr!=S.end(); itr++) {\n if(next(itr)==S.end()) {\n break;\n }\n //Calculate all potential positions using consecutive elements in the map\n int mid = (*(next(itr)) + *itr)/2;\n if(cur_dif<mid-(*itr)) {\n cur_dif = mid-(*itr);\n res = mid;\n } \n }\n\n //Calculate ad-hoc if 0 or n-1 is absent in the map\n if(S.find(0)==S.end()) {\n if(*S.begin() >= cur_dif) {\n S.insert(0);\n return 0;\n }\n }\n if(S.find(n-1)==S.end()) {\n auto tmp = prev(S.end());\n if(n-1-(*tmp) > cur_dif) {\n S.insert(n-1);\n return n-1;\n }\n }\n S.insert(res);\n return res;\n }\n \n void leave(int p) {\n S.erase(p);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n```
1
0
['C++']
0
exam-room
Swift linear solution
swift-linear-solution-by-ericdrew08-gg2z
Code\n\n\nclass ExamRoom {\n // seated is an array of seats taken\n // a sorted set may be faster\n var seated: [Int]\n let n: Int\n\n init(_ n:
ericdrew08
NORMAL
2023-03-12T21:39:56.125741+00:00
2023-03-12T21:39:56.125779+00:00
652
false
# Code\n```\n\nclass ExamRoom {\n // seated is an array of seats taken\n // a sorted set may be faster\n var seated: [Int]\n let n: Int\n\n init(_ n: Int) {\n self.n = n\n seated = []\n }\n \n func seat() -> Int {\n if seated.isEmpty {\n seated.append(0)\n return 0\n }\n\n var idx = 0\n var value = 0\n var maxDistance = seated[0] // inital distance is first seat to the beginning\n\n // for each seat that is taken,\n // calculate the distance between seats\n for i in 0..<seated.count - 1 {\n let midDistance = (seated[i + 1] - seated[i]) / 2\n\n if midDistance > maxDistance {\n idx = i + 1\n value = seated[i] + midDistance\n maxDistance = midDistance\n }\n }\n\n if n - 1 - seated.last! > maxDistance {\n // distance from last seat taken to the end\n // is greater than max distance\n seated.append(n - 1)\n return n - 1\n } else {\n // insert at idx so that the seated array remains sorted\n seated.insert(value, at: idx)\n return value\n }\n }\n \n func leave(_ p: Int) {\n // remove seat from array\n seated = seated.filter { $0 != p }\n }\n}\n\n```
1
0
['Swift']
1
exam-room
Fully Explained: Python Fast O(log occupied) seat and leave
fully-explained-python-fast-olog-occupie-yl4e
Background\n Describe your first thoughts on how to solve this problem. \n- This problem is similar to 849. Maximize Distance to Closest Person but with some di
PabloLION
NORMAL
2023-03-02T06:56:35.436457+00:00
2023-04-18T04:49:45.526643+00:00
527
false
# Background\n<!-- Describe your first thoughts on how to solve this problem. -->\n- This problem is similar to [849. Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/description/) but with some differences:\n\n 1. input comes in a stream instead of a single input\n 2. new function `leave`\n\n So I knew that cases of left/right boundary should be should be handled with extra care.\n\n- Name `S` as the number of occupied seats, `S<n`.\n- `Gap`: Call a sequence of vacant seat with two occupied seats a `Gap`, represented by a 3-tuple (AKA, triplet).\n\n# Intuition\n\n1. We can add new gaps on `seat`, but to do this, we need to pop a current longest `Gap` hence it\'s natural to use a priority queue, because it takes only `O(log l)` time to pop or insert. Due to (3.) we also remove any outdated and invalid gaps that are longer than the valid one.\n2. After having the current longest gap, let\'s deduce the new gap(s) and return the new seat index.\n - if the gap touches the left boundary, the new seat index is 0, and there\'s no gap on the left, unless the current longest gap also touches the right boundary; \n - if the gap touches the right boundary, the new seat index is `n-1`, and we cannot add any gap on the left (we can move "unless" here).\n - otherwise it\'s in the middle, we split the old longest gap into two new gaps.\n3. On `leave` we add a merged big gap, but not removing the old ones: finding it requires going through the entire queue, which takes much longer than doing it in `seat` \n\n\n# Approach\n- We define gap_length as the absolute difference between the indices of two adjacent seats, i.e., `gap_length := abs(seat_1_index - seat_2_index)`. You can subtract or add 1 based if you prefer, as the order doesn\'t change. I used this because mathematically distance == 0 `<=>` seat_1 == seat_2.\n- About `distance`: the `gap_length//2` is a must since we want the "closest person" and since the seats in the classroom are discrete. Also we need `gap_length-1` in the on-boundary cases because we used index `-1` and `n` as sentinel seats.\n- In `Gap`, use `-distance` (negative) to sort the priority queue in descending order. The index of left seat goes the second in `Gap` tuples, to easily achieve "If there are multiple such seats, they sit in the seat with the lowest number"\n- Used a dictionary instead of `SortedList` to store the previous and next seats. It\'s faster tho takes roughly 3x more memory (asymptotically on large room size `n`).\n- Priority queue with `heapq`\n\n# Complexity\n- Time complexity: O(log S) on each `seat` / `leave`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n\n- Possible improvement: don\'t add gap with length 0. This happens only when `new_seat==l==r-1`. I didn\'t add the `if l==r-1: return` to `__push_gap()`, but those 0-length gap will never be removed from the queue and would possibly use up all memory on large scale of problem!\n\n# Code\n```\n# Similar to [849] Maximize Distance to Closest Person\n# We need a data structure to store the vacancy intervals that can be\n# queried by left, right and ordered by a custom length (when at boundary)\n# With priority queue, we can get the interval with the longest length in\n# O(log n) time but remove is O(n) time.\n# With BBST, we can get the interval with the longest length in\n# O(log n) time and remove is O(log n) time. So I didn\'t finish the pq version.\n# For a flatten BBST, although two lists can be used to store the left ends and\n# right ends, but it\'s longer than just using a occupancy list.\n\n\nfrom heapq import heappop, heappush\n\nGap = tuple[int, int, int] # -length, left seat index, right seat index\n\n\nclass ExamRoom:\n def __init__(self, n: int):\n self.n = n\n self.ss = { # seats, to find and edit prev and next seats\n -1: [None, n],\n n: [-1, None],\n } # sorted list is 3x smaller, but O(log n) slower\n self.pq: list[Gap] = [(-(n - (-1)), -1, n)]\n\n def __is_outdated_gap(self, gap: Gap):\n # we only remove invalid gaps on the fly. otherwise it\'s slower.\n nn = [None, None]\n return (\n # left seat\'s right neighbor is not right seat\n self.ss.get(gap[1], nn)[1] != gap[2]\n # or right seat\'s left neighbor is not left seat\n or gap[1] != self.ss.get(gap[2], nn)[0]\n )\n\n def __rm_outdated_gaps(self):\n # remove outdated gaps\n while self.pq and self.__is_outdated_gap(self.pq[0]):\n heappop(self.pq)\n\n def __push_gap(self, l: int, r: int) -> None:\n dist = r - l\n dist = dist - 1 if (l == -1 or r == self.n) else dist // 2\n heappush(self.pq, (-dist, l, r))\n\n def seat(self) -> int:\n self.__rm_outdated_gaps() # remove outdated gaps\n _, l, r = heappop(self.pq) # best valid gap. also sorted by `l` on tie\n alb, arb = l == -1, r == self.n # at left boundary, at right boundary\n ns = 0 if alb else r - 1 if arb else (l + r) // 2 # new seat\n\n if not alb: # push a new left gap if not at left boundary\n self.__push_gap(l, ns)\n if not arb or alb: # push a right gap if not at right boundary or alb\n self.__push_gap(ns, r)\n\n # curate the seats info\n self.ss[l][1], self.ss[r][0] = ns, ns\n self.ss[ns] = [l, r]\n\n return ns\n\n def leave(self, p: int) -> None:\n ss, (prv, nxt) = self.ss, self.ss[p]\n\n self.__push_gap(prv, nxt) # push merged adjacent gap. keep the old ones\n\n # curate the seats info\n ss[prv][1], ss[nxt][0] = nxt, prv\n ss.pop(p)\n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
1
0
['Python3']
0
exam-room
c++ | easy | faster and easy
c-easy-faster-and-easy-by-venomhighs7-qr5s
\n\n# Code\n\nstruct IntV\n{\n static int N;\n int l, r;\n IntV(int l, int r) : l(l), r(r) {}\n int getD() const\n {\n if(l == 0) return r
venomhighs7
NORMAL
2022-10-30T04:40:39.449350+00:00
2022-10-30T04:40:39.449388+00:00
634
false
\n\n# Code\n```\nstruct IntV\n{\n static int N;\n int l, r;\n IntV(int l, int r) : l(l), r(r) {}\n int getD() const\n {\n if(l == 0) return r;\n if(r == N - 1) return N - 1 - l;\n if(r < l) return -1;\n else return (r - l) / 2;\n }\n int getP() const\n {\n if(l == 0) return 0;\n if(r == N - 1) return N - 1;\n else return l + (r - l) / 2;\n }\n bool operator < (const IntV& a) const\n {\n int d1 = getD(), d2 = a.getD();\n if(d1 != d2) return d1 > d2;\n return l < a.l;\n }\n};\n\nint IntV :: N = 0;\n\nclass ExamRoom {\npublic:\n set<IntV> tab;\n map<int, int> l2r, r2l;\n \n ExamRoom(int N)\n {\n IntV :: N = N;\n tab.clear(); l2r.clear(); r2l.clear();\n tab.insert(IntV(0, N - 1));\n l2r[0] = N - 1;\n r2l[N - 1] = 0;\n }\n \n int seat()\n {\n IntV cur = *(tab.begin());\n tab.erase(tab.begin());\n \n int pos = cur.getP();\n tab.insert(IntV(cur.l, pos - 1));\n tab.insert(IntV(pos + 1, cur.r));\n l2r[cur.l] = pos - 1; r2l[pos - 1] = cur.l;\n l2r[pos + 1] = cur.r; r2l[cur.r] = pos + 1;\n return pos;\n }\n \n void leave(int p)\n {\n int l = r2l[p - 1], r = l2r[p + 1];\n tab.erase(IntV(l, p - 1));\n tab.erase(IntV(p + 1, r));\n tab.insert(IntV(l, r));\n l2r[l] = r; r2l[r] = l;\n r2l.erase(p - 1); l2r.erase(p + 1);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n```
1
1
['C++']
1
exam-room
C++✅ || Easy || Solution
c-easy-solution-by-prinzeop-e9hr
\nclass ExamRoom {\nprivate:\n\tvector<int> v;\n\tint sz;\npublic:\n\tExamRoom(int n) {\n\t\tsz = n;\n\t}\n\n\tint seat() {\n\t\tif (v.size() == 0) {\n\t\t\tv.p
casperZz
NORMAL
2022-08-16T12:14:25.284112+00:00
2022-08-16T12:14:25.284158+00:00
224
false
```\nclass ExamRoom {\nprivate:\n\tvector<int> v;\n\tint sz;\npublic:\n\tExamRoom(int n) {\n\t\tsz = n;\n\t}\n\n\tint seat() {\n\t\tif (v.size() == 0) {\n\t\t\tv.push_back(0);\n\t\t\treturn 0;\n\t\t}\n\t\tint maxi = max(v[0], sz - 1 - v.back());\n\t\tfor (int i = 0; i < v.size() - 1; ++i) maxi = max(maxi, (v[i + 1] - v[i]) >> 1);\n\n\t\tif (v[0] == maxi) {\n\t\t\tv.insert(v.begin(), 0);\n\t\t\treturn 0;\n\t\t}\n\n\t\tfor (int i = 0; i < v.size() - 1; ++i) {\n\t\t\tif (((v[i + 1] - v[i]) >> 1) == maxi) {\n\t\t\t\tv.insert(v.begin() + i + 1, (v[i + 1] + v[i]) >> 1);\n\t\t\t\treturn v[i + 1];\n\t\t\t}\n\t\t}\n\t\tv.push_back(sz - 1);\n\t\treturn sz - 1;\n\t}\n\n\tvoid leave(int p) {\n\t\tfor (int i = 0; i < v.size(); ++i) if (v[i] == p) v.erase(v.begin() + i);\n\t}\n};\n```
1
1
['C']
0
exam-room
My solution using Heap and TreeMap
my-solution-using-heap-and-treemap-by-ja-oe31
Used concept (-1, N) and different distance measuring from below link.\nhttps://leetcode.com/problems/exam-room/discuss/404676/Java-Two-TreeSets-Solution.-Both-
jaehoonlee88
NORMAL
2022-08-14T02:08:12.888686+00:00
2022-08-14T02:09:13.277544+00:00
374
false
Used concept (-1, N) and different distance measuring from below link.\nhttps://leetcode.com/problems/exam-room/discuss/404676/Java-Two-TreeSets-Solution.-Both-Seat-and-Leave-O(log-n)-Time-Complexity\n\n\n```\n// 0 to x1\n// xn to xn+1\n// xn to last\n\nclass ExamRoom {\n\n int N;\n class Interval {\n int x, y, dis;\n String id; // for O(1) lookup\n\n public Interval(int x, int y) {\n this.x = x;\n this.y = y;\n if (x == -1) {\n this.dis = y;\n } else if (y == N) {\n this.dis = N - 1 - x;\n } else {\n this.dis = Math.abs(x - y) / 2; // works for both odd and even distance. The dis is to the closest person, no matter on the left or right.\n }\n this.id = x + "_" + y;\n }\n\n // this is for TreeSet remove (Object o) method.\n public boolean equals(Interval i) {\n return this.id.equals(i.id);\n }\n \n public String toString() {\n return x + "_" + y + "_" + dis; \n }\n }\n \n TreeMap<Integer, Interval> takenSeats;\n PriorityQueue<Interval> maxHeap;\n \n public ExamRoom(int N) {\n takenSeats = new TreeMap<>();\n maxHeap = new PriorityQueue<>((a, b) -> { \n if(a.dis == b.dis) return a.x - b.x;\n \n return b.dis - a.dis;\n });\n this.N = N;\n \n Interval initial = new Interval(-1, N);\n maxHeap.offer(new Interval(-1, N));\n takenSeats.put(-1, initial);\n }\n \n public int seat() {\n int pos = 0;\n Interval cand = maxHeap.poll(); \n takenSeats.remove(cand.x);\n \n if (cand.x == -1) { // we keep -1\n pos = 0;\n } else if(cand.y == N) {\n pos = N-1;\n } else {\n pos = (cand.y + cand.x) / 2;\n }\n \n Interval oldInterval = new Interval(cand.x, pos);\n Interval newInterval = new Interval(pos, cand.y);\n \n maxHeap.offer(oldInterval);\n maxHeap.offer(newInterval);\n takenSeats.put(cand.x, oldInterval);\n takenSeats.put(pos, newInterval);\n \n return pos; \n }\n \n public void leave(int p) {\n int startIndex = takenSeats.lowerKey(p);\n mergeInterval(takenSeats.get(startIndex), takenSeats.get(p), maxHeap);\n }\n \n private void mergeInterval(Interval i1, Interval i2, PriorityQueue<Interval> maxHeap) {\n maxHeap.remove(i1);\n maxHeap.remove(i2);\n \n takenSeats.remove(i1.x);\n takenSeats.remove(i2.x);\n \n Interval newInterval = new Interval(i1.x, i2.y);\n maxHeap.add(newInterval);\n takenSeats.put(newInterval.x, newInterval);\n }\n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(n);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```
1
0
[]
1
exam-room
[Python] O(logn) both seat and leave. Easier to understand
python-ologn-both-seat-and-leave-easier-uibvw
The intuition is that, \n when to seat, use a heap to figure out the seat with max distance to neighbor.\n when to leave, use a seat to neighbor dict to get lef
subtlecold
NORMAL
2022-08-12T07:06:26.132998+00:00
2022-08-12T07:14:25.756265+00:00
330
false
The intuition is that, \n* when to seat, use a heap to figure out the seat with max distance to neighbor.\n* when to leave, use a seat to neighbor dict to get left and right neighbors, then update both neighbors pointing to each other, then remove this student from dict.\n\nOf course, we also need to update neighbors when a new student get seated. And we lazy delete the entry in the heap if the entry cannot be validated against the neighbor dict.\n\n```python\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.h = [(self.dist(-1, n), -1, n)]\n self.nei = {}\n \n def dist(self, l, r) -> int:\n if l == -1:\n return -r\n elif r == self.n:\n return -(self.n-1-l)\n else:\n return - ((r-l) // 2)\n\n def seat(self) -> int:\n n, h, nei = self.n, self.h, self.nei\n while h:\n _, left, right = heapq.heappop(h)\n if (left != -1 and (left not in nei or nei[left][1] != right))\\\n or (right != n and (right not in nei or nei[right][0] != left)):\n continue\n if left == -1:\n nei[0] = [-1, right]\n if right < n:\n nei[right][0] = 0\n heapq.heappush(h, (self.dist(0, right), 0, right))\n return 0\n elif right == n:\n nei[n-1] = [left, n]\n nei[left][1] = n-1\n heapq.heappush(h, (self.dist(left, n-1), left, n-1))\n return n-1\n else:\n pos = (left+right) // 2\n nei[left][1] = pos\n nei[right][0] = pos\n nei[pos] = [left, right]\n heapq.heappush(h, (self.dist(left, pos), left, pos))\n heapq.heappush(h, (self.dist(pos, right), pos, right))\n return pos\n\n def leave(self, p: int) -> None:\n n, h, nei = self.n, self.h, self.nei\n left, right = nei[p]\n if left > -1:\n nei[left][1] = right\n if right < n:\n nei[right][0] = left\n heapq.heappush(h, (self.dist(left, right), left, right))\n del nei[p]\n\n```
1
0
[]
1
exam-room
C# | Quick learner | Two practices
c-quick-learner-two-practices-by-jianmin-xfwu
July 21, 2022\n\nProblem statement:\nThere is an exam room with n seats in a single row labeled from 0 to n - 1.\n\nWhen a student enters the room, they must si
jianminchen
NORMAL
2022-07-21T21:26:20.680756+00:00
2022-08-04T23:11:15.824080+00:00
111
false
July 21, 2022\n\nProblem statement:\nThere is an exam room with n seats in a single row labeled from 0 to n - 1.\n\nWhen a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0.\n\nDesign a class that simulates the mentioned exam room.\n\nImplement the ExamRoom class:\n\n**ExamRoom(int n)** Initializes the object of the exam room with the number of the seats n.\n**int seat()** Returns the label of the seat at which the next student will set.\n**void leave(int p)** Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p.\n\n**Solution 1**: \nUse a C# SortedSet<int> to record the index of seats where people sit.\n\nseat():\n1. Go over each seat and compare to previous seated position, calculate the middle seat; keep the one if the range is maximum distance.\n3. return index\n \n```\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace _855_exam_room\n{\n class ExamRoom\n {\n static void Main(string[] args)\n {\n /*\n Input\n ["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"]\n [[10], [], [], [], [], [4], []]\n Output\n [null, 0, 9, 4, 2, null, 5]\n */\n var examRoom = new ExamRoom(10);\n var value = examRoom.Seat(); // check return == 0\n value = examRoom.Seat(); // value == 9\n value = examRoom.Seat(); // value = 4, 4 and 5 have closest distance 4, but 4 < 5\n value = examRoom.Seat(); // value = 2 \n examRoom.Leave(4);\n value = examRoom.Seat();\n }\n\n // study code\n // https://leetcode.com/problems/exam-room/discuss/1698231/C-SortedSet-solution\n private SortedSet<int> seats;\n private int N;\n\n public ExamRoom(int n)\n {\n seats = new SortedSet<int>();\n N = n;\n }\n\n // O(n + logn)\n public int Seat()\n {\n if (seats.Count == 0)\n {\n seats.Add(0);\n return 0;\n }\n else\n {\n // Seat as far as possible, lowest number as possible, empty then choose 0\n int maxDistance = seats.First();\n int prev = -1;\n\n var seatNumber = 0;\n\n // sorted seat number - check each range \n // calculate middle seat \n // keep the one if it is maximum distance range\n foreach (var curr in seats)\n {\n // case1 & case 2\n int currDistance = prev == -1 ? curr : (curr - prev) / 2;\n\n // only keep largest one - \n if (currDistance > maxDistance)\n {\n maxDistance = currDistance;\n seatNumber = prev + maxDistance; // prev + maxDistance - lowest as possible!\n }\n\n prev = curr;\n }\n\n // case 3\n if (N - 1 - prev > maxDistance)\n {\n seatNumber = N - 1;\n }\n\n seats.Add(seatNumber);\n return seatNumber;\n }\n }\n\n // log(n)\n public void Leave(int p)\n {\n seats.Remove(p);\n }\n }\n}\n```\n**Solution 2 | Failed one test case**\nJuly 19, 2020\n\nIt is so challenge for me to figure out where the bug is. I have to run visual studio debugger with the failed test case and then figure out. \n\n\n95 / 128 test cases passed.\nStatus: Wrong Answer\nSubmitted: 2 years ago\n\nInput:\n["ExamRoom","seat","seat","seat","leave","leave","seat","seat","seat","seat","seat","seat","seat","seat","seat","leave","leave","seat","seat","leave","seat","leave",\n"seat","leave","seat","leave","seat","leave","leave","seat","seat","leave","leave","seat","seat","leave"]\n[[10],[],[],[],[0],[4],[],[],[],[],[],[],[],[],[],[0],[4],[],[],[7],[],[3],[],[3],[],[9],[],[0],[8],[],[],[0],[8],[],[],[2]]\nOutput:\n[null,0,9,4,null,null,0,4,2,6,1,3,5,7,8,null,null,4,9,null,7,null,3,null,3,null,9,null,null,8,9,null,null,8,9,null]\nExpected: \n[null,0,9,4,null,null,0,4,2,6,1,3,5,7,8,null,null,0,4,null,7,null,3,null,3,null,9,null,null,0,8,null,null,0,8,null]\n\nI will document what I should learn from the failed test case. \n\n```\npublic class ExamRoom {\n private SortedSet<int> taken; \n private int total;\n public ExamRoom(int N) {\n if(N <= 0)\n return; \n \n total = N;\n taken = new SortedSet<int>(); \n }\n \n public int Seat() {\n var maximum = 0;\n \n var previous = -1; \n \n if(taken.Count == 0)\n {\n taken.Add(0); \n return 0; \n } \n \n var list = taken.ToList(); \n var max = 0; \n var number = 0; \n var range = 0; \n for(int i = 0; i < list.Count; i++)\n { \n range = i ==0? list[i] : (list[i] - list[i-1]);\n if(range > max + 1)\n {\n max = range; \n number = i==0? 0 : (list[i] + list[i-1])/2; \n }\n }\n \n var lastRange = total - list[list.Count - 1];\n if(lastRange > max)\n {\n max = lastRange;\n number = total - 1; \n }\n \n taken.Add(number);\n return number; \n }\n \n public void Leave(int p) {\n if(p < 0 || p > total - 1)\n return; \n \n taken.Remove(p); \n }\n}\n```
1
0
[]
0
exam-room
Java || Detail explanation of the solution || Better variable names || TC & SC explained
java-detail-explanation-of-the-solution-eihrj
// TC : Adding/Removing from TreeSet takes O(logN) times\n// SC : O(N)\n\nclass ExamRoom {\n\n TreeSet<Integer> seatTakenAtI; // TreeSet because of lower() a
ICodeToSurvive
NORMAL
2022-07-14T02:24:07.499702+00:00
2022-07-14T02:24:07.499742+00:00
280
false
// TC : Adding/Removing from TreeSet takes O(logN) times\n// SC : O(N)\n```\nclass ExamRoom {\n\n TreeSet<Integer> seatTakenAtI; // TreeSet because of lower() and higher() methods\n TreeSet<Intervals> nextIntervalToFill; // Priority Queue could also be used here with custom Comparator (removing any obj other than min/max takes O(N) times in PQ)\n int max;\n \n public ExamRoom(int n) {\n seatTakenAtI = new TreeSet<>();\n nextIntervalToFill = new TreeSet<>((a,b) -> b.intervalSize != a.intervalSize ? b.intervalSize - a.intervalSize : a.leftOfInterval - b.leftOfInterval); // look at the rules (2 & 3) explained before seat() method below\n max = n;\n \n // We need a default interval (the whole space) to make students sit\n nextIntervalToFill.add(new Intervals(-1, max, n));\n }\n \n // There are following rules to make student sit at particular place:\n // 1. If no one is there, then sit at 0\n // 2. Maximize the distance between 2 students, so fill LARGER interval first\n // 3. If the Intervals (to be filled next) have same size, then make student sit at lower seat number, basically the interval at left side of scale\n public int seat() {\n int pos = 0; // default\n \n Intervals interval = nextIntervalToFill.pollFirst(); // always poll the interval on top (it is on the top because of the rules defined above)\n \n // create the new interval(s) depending on the position\n if(interval.leftOfInterval == -1) { // if there is no student in the class\n pos = 0;\n nextIntervalToFill.add(new Intervals(pos, interval.rightOfInterval, max)); // add the remaining interval to the SET\n } else if(interval.rightOfInterval == max) { // when there is only 1 student (on seat 0)\n pos = max - 1;\n nextIntervalToFill.add(new Intervals(interval.leftOfInterval, pos, max));\n } else {\n pos = interval.leftOfInterval + (interval.rightOfInterval - interval.leftOfInterval)/2; // mid seat of the top interval in the SET (to maximize the dist)\n // since the new student will be added to this seat which is at MID of previous interval, it will create 2 new intervals and we need to add them in our SET\n nextIntervalToFill.add(new Intervals(interval.leftOfInterval, pos, max));\n nextIntervalToFill.add(new Intervals(pos, interval.rightOfInterval, max));\n }\n \n // always fill the seat at \'pos\'\n seatTakenAtI.add(pos);\n return pos;\n }\n \n // when a student is removed from a \'pos\', 2 things happen\n // 1. the 2 intervals to the left and right of this \'pos\' does not remain valid (since the divding factor \'pos\' is no more there)\n // 2. a new interval (composed of the above 2 intervals at left and right of \'pos\') is formed\n // So remove the 2 intervals from the SET and add the newer one\n public void leave(int p) {\n int startIdxOfLeftInterval = seatTakenAtI.lower(p) == null ? -1 : seatTakenAtI.lower(p); // the \'p\' could be 0 otherwise lower(p) returns GREATEST ele in SET which is STRICTLY less than \'p\'\n int endIdxOfRightInterval = seatTakenAtI.higher(p) == null ? max : seatTakenAtI.higher(p); // the \'p\' could be N otherise higher(p) returns LEAST ele in SET which is STRICTLT greater than \'p\'\n \n // create the 2 intervals at left and right of \'p\' and remove them\n Intervals leftInterval = new Intervals(startIdxOfLeftInterval, p, max);\n Intervals rightInterval = new Intervals(p , endIdxOfRightInterval, max);\n nextIntervalToFill.remove(leftInterval);\n nextIntervalToFill.remove(rightInterval);\n \n // create new interval and add it to SET\n Intervals newInterval = new Intervals(startIdxOfLeftInterval, endIdxOfRightInterval, max);\n nextIntervalToFill.add(newInterval);\n \n // dont forget to remove the student from \'p\'\n seatTakenAtI.remove(p);\n }\n}\n\n// Basic class to mark interval\'s size, left idx and right idx\nclass Intervals {\n int leftOfInterval;\n int rightOfInterval;\n int intervalSize;\n \n public Intervals(int x, int y, int n) {\n this.leftOfInterval = x;\n this.rightOfInterval = y;\n \n if(x == -1) {\n this.intervalSize = y;\n } else if(y == n) {\n this.intervalSize = n - 1 - x;\n } else {\n this.intervalSize = Math.abs(x - y)/2; // /2 to handle middle point issue (in case the left and right interval differ by just 1 and if putting the cstudent even in higher sized interval is same as in lower side interval, so we should prefer lower side); use the example to layout the numbers and you will see the reason\n }\n }\n}\n```
1
0
[]
0
exam-room
Most Complex Question Till Now (soln)
most-complex-question-till-now-soln-by-t-4f2z
If u can understand this solution easily then u should stop dude...XD :)\n`\nclass ExamRoom {\npublic:\n set<int> s;\n\n int n;\n ExamRoom(int N) {\n
tanuj_1099
NORMAL
2022-06-19T17:47:35.585129+00:00
2022-06-19T17:47:35.585175+00:00
378
false
If u can understand this solution easily then u should stop dude...XD :)\n```\nclass ExamRoom {\npublic:\n set<int> s;\n\n int n;\n ExamRoom(int N) {\n n=N;\n \n }\n \n int seat() {\n if(s.empty())\n {\n s.insert(0);\n return 0;\n }\n int x=-1;\n int prev=-1;\n int maxdis=INT_MIN;\n if(*(s.begin())>0)\n {\n x=0;\n maxdis=*(s.begin())-1;\n }\n for(auto it: s)\n {\n //cout<<it<<endl;\n if((it-prev-1)>0)\n {\n if(((it-prev-1)%2==0 && ((it-prev-1)/2-1)>maxdis) || ((it-prev-1)%2!=0 && ((it-prev-1)/2)>maxdis))\n {\n \n \n if((it-prev-1)%2==0)\n {\n maxdis=(it-prev-1)/2 -1;\n x=prev+(it-prev-1)/2;\n }\n else\n {\n maxdis=(it-prev-1)/2;\n x=prev+maxdis+1; \n }\n // cout<<maxdis<<" "<<prev<<endl;\n }\n }\n prev=it;\n }\n if((n-prev-1)>0)\n {\n if((n-prev-2)>maxdis)\n {\n x=n-1;\n }\n }\n \n s.insert(x);\n //cout<<endl;\n return x;\n }\n \n void leave(int p) {\n s.erase(p);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n ``
1
0
['C', 'Ordered Set']
1
exam-room
Java TreeSet
java-treeset-by-tomythliu-s2zh
\n\n\nclass ExamRoom {\n int n; \n \n class Interval {\n int l;\n int r;\n int dis;\n boolean isStart;\n boolean
tomythliu
NORMAL
2022-06-14T00:38:14.004699+00:00
2022-06-14T00:38:14.004730+00:00
159
false
```\n\n\nclass ExamRoom {\n int n; \n \n class Interval {\n int l;\n int r;\n int dis;\n boolean isStart;\n boolean isEnd;\n \n Interval(int l, int r) {\n this.l = l;\n this.r = r;\n if(l == -1) {\n this.dis = r;\n isStart = true;\n } else if(r == n) {\n this.dis = n-1-l;\n isEnd = true;\n } else {\n this.dis = (r - l)/2;\n }\n }\n }\n \n Map<Integer, Interval> leftIntervals;\n Map<Integer, Interval> rightIntervals;\n TreeSet<Interval> intervals;\n \n public ExamRoom(int n) {\n this.n = n;\n leftIntervals = new HashMap();\n rightIntervals = new HashMap();\n intervals = new TreeSet<Interval>((a,b)->{\n if(a.dis > b.dis) return -1;\n if(a.dis < b.dis) return 1;\n // if(a.dis == b.dis) {\n // if(a.l <= b.l) return -1;\n // }\n \n return a.l - b.l;\n });\n \n intervals.add(new Interval(-1, n));\n }\n \n public int seat() {\n Interval largest = intervals.first();\n // System.out.println("largest l:" + largest.l + " r:" + largest.r + " isStart:" + largest.isStart);\n int seat = -1;\n if(largest.isStart) {\n seat = 0;\n } else if(largest.isEnd) {\n seat = n-1;\n } else {\n seat = largest.l + largest.dis;\n }\n \n removeInterval(largest);\n \n if(seat != 0) {\n Interval newLeft = new Interval(largest.l, seat);\n addInterval(newLeft);\n // System.out.println("left dis:" + newLeft.dis + " l:" + newLeft.l + " r:" + newLeft.r);\n }\n \n if(seat != n-1) {\n Interval newRight = new Interval(seat, largest.r);\n addInterval(newRight);\n // System.out.println("right dis:" + newRight.dis + " l:" + newRight.l + " r:" + newRight.r);\n }\n \n // System.out.println("intervals first:" + intervals.first().l + " seat:" + seat);\n \n return seat;\n }\n \n public void leave(int p) {\n Interval left = leftIntervals.get(p);\n Interval right = rightIntervals.get(p);\n \n int l = -1;\n int r = n;\n \n if(left != null) {\n l = left.l;\n removeInterval(left);\n }\n \n if(right != null) {\n r = right.r;\n removeInterval(right);\n }\n \n addInterval(new Interval(l, r));\n }\n \n private void removeInterval(Interval interval) {\n intervals.remove(interval);\n // System.out.println("After remove intervals:" + intervals + " to remove:" + interval);\n leftIntervals.remove(interval.r);\n rightIntervals.remove(interval.l);\n }\n \n private void addInterval(Interval interval) {\n intervals.add(interval);\n if(interval.r != n) leftIntervals.put(interval.r, interval);\n if(interval.l != -1) rightIntervals.put(interval.l, interval);\n }\n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(n);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```
1
0
[]
0
exam-room
C++ || Set and Vector
c-set-and-vector-by-be_quick-ulbg
\nstruct interval{\n static int tot;\n int l,r;\n int dist;\n\n interval(int l,int r){\n this->l = l;\n this->r = r;\n if(l==0)
be_quick
NORMAL
2022-04-01T20:19:24.344859+00:00
2022-04-01T20:19:41.232240+00:00
229
false
```\nstruct interval{\n static int tot;\n int l,r;\n int dist;\n\n interval(int l,int r){\n this->l = l;\n this->r = r;\n if(l==0)dist = r;\n else if((r+1)==tot)dist = r-l;\n else dist = (r-l)/2;\n }\n};\n\nint interval::tot = 0;\nauto comp = [](interval a,interval b)->bool{\n if(a.dist!=b.dist)\n return a.dist>b.dist;\n return a.l<b.l;\n};\n\nset<interval,decltype(comp)> seats(comp);\n\nclass ExamRoom {\npublic:\n int N = 0;\n set<int> occupied;\n ExamRoom(int n) {\n interval::tot = n;\n N = n;\n seats.clear();\n seats.insert(interval(0,n-1));\n }\n \n int seat() {\n interval tp = *seats.begin();\n seats.erase(seats.begin());\n // cout<<tp.l<<" "<<tp.r<<" "<<tp.dist<<"||";\n if(tp.l==0){\n if(tp.l+1<=tp.r)\n seats.insert(interval(tp.l+1,tp.r));\n occupied.insert(tp.l);\n return tp.l;\n }else if(tp.r==N-1){\n if(tp.l<=tp.r-1)\n seats.insert(interval(tp.l,tp.r-1));\n occupied.insert(tp.r);\n return tp.r;\n }\n \n int mid = tp.l+(tp.r-tp.l)/2;\n \n if(tp.l<=mid-1)\n seats.insert(interval(tp.l,mid-1));\n \n if(mid+1<=tp.r)\n seats.insert(interval(mid+1,tp.r));\n \n occupied.insert(mid);\n return mid;\n }\n \n void leave(int p) {\n auto it = occupied.find(p);\n // if(it==occupied.begin()){\n // cout<<"hello";\n // }\n int lperson = it==occupied.begin()?-1:*prev(it,1);\n int rperson = next(it,1)==occupied.end()?N:*next(it,1);\n\n seats.erase(interval(lperson+1,p-1));\n seats.erase(interval(p+1,rperson-1));\n \n if((lperson+1)<=(rperson-1))\n seats.insert(interval(lperson+1,rperson-1));\n \n occupied.erase(p);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n```
1
0
['Binary Tree', 'Ordered Set']
0
exam-room
C++ | faster than 97%
c-faster-than-97-by-arvinleetcode-8yjo
The not so difficult solution is to use a sliding window (2 pointer) approach to find the next location each time a seat is asked. That would take O(n) and ther
arvinleetcode
NORMAL
2022-01-16T10:28:42.589171+00:00
2022-01-16T10:56:54.026492+00:00
368
false
The not so difficult solution is to use a sliding window (2 pointer) approach to find the next location each time a seat is asked. That would take O(n) and there is a leetcode for that. First tried and that approach exceeds the time limit for the last test cases. So O(n) for each command is not acceptable.\nThe solution I found to work (instead of tracking which seats are free or taken), was to track the spaces. I have created a set of spaces - spaces are defined by the { distance to next person if someone sits in this space, first empty seat, last empty seat}\nThen the set is ranked by 1- First the descending based on distance to next person and 2- Second ascending based on seat number. set in C++ is created by BST so the ranking takes O(logm) that m is the number of spaces. \nIt is probably possible to make the code look cleaner.\n\nInteresting NOTE: I also tried to pass just the index of first empty and last empty to the set and track only a set of {first empty, last empty} and then rank the set by calculating the distance in the compare function of the struct. But unfortunately, with the version of C++ in leetcode, it seemed that it is not possible to pass down any member to a nested class or struct ... and I had to pass the array size at minimum to calculate the distances\n\n```\nclass ExamRoom {\npublic:\n \n int num;\n ExamRoom(int n) {\n num = n;\n spaces.insert({n, 0, n - 1});\n }\n \n int seat() {\n vector<int> location = *spaces.begin();\n spaces.erase(spaces.begin());\n int s = 0;\n if(location[1] == 0){\n s = 0;\n if(location[2] == num - 1)\n spaces.insert({num-2, 1, num-1});\n else \n if(location[2]>=1) spaces.insert({(location[2]-1)/2, 1, location[2]});\n }\n else if(location[2] == num - 1){\n s = num - 1;\n if(location[1] == 0)\n spaces.insert({num-1, 0, num - 1});\n else\n if(location[1]<=num-2) spaces.insert({(num -2 -location[1])/2, location[1], num - 2}); \n }\n else{\n s = (location[1] + location [2]) / 2;\n if(s - location[1] > 0) \n spaces.insert({(s - 1 - location[1])/2, location[1], s- 1});\n if(location[2] - s > 0) \n spaces.insert({(location[2] - s - 1)/2, s + 1, location[2]});\n }\n return s;\n }\n \n void leave(int p) {\n set<vector<int>>::iterator before = spaces.end();\n set<vector<int>>::iterator after = spaces.end();\n \n for(auto i = spaces.begin(); i!=spaces.end();i++){\n if((*i)[1] == p+1)\n after = i;\n if((*i)[2] == p-1)\n before = i;\n }\n \n if(p == 0){\n vector<int> temp = {0, p, p};\n if(after!=spaces.end()){\n temp = *after;\n spaces.erase(after);}\n \n spaces.insert({temp[2], 0, temp[2]});\n }\n else if(p == num-1){\n vector<int> temp {0, p, p};\n if(before!=spaces.end()){\n temp = *before;\n spaces.erase(before);}\n \n spaces.insert({num - temp[1]-1, temp[1], num-1});\n }\n else{\n vector<int> temp1 = {0, p, p};\n if(before!=spaces.end()){\n temp1 = *before;\n spaces.erase(before);\n }\n \n vector<int> temp2 = {0, p, p};\n if(after!=spaces.end()){\n temp2 = *after;\n spaces.erase(after);\n }\n \n spaces.insert({(temp2[2]-temp1[1])/2, temp1[1], temp2[2]});\n }\n return; \n }\n \nstruct veccompare{\n bool operator()(vector<int> const & a, vector<int> const & b) const{\n if(a[0] == b[0])\n return a[1] < b[1];\n return a[0] > b[0];\n } \n};\n \nset<vector<int>, veccompare> spaces;\n};\n\n\n```
1
0
[]
0
exam-room
Kotlin - Treeset
kotlin-treeset-by-yuanchac-bjbo
\nclass ExamRoom(n: Int) {\n\n val seated = TreeSet<Int>()\n val capacity = n\n \n fun seat(): Int {\n if(seated.isEmpty()){\n sea
yuanchac
NORMAL
2021-10-04T13:41:09.151061+00:00
2021-10-04T13:41:09.151135+00:00
90
false
```\nclass ExamRoom(n: Int) {\n\n val seated = TreeSet<Int>()\n val capacity = n\n \n fun seat(): Int {\n if(seated.isEmpty()){\n seated.add(0)\n return 0\n }\n \n var seatNum = 0\n \n var maxDistance = seated.first()\n var pre = -1\n seated.forEach{\n if(pre != -1){\n val distance = (it-pre)/2\n if(distance > maxDistance){\n maxDistance = distance\n seatNum = (it+pre)/2\n }\n }\n pre = it\n }\n if(maxDistance < capacity-1-seated.last()){\n seatNum = capacity-1\n }\n seated.add(seatNum)\n \n return seatNum\n }\n\n fun leave(p: Int) {\n seated.remove(p)\n }\n \n}\n```
1
0
[]
0
exam-room
Python seat logN, leave logN solution
python-seat-logn-leave-logn-solution-by-t5lgd
The idea is to maintain valid intervals in the dictionary d. Key is seat and value is intervals that contain key. For example, students have seats 0,4,9, then t
arsamigullin
NORMAL
2021-09-24T08:10:32.671088+00:00
2021-09-24T23:58:50.274288+00:00
1,796
false
The idea is to maintain valid intervals in the dictionary d. Key is seat and value is intervals that contain key. For example, students have seats 0,4,9, then the dictionary with valid intervals is\n```\nintervals = {0:{(0,4)}, 4:{(0,4),(4,9)}, 9:{(4,9)}}\n```\nEvery value in intervals is the set of length at most 2 because whenever we placing or evicting a student, we maintain the intervals (merging intervals or removing invalid ones) \n\nThere is also priority queue here. It conains the entry of distance, x, y where distance either y-x//2 or y-x (we use this ditance only if placing the student at 0 or n-1 place)\n\n```\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.intervals = collections.defaultdict(set)\n self.pq = [(0, 0, n - 1)]\n self.intervals[0].add((0, n - 1))\n self.n = n\n self.zeroDeleted = True\n self.nDeleted = True\n\n def seat(self) -> int:\n\n while self.pq:\n dist, i, j = heapq.heappop(self.pq)\n if (i, j) not in self.intervals[i]:\n continue\n break\n\n if self.zeroDeleted and i == 0:\n self.zeroDeleted = False\n mid = 0\n self.putrigh(mid, j)\n elif self.nDeleted and j == self.n - 1:\n self.nDeleted = False\n mid = self.n - 1\n self.putleft(i, mid)\n else:\n mid = (i + j) // 2\n self.putleft(i, mid)\n self.putrigh(mid, j)\n\n return mid\n\n def putleft(self, i, mid):\n heapq.heappush(self.pq, (-((mid - i) // 2), i, mid))\n self.cleanupleft(i, mid)\n self.cleanupright(i, mid)\n\n def putrigh(self, mid, j):\n heapq.heappush(self.pq, (-((j - mid) // 2), mid, j))\n self.cleanupleft(mid, j)\n self.cleanupright(mid, j)\n\n def cleanupleft(self, key, y):\n to_evict = set([(i, j) for i, j in self.intervals[key] if i == key])\n self.intervals[key] = self.intervals[key].difference(to_evict)\n self.intervals[key].add((key, y))\n\n def cleanupright(self, x, key):\n to_evict = set([(i, j) for i, j in self.intervals[key] if j == key])\n self.intervals[key] = self.intervals[key].difference(to_evict)\n self.intervals[key].add((x, key))\n\n def leave(self, p: int) -> None:\n vals = sorted(self.intervals[p])\n l = vals[0][0]\n r = vals[0][1]\n if p == 0:\n self.zeroDeleted = True\n heapq.heappush(self.pq, (-(r - l), l, r))\n self.cleanupright(p, r)\n self.cleanupleft(p, r)\n elif p == self.n - 1:\n self.nDeleted = True\n heapq.heappush(self.pq, (-(r - l), l, r))\n self.cleanupright(l, p)\n self.cleanupleft(l, p)\n else:\n l = vals[0][0]\n r = vals[1][1]\n self.cleanupleft(l, r)\n self.cleanupright(l, r)\n if (self.zeroDeleted and l == 0) or (self.nDeleted and r == self.n - 1):\n heapq.heappush(self.pq, (-(r - l), l, r))\n else:\n heapq.heappush(self.pq, (-((r - l) // 2), l, r))\n self.intervals.pop(p)\n```
1
0
['Heap (Priority Queue)', 'Python', 'Python3']
3
exam-room
Maximum of Difference Between Allotted Seats.
maximum-of-difference-between-allotted-s-90tp
Take Difference between Neighbouring Alloted Seats. The Max of difference will be the required Distance for each New Seat.\n\nclass ExamRoom:\n\n def __init_
adarsh_gogreen
NORMAL
2021-06-13T11:05:21.607410+00:00
2021-06-13T11:05:21.607470+00:00
148
false
Take Difference between Neighbouring Alloted Seats. The Max of difference will be the required Distance for each New Seat.\n```\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.c=0\n self.akk=[]\n self.n=n\n def seat(self) -> int:\n if(self.c==0):\n self.akk.append(0)\n self.c+=1\n return 0\n \n first=self.akk[0]-0\n last=self.n-self.akk[-1]-1\n midmax=0\n midmaxindex=0\n for i in range(1,len(self.akk)):\n if(((self.akk[i]-self.akk[i-1])//2) > midmax):\n midmax=((self.akk[i]-self.akk[i-1])//2)\n midmaxindex=midmax+self.akk[i-1]\n if(first>=last and first>=midmax):\n self.c+=1\n self.akk.insert(0,0)\n return 0\n \n elif(last>first and last>midmax):\n self.c+=1\n self.akk.append(self.n-1)\n return self.n-1\n \n else:\n self.c+=1\n bisect.insort(self.akk,midmaxindex)\n return midmaxindex\n \n \n def leave(self, p: int) -> None:\n self.akk.pop(self.akk.index(p))\n self.c-=1\n```
1
0
[]
0
exam-room
Python Indexed Priority Queue O(logN) seat(), O(logN) leave()
python-indexed-priority-queue-ologn-seat-xqnp
Inspired by William Fiset\'s binary heap indexed priority queue implementation:\n\nhttps://www.youtube.com/watch?v=jND_WJ8r7FE&t=342s\n\nAlso took some notes fr
alando46
NORMAL
2021-01-19T05:14:03.774250+00:00
2021-01-19T05:18:41.602891+00:00
734
false
Inspired by William Fiset\'s binary heap indexed priority queue implementation:\n\nhttps://www.youtube.com/watch?v=jND_WJ8r7FE&t=342s\n\nAlso took some notes from @spatar \'s implementation:\n\nhttps://leetcode.com/problems/exam-room/discuss/139941/Python-O(log-n)-time-for-both-seat()-and-leave()-with-heapq-and-dicts-Detailed-explanation\n\nHowever, as this is a true indexed priority queue the heap only stores valid segments. Invalid segments are eagerly removed in O(logn) as well by swapping with the value at the bottom right of the heap, removing it O(1), and updating the heap invariant O(logn). One downside is for really large inputs, the index priority queue must construct a key map first. I might try and rewrite the priority queue so this isn\'t required, but i\'m not sure if that\'s possible. \n\nAnyways, upvote if you like. Despite getting TLE on LC this is the most comprehensive way to solve this problem.\n\n```\nclass IPQ:\n \n def __init__(self, N):\n self.values = [None] * N\n # each index of the position map is the key index\n # of an object. the value at that index is the \n # top-left->bottom-right index of the object in the\n # heap\n # position map is key_index:heap_pos\n self.pm = [-1] * N\n # inverse map is heap_pos:key_index\n self.im = [-1] * N\n self.sz = 0\n \n def get_heap(self):\n """useful for debugging and understanding"""\n return [self.values[i] for i in self.im if i != -1]\n \n def _swim(self, h_i):\n """\n Time O(logn)\n """\n p = (h_i-1)//2\n # if the idx of the current node is not the root node\n # (which has idx=0) and the value of the current node\n # is less than the value of the parent node...\n while h_i > 0 and self._less(h_i, p):\n # we need to swap the current node with the parent node\n self._swap(h_i, p)\n h_i = p\n p = (h_i-1)//2\n\n def _sink(self, h_i):\n """\n Time O(logn)\n Sinks the node at index i by swapping\n itself with the smallest of the left\n or the right child node.\n """\n while True:\n left = 2*h_i+1\n right = 2*h_i+2\n smallest = left\n\n if right < self.sz and self._less(right, left):\n smallest = right\n\n if left >= self.sz or self._less(h_i, smallest):\n break\n\n self._swap(smallest, h_i)\n h_i = smallest\n\n def _swap(self, h_i, h_j):\n """Time O(1)"""\n # use inverse map to update position map\n # heap pos j-> ki j -> pos j = i\n self.pm[self.im[h_j]] = h_i\n self.pm[self.im[h_i]] = h_j\n # update inverse map\n self.im[h_i], self.im[h_j] = self.im[h_j], self.im[h_i]\n\n def _less(self, h_i, h_j):\n """\n Time O(1)\n Takes heap positions i and j, looks up values and returns\n if heap element i < heap element j\n """\n return self.values[self.im[h_i]] < self.values[self.im[h_j]]\n\n def insert(self, ki, value):\n """Time O(logn)"""\n \n # update values map\n self.values[ki] = value\n # update heap position map\n self.pm[ki] = self.sz\n # update inverse position (heap_pos:ki) map\n self.im[self.sz] = ki\n # because we start with inserted val at end, we\n # swim it up\n self._swim(self.sz)\n # increment size\n self.sz += 1\n \n def remove(self, ki):\n """Time O(logn)\n Remove a segment that starts with ki\n """\n # first find the heap index of that key\n h_i = self.pm[ki]\n # decrement the size\n self.sz -= 1\n # next swap that key index with the last thing in the heap\n self._swap(h_i, self.sz)\n # because i was swapped, i now is the position\n # of the node that was previously at the bottom\n # right of the heap. we don\'t know if we need to\n # push that node down or bring it closer to the top\n # so we call sink(i) and swim(i) to make sure it is \n # in the right place.\n self._sink(h_i)\n self._swim(h_i)\n\n val = self.values[ki]\n self.values[ki] = None\n self.pm[ki] = -1\n self.im[self.sz] = -1\n return ki, val\n\n def update(self, ki, value):\n """Time O(logn)"""\n h_i = self.pm[ki]\n self.values[ki] = value\n self._sink(h_i)\n self._swim(h_i)\n \n def poll(self):\n """\n Time O(logn + k)\n where k is num of vals at top of heap\n with same min val\n \n guaranteed to have at least 1 item in heap\n """\n # find ki (start idx) with greatest val\n # start from h_i = 0 and go down until val increases\n # top of heap\n ki = self.im[0]\n val = self.values[ki]\n queue = deque([0])\n while queue:\n h_i = queue.popleft()\n left = 2*h_i+1\n right = 2*h_i+2\n if right < self.sz and self.values[self.im[right]] == val:\n queue.append(right)\n if left < self.sz and self.values[self.im[left]] == val:\n queue.append(left)\n ki = min(ki, self.im[h_i])\n return self.remove(ki)\n\nclass ExamRoom:\n\n def __init__(self, n: int):\n\n self.n = n\n # we use this to check a cornercase where \n # the seat leaving opens up a segment of \n # start and end = that seat index\n self.seats = [0]*n\n \n # initialize queue\n self.ipq = IPQ(n)\n \n # these are just lookup keys for the priority queue\n # we just need n number of unique keys, their values are\n # irrelevant\n self.availKeys = set(range(n))\n \n # we need a way to remove a priority queue lookup key\n # based on just the upper or lower segment bound\n \n # lower_idx:key\n self.leftKey = {}\n # upper_idx:key\n self.rightKey = {}\n \n # push first segment to queue\n self.put_segment(0,n-1)\n \n def clean_key_map(self, key, seg):\n if key == None:\n return\n\n self.availKeys.add(key)\n del self.leftKey[seg[1]]\n del self.rightKey[seg[2]]\n \n def put_segment(self, first, last):\n if first == 0 or last == self.n - 1:\n priority = last-first\n else:\n priority = (last - first) // 2\n \n segment = [-priority, first, last]\n \n key = self.availKeys.pop()\n self.leftKey[first] = key\n self.rightKey[last] = key\n self.ipq.insert(key, segment)\n\n def seat(self) -> int:\n k, (p, first, last) = self.ipq.poll()\n self.clean_key_map(k, (p,first,last))\n\n if first == 0:\n out = 0\n if first != last:\n self.put_segment(first+1, last)\n \n elif last == self.n-1:\n out = last\n if first != last:\n self.put_segment(first, last-1)\n else:\n out = first + (last - first) // 2\n \n if out > first:\n self.put_segment(first, out-1)\n if out < last:\n self.put_segment(out+1, last)\n\n self.seats[out] = 1\n\n return out\n\n def leave(self, p: int) -> None:\n lowerAvail, upperAvail = True, True\n \n # check to see if there is\n # avail seg that ends on left and right sides\n if p == 0 or self.seats[p-1]:\n lowerAvail = False\n if p+1==self.n or self.seats[p+1]:\n upperAvail = False\n \n self.seats[p] = 0 \n\n # there is no space on either side\n # make avail segment of size 1\n if not lowerAvail and not upperAvail:\n self.put_segment(p,p)\n return\n\n if lowerAvail:\n # get priority queue key for segment which ends at left upper\n leftKey = self.rightKey[p-1]\n _, leftSeg = self.ipq.remove(leftKey)\n self.clean_key_map(leftKey, leftSeg)\n if upperAvail:\n # get priority queue key for segment which starts at right lower\n rightKey = self.leftKey[p+1]\n _, rightSeg = self.ipq.remove(rightKey)\n self.clean_key_map(rightKey, rightSeg)\n\n # we have both lower and upper segments\n if lowerAvail and upperAvail:\n self.put_segment(leftSeg[1], rightSeg[2])\n # there is only a lower segment\n elif lowerAvail:\n self.put_segment(leftSeg[1], p)\n # there is only an upper segment\n elif upperAvail:\n self.put_segment(p, rightSeg[2])
1
1
['Heap (Priority Queue)']
0
exam-room
Java hashmap and treeset solution faster than 81% with seat O(logN) and leave O(1))
java-hashmap-and-treeset-solution-faster-zarx
\nclass ExamRoom {\n\n int count = 0;\n int capability;\n TreeSet<int[]> pq; \n Map<Integer, Pair<Integer, Integer>> map; // key is seat itself, va
yzhou78
NORMAL
2020-11-14T19:36:03.957385+00:00
2020-11-14T19:42:15.212098+00:00
188
false
```\nclass ExamRoom {\n\n int count = 0;\n int capability;\n TreeSet<int[]> pq; \n Map<Integer, Pair<Integer, Integer>> map; // key is seat itself, value is pair which record its\' left and right neighbors\n \n public ExamRoom(int N) {\n this.capability = N;\n this.count = 0;\n this.pq = new TreeSet<int[]>((a ,b)-> {\n int len_a = (a[1]-a[0])/2;\n int len_b = (b[1]-b[0])/2;\n if (a[0] == -1 || a[1] == capability) {\n len_a = a[1] - a[0] - 1;\n }\n if (b[0] == -1 || b[1] == capability) {\n len_b = b[1] - b[0] - 1;\n }\n if (len_b - len_a != 0) {\n return len_b - len_a;\n } else {\n return (a[0] - b[0]);\n }\n });\n this.map = new HashMap<>();\n pq.add(new int[] {-1, capability}); \n }\n \n public int seat() {\n count++;\n int[] seatsPair = pq.pollFirst();\n int left = seatsPair[0];\n int right = seatsPair[1];\n Pair<Integer, Integer> leftP = map.get(left);\n Pair<Integer, Integer> rightP = map.get(right);\n if (left == -1) {\n map.put(0, new Pair<Integer,Integer>(-1, right));\n if (right != capability)\n map.put(right, new Pair<Integer,Integer>(0, rightP.getValue()));\n pq.add(new int[] {0, right}); // first choice\n return 0;\n } else if (right == capability) {\n map.put(capability-1, new Pair<Integer,Integer>(left, capability));\n map.put(left, new Pair<Integer,Integer>(leftP.getKey(), capability-1));\n pq.add(new int[] {left, capability-1}); // second choice\n return capability-1;\n } else {\n int pos = left + (right - left) / 2;\n map.put(pos, new Pair<>(left, right));\n map.put(left, new Pair<>(leftP.getKey(), pos));\n map.put(right, new Pair<>(pos, rightP.getValue())); \n pq.add(new int[] {left, pos});\n pq.add(new int[] {pos, right});\n return pos;\n }\n }\n \n public void leave(int p) {\n count--;\n Pair<Integer,Integer> pair = map.get(p);\n int pos1 = pair.getKey(); \n int pos2 = pair.getValue();\n Pair<Integer, Integer> leftP = map.get(pos1);\n Pair<Integer, Integer> rightP = map.get(pos2);\n map.remove(p);\n if (leftP != null)\n map.put(pos1, new Pair<Integer, Integer>(leftP.getKey(), pos2));\n if (rightP != null)\n map.put(pos2, new Pair<Integer, Integer>(pos1, rightP.getValue()));\n pq.remove(new int[] {pos1, p});\n pq.remove(new int[] {p, pos2});\n pq.add(new int[] {pos1, pos2});\n }\n}\n```
1
0
[]
0
exam-room
[Python] O(logN) time for both seat() and leave() Using Segment Tree
python-ologn-time-for-both-seat-and-leav-plum
\nclass SegmentTree(object):\n def __init__(self, start, end, size, rank=1):\n self.rank = rank # rank is the number of leaves of this segment tree,
shoomoon
NORMAL
2020-09-10T01:48:20.765258+00:00
2020-09-10T01:48:20.765297+00:00
273
false
```\nclass SegmentTree(object):\n def __init__(self, start, end, size, rank=1):\n self.rank = rank # rank is the number of leaves of this segment tree, to keep the segment tree balance and reduce the depth of the tree\n self.start = start\n self.end = end\n self.left = None\n self.right = None\n self.priority_segment = self # the most priority segment\n self.priority = end - start if start == 0 or end == size - 1 else (end - start) // 2\n\n\nclass ExamRoom(object):\n\n def __init__(self, N):\n """\n :type N: int\n """\n self.segmentTree = SegmentTree(0, N - 1, N)\n self.N = N\n\n\n def position(self):\n node = self.segmentTree.priority_segment\n if node.start == 0:\n return 0\n if node.end == self.N - 1:\n return self.N - 1\n return (node.start + node.end) // 2\n\n def update(self, node):\n """\n :type node: SegmentTree\n :rtype: SegmentTree\n """\n\t\t# after modifying some node (remove or add or merge seats), update all ancestors nodes\n if not node or not node.left and not node.right:\n return node\n if not node.left or not node.right:\n return node.left or node.right\n node.rank = node.left.rank + node.right.rank\n node.start = node.left.start\n node.end = node.right.end\n if node.left.priority >= node.right.priority:\n node.priority = node.left.priority\n node.priority_segment = node.left.priority_segment\n else:\n node.priority = node.right.priority\n node.priority_segment = node.right.priority_segment\n return node\n\n def remove(self, node, p):\n """\n :type node: SegmentTree\n :type p: int\n :rtype: SegmentTree\n """\n\t\t# occupy seat p, and return new segment node\n if node.end < p or node.start > p:\n return node\n if not node.left:\n if node.start == node.end:\n return None\n if p == node.start:\n return SegmentTree(p + 1, node.end, self.N)\n if p == node.end:\n return SegmentTree(node.start, p - 1, self.N)\n node.left = SegmentTree(node.start, p - 1, self.N)\n node.right = SegmentTree(p + 1, node.end, self.N)\n else:\n node.left = self.remove(node.left, p)\n node.right = self.remove(node.right, p)\n return self.update(node)\n\n def add(self, node, p):\n """\n :type node: SegmentTree\n :type p: int\n :rtype: SegmentTree\n """\n\t\t# release seat p\n* \t\t # # add segment besides leaves, may increase the segment tree\'s depth\n* # if not node.left:\n* # ans = SegmentTree(min(p, node.start), max(p, node.end), self.N)\n* # if p == node.start - 1 or p == node.end + 1:\n* # return ans\n* # cur_node = SegmentTree(p, p, self.N)\n* # if p < node.start - 1:\n* # ans.left = cur_node\n* # ans.right = node\n* # else:\n* # ans.left = node\n* # ans.right = cur_node\n* # node = ans\n* # elif p <= (node.end + node.start) // 2:\n* # node.left = self.add(node.left, p)\n* # else:\n* # node.right = self.add(node.right, p)\n* # if node.left.end + 1 == node.right.start:\n* # node.left, node.right = self.merge(node.left, node.right, node.left.rank < node.right.rank)\n* # return self.update(node)\n \n\t\t# not always add segment besides leaves\n if p < node.start - 1 or p > node.end + 1 or not node.left:\n ans = SegmentTree(min(p, node.start), max(p, node.end), self.N)\n cur_node = SegmentTree(p, p, self.N)\n if p < node.start - 1:\n ans.left = cur_node\n ans.right = node\n elif p > node.end + 1:\n ans.left = node\n ans.right = cur_node\n node = ans\n return self.update(node)\n elif p <= (node.right.start + node.left.end) // 2:\n node.left = self.add(node.left, p)\n else:\n node.right = self.add(node.right, p)\n\t\t# if adjascent subtrees don\'t have gap between them, merge them\n if node.left.end + 1 == node.right.start:\n node.left, node.right = self.merge(node.left, node.right, node.left.rank < node.right.rank)\n return self.update(node)\n\n def merge(self, n1, n2, toLeft = True):\n """\n :type n1: SegmentTree\n :type n2: SegmentTree\n :rtype: SegmentTree, SegmentTree\n """\n\t\t# if n1.rank < n2.rank, merge to left: delete the first leaf segment of n2, extend the last leaf segment of n1\n\t\t# otherwise, merge to right: delete the last leaf segment of n1, extend the first leaf segment of n2\n if not n1.left and not n2.left: # both are leaves\n if toLeft:\n return SegmentTree(n1.start, n2.end, self.N), None\n else:\n return None, SegmentTree(n1.start, n2.end, self.N)\n if not n1.left:\n n1, n2.left = self.merge(n1, n2.left, toLeft)\n elif not n2.left:\n n1.right, n2 = self.merge(n1.right, n2, toLeft)\n else:\n n1.right, n2.left = self.merge(n1.right, n2.left, toLeft)\n n1 = self.update(n1)\n n2 = self.update(n2)\n return n1, n2\n\n\n def seat(self):\n """\n :rtype: int\n """\n\t\t# \n pos = self.position()\n self.segmentTree = self.remove(self.segmentTree, pos)\n return pos\n\n\n def leave(self, p):\n """\n :type p: int\n :rtype: None\n """\n if not self.segmentTree:\n self.segmentTree = SegmentTree(p, p, self.N)\n else:\n self.segmentTree = self.add(self.segmentTree, p)\n```
1
0
[]
1
exam-room
[Java] O(log n) for both operations using TreeSet
java-olog-n-for-both-operations-using-tr-3p66
\nclass ExamRoom {\n class Interval implements Comparable<Interval> {\n public int L, R, dist, index;\n Interval(int L, int R) {\n t
shk10
NORMAL
2020-09-07T02:32:48.397450+00:00
2020-09-07T02:32:48.397541+00:00
219
false
```\nclass ExamRoom {\n class Interval implements Comparable<Interval> {\n public int L, R, dist, index;\n Interval(int L, int R) {\n this.L = L;\n this.R = R;\n if(L == 0) {\n dist = R - L; index = L;\n } else if(R == N - 1) {\n dist = R - L; index = R;\n } else {\n dist = (R - L) >> 1; index = L + dist;\n }\n }\n @Override\n public int compareTo(Interval i) {\n return dist == i.dist ? i.index - index : dist - i.dist;\n }\n }\n private int N;\n private TreeSet<Integer> seats = new TreeSet<>();\n private TreeSet<Interval> intervals = new TreeSet<>();\n\n public ExamRoom(int N) {\n this.N = N;\n intervals.add(new Interval(0, N-1));\n }\n \n public int seat() {\n Interval max = intervals.pollLast();\n int index = max.index;\n seats.add(index);\n if(max.L <= index-1) {\n intervals.add(new Interval(max.L, index-1));\n }\n if(index+1 <= max.R) {\n intervals.add(new Interval(index+1, max.R));\n }\n return index;\n }\n \n public void leave(int p) {\n seats.remove(p);\n Integer left = seats.floor(p), right = seats.ceiling(p);\n int L = left == null ? 0 : left + 1, R = right == null ? N-1 : right - 1;\n if(L <= p-1) {\n intervals.remove(new Interval(L, p-1));\n }\n if(p+1 <= R) {\n intervals.remove(new Interval(p+1, R));\n }\n intervals.add(new Interval(L, R));\n }\n}\n```
1
0
[]
0
exam-room
[Python] logN logN SortedList
python-logn-logn-sortedlist-by-cheol-uewe
python\nfrom sortedcontainers import SortedList\n\n\nclass ExamRoom:\n\n def __init__(self, N: int):\n self.starts = dict()\n self.ends = dict(
cheol
NORMAL
2020-08-18T16:39:28.575562+00:00
2020-08-20T11:04:54.590086+00:00
300
false
```python\nfrom sortedcontainers import SortedList\n\n\nclass ExamRoom:\n\n def __init__(self, N: int):\n self.starts = dict()\n self.ends = dict()\n # Alternative Heap \n self.fragments = SortedList()\n self.n = N\n \n self.add_fragment((0, N-1))\n \n def distance(self, s, e):\n if s == 0:\n return e\n if e == self.n-1:\n return e-s\n mid = (s+e) // 2\n return min(mid-s, e-mid)\n\n def add_fragment(self, fragment):\n s, e = fragment\n if s > e:\n return\n self.starts[s] = self.ends[e] = fragment\n self.fragments.add((self.distance(s,e), -s, -e))\n \n def remove_fragment(self, fragment):\n s, e = fragment\n if s > e:\n return\n self.starts.pop(s)\n self.ends.pop(e)\n self.fragments.remove((self.distance(s,e), -s, -e))\n \n def divideFragment(self, fragment):\n s, e = fragment\n if s == 0:\n return s, [(s+1, e)]\n elif e == self.n-1:\n return e, [(s, e-1)]\n mid = (s+e) // 2\n return mid, [(s, mid-1), (mid+1, e)]\n \n def mergeFragment(self, left, right):\n if left == None:\n return (right[0]-1, right[1])\n if right == None:\n return (left[0], left[1]+1)\n return (left[0], right[1])\n \n def seat(self) -> int:\n # print(self.fragments)\n _, s, e = self.fragments[-1]\n s, e = -s, -e\n \n self.remove_fragment((s, e))\n seat, fragments = self.divideFragment((s, e))\n for frag in fragments:\n self.add_fragment(frag)\n\n return seat\n\n def leave(self, p: int) -> None:\n # print(self.fragments)\n left, right = self.ends.get(p-1, None), self.starts.get(p+1, None)\n if left:\n self.remove_fragment(left)\n if right:\n self.remove_fragment(right)\n if left == right == None:\n fragment = (p, p)\n else:\n fragment = self.mergeFragment(left, right)\n self.add_fragment(fragment)\n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(N)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
1
0
[]
1
exam-room
Golang 8ms 100% Solution
golang-8ms-100-solution-by-tjucoder-7eqc
go\ntype ExamRoom struct {\n\tseat int\n\tstudent []int\n}\n\nfunc Constructor(N int) ExamRoom {\n\treturn ExamRoom{\n\t\tseat: N,\n\t\tstudent: []int{},\
tjucoder
NORMAL
2020-08-14T13:53:44.385913+00:00
2020-08-14T13:53:44.385948+00:00
219
false
```go\ntype ExamRoom struct {\n\tseat int\n\tstudent []int\n}\n\nfunc Constructor(N int) ExamRoom {\n\treturn ExamRoom{\n\t\tseat: N,\n\t\tstudent: []int{},\n\t}\n}\n\nfunc (er *ExamRoom) Seat() int {\n\tif len(er.student) == 0 {\n\t\ter.student = append(er.student, 0)\n\t\treturn 0\n\t}\n\tseat, distance, index := 0, er.student[0], 0\n\tfor i := 0; i < len(er.student)-1; i++ {\n\t\tcurrentDistance := (er.student[i+1] - er.student[i]) / 2\n\t\tif currentDistance > distance {\n\t\t\tdistance = currentDistance\n\t\t\tseat = er.student[i] + distance\n\t\t\tindex = i + 1\n\t\t}\n\t}\n if er.seat - 1 - er.student[len(er.student)-1] > distance {\n\t\tdistance = er.seat - 1 - er.student[len(er.student)-1]\n\t\tseat = er.seat - 1\n\t\tindex = len(er.student)\n\t}\n\ter.student = append(er.student, 0)\n\tcopy(er.student[index+1:], er.student[index:])\n\ter.student[index] = seat\n\treturn seat\n}\n\nfunc (er *ExamRoom) Leave(p int) {\n\tl, r := 0, len(er.student)-1\n\tfor l <= r {\n\t\tm := (l+r)>>1\n\t\tif er.student[m] == p {\n // remove student[m]\n\t\t\ter.student = append(er.student[:m], er.student[m+1:]...)\n\t\t\treturn\n\t\t}\n\t\tif er.student[m] > p {\n\t\t\tr = m-1\n\t\t} else {\n\t\t\tl = m+1\n\t\t}\n\t}\n\treturn\n}\n```
1
0
['Go']
0
exam-room
C++ Solution
c-solution-by-indrajohn-e22y
\nclass ExamRoom {\npublic:\n int num;\n set<int> sec;\n ExamRoom(int N) {\n num = N;\n }\n \n int seat() {\n if (sec.size() ==
indrajohn
NORMAL
2020-07-27T09:50:50.139745+00:00
2020-07-27T09:50:50.139791+00:00
311
false
```\nclass ExamRoom {\npublic:\n int num;\n set<int> sec;\n ExamRoom(int N) {\n num = N;\n }\n \n int seat() {\n if (sec.size() == 0){\n sec.insert(0);\n return 0;\n } else if (sec.size() == 1) {\n set<int> :: iterator it = sec.begin();\n int res = 0;\n if (*it >= (num - *it)) {\n res = 0;\n } else {\n res = num - 1;\n }\n sec.insert(res);\n return (res);\n } \n \n int max_gap, min_pos, zero_gap, end_gap;\n max_gap = min_pos = zero_gap = end_gap = 0;\n bool zero_flag, end_flag;\n zero_flag = end_flag = false;\n if (sec.find(0) == sec.end()) {\n zero_flag = true;\n zero_gap = *(sec.begin());\n } \n if (sec.find(num - 1) == sec.end()) {\n end_flag = true;\n end_gap = (num - 1) - (*(sec.rbegin()));\n }\n if (zero_flag || end_flag) {\n if (end_gap > zero_gap) {\n zero_flag = false;\n } else if (end_gap <= zero_gap) {\n end_flag = false;\n } \n }\n \n for (set<int> :: iterator it = sec.begin(); it != sec.end(); it++) {\n set<int> :: iterator iter = it;\n if (++iter == sec.end())\n break;\n if ((abs(*iter - *it) / 2) > max_gap) {\n max_gap = (abs(*iter - *it) / 2);\n min_pos = *it + max_gap;\n } else if ((abs(*iter - *it) / 2) == max_gap) {\n if (min_pos > (*it + max_gap)) {\n min_pos = *it + max_gap;\n }\n }\n }\n int res = min_pos;\n if (zero_flag) {\n if (zero_gap >= max_gap) {\n res = 0;\n } else {\n res = min_pos;\n }\n } else if (end_flag) {\n if (end_gap > max_gap) {\n res = num - 1;\n } else {\n res = min_pos;\n }\n }\n sec.insert(res);\n return res;\n }\n \n void leave(int p) {\n sec.erase(p);\n }\n};\n\n```
1
0
[]
0
exam-room
Elegant O(LogN) C++ solution with set and map
elegant-ologn-c-solution-with-set-and-ma-bn4q
\nstruct Interval {\n Interval(int _left, int _right, int _n) \n : left(_left), \n right(_right), \n N(_n) {\n \n } \n
etotuan
NORMAL
2020-06-22T04:08:52.228520+00:00
2020-06-22T04:08:52.228575+00:00
212
false
```\nstruct Interval {\n Interval(int _left, int _right, int _n) \n : left(_left), \n right(_right), \n N(_n) {\n \n } \n \n int get_minimax() const {\n return (left<0) ? ((right < 0) ? N - 1 : right) \n : ((right < 0) ? N - 1 - left \n : (right - left) / 2);\n }\n \n int get_mid() const {\n return (left<0) ? 0 : left + get_minimax();\n }\n \n int left;\n int right;\n int N;\n};\n\nbool operator<(const Interval& l, const Interval& r) {\n \n int l_minimax = l.get_minimax();\n int r_minimax = r.get_minimax();\n\n int l_mid = l.get_mid();\n int r_mid = r.get_mid();\n \n if (l_minimax < r_minimax) return true;\n if (l_minimax == r_minimax && l_mid > r_mid) return true;\n return false;\n}\n\nclass ExamRoom {\npublic:\n ExamRoom(int _n) : N(_n) {\n Interval first(-1, -1, N);\n m.insert(first);\n }\n \n int seat() {\n \n Interval it = (*m.rbegin());\n \n int p = it.get_mid(); \n \n tail[it.left] = p;\n head[it.right] = p;\n \n tail[p] = it.right;\n head[p] = it.left;\n \n Interval half_left(it.left, p, N);\n \n Interval half_right(p, it.right, N); \n \n m.erase(it);\n m.insert(half_left);\n m.insert(half_right);\n \n return p;\n }\n \n void leave(int p) {\n\n int old_head = head[p]; \n m.erase(Interval(old_head, p, N));\n \n int old_tail = tail[p];\n m.erase(Interval(p, old_tail, N));\n \n m.insert(Interval(old_head, old_tail, N));\n }\n \n int N;\n \n set<Interval> m;\n unordered_map<int, int> head;\n unordered_map<int, int> tail;\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(N);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n```
1
0
[]
0
exam-room
O(log n) for both seat and leave, but it is harder than most hard problems
olog-n-for-both-seat-and-leave-but-it-is-f38a
Idea: use a heap to maintain the vacant segment, but there are so many tricky things to handle.\n\n\nclass Segment:\n def __init__(self, MAX, start, end):\n
fang15
NORMAL
2020-06-07T14:33:21.901602+00:00
2020-06-07T14:33:21.901650+00:00
218
false
Idea: use a heap to maintain the vacant segment, but there are so many tricky things to handle.\n\n```\nclass Segment:\n def __init__(self, MAX, start, end):\n self.MAX = MAX # the most right spot\n self.start = start\n self.end = end\n self.status = True\n \n @property\n def length(self):\n span = self.end - self.start + 1\n \n if self.start == 0 or self.end == self.MAX:\n return span - 1\n \n if span % 2:\n return span // 2\n \n return span // 2 - 1\n\n \n def split(self):\n left = None\n right = None\n \n if self.start == 0:\n seat = 0 \n elif self.end == self.MAX:\n seat = self.MAX\n else:\n seat = (self.start + self.end) // 2\n \n if seat > self.start:\n left = Segment(self.MAX, self.start, seat - 1)\n \n if seat < self.end:\n right = Segment(self.MAX, seat + 1, self.end)\n\n return left, right, seat\n \n def __lt__(self, other): # high priority lower\n if self.length == other.length:\n return self.start <= other.start \n \n return self.length > other.length\n \n \nclass ExamRoom:\n\n def __init__(self, N: int):\n self.N = N\n self.MAX = N-1 # the most right spot\n init_seg = Segment(self.MAX, 0, self.MAX)\n self.heap = [init_seg]\n self.seated = {\n -1: [None, init_seg],\n N: [init_seg, None]\n }\n\n def seat(self) -> int:\n if len(self.seated) == self.N + 2: # -1, and N are two virtual seat\n raise Exception(\'Room full, sorry\')\n \n seg = self._pop()\n left, right, seat = seg.split()\n self._push(left)\n self._push(right)\n self.seated[seat] = [left, right]\n \n # tricky part\n self.seated[seg.start-1][1] = left\n self.seated[seg.end+1][0] = right\n \n return seat\n\n def leave(self, p: int) -> None:\n if p not in self.seated:\n raise Exception(\'No person sits there\')\n \n left, right = self.seated[p]\n del self.seated[p]\n \n start = p\n end = p\n \n if left:\n left.status = False\n start = left.start\n \n if right:\n right.status = False\n end = right.end\n \n merged = Segment(self.MAX, start, end)\n # tricky part\n self.seated[merged.start-1][1] = merged\n self.seated[merged.end+1][0] = merged\n \n self._push(merged)\n \n \n def _push(self, seg):\n if seg:\n heapq.heappush(self.heap, seg)\n \n def _pop(self):\n while self.heap:\n seg = heapq.heappop(self.heap)\n if seg.status: # drop invalid segs\n return seg\n \n raise Exception(\'empty heap\')\n\t\t\n```
1
0
[]
0
exam-room
Simple C++ solution
simple-c-solution-by-caspar-chen-hku-5swi
\nclass ExamRoom {\npublic:\n \n vector<int> seats;\n int num;\n \n ExamRoom(int N) {\n num = N;\n }\n \n int seat() {\n i
caspar-chen-hku
NORMAL
2020-05-20T15:47:18.496044+00:00
2020-05-20T15:47:18.496097+00:00
282
false
```\nclass ExamRoom {\npublic:\n \n vector<int> seats;\n int num;\n \n ExamRoom(int N) {\n num = N;\n }\n \n int seat() {\n if (seats.empty()){\n seats.push_back(0); return 0;\n }else{\n int maxSeat = 0, maxDis = seats[0], toinsert = 0;\n for (int i=0; i<seats.size()-1; i++){\n if ((seats[i+1]-seats[i])/2 > maxDis){\n maxDis = (seats[i+1]-seats[i])/2;\n maxSeat = (seats[i+1]+seats[i])/2;\n toinsert = i+1;\n }\n }\n if (num-1-seats.back()>maxDis){\n seats.push_back(num-1);\n return num-1;\n }else{\n seats.insert(seats.begin()+toinsert, maxSeat);\n return maxSeat; \n }\n }\n }\n \n void leave(int p) {\n int i=0, j=seats.size()-1, mid;\n while (i<=j){\n mid = (i+j)/2;\n if (seats[mid]==p){\n seats.erase(seats.begin()+mid); return;\n }else if (seats[mid]>p) j=mid-1;\n else i=mid+1;\n }\n return;\n }\n};\n```
1
0
[]
0
exam-room
Clean python solution
clean-python-solution-by-olivia_xie_93-xirv
python\nclass ExamRoom:\n\n def __init__(self, N: int):\n self.n = N\n self.seats = []\n\n def seat(self) -> int:\n n = self.n\n
olivia_xie_93
NORMAL
2020-05-17T23:38:20.270080+00:00
2020-05-17T23:38:20.270129+00:00
242
false
```python\nclass ExamRoom:\n\n def __init__(self, N: int):\n self.n = N\n self.seats = []\n\n def seat(self) -> int:\n n = self.n\n last_seat = -1\n dist = 0\n seat = -1\n idx = -1\n \n for i in range(len(self.seats)):\n if last_seat == -1:\n if self.seats[i] > dist:\n dist = self.seats[i]\n seat = 0\n idx = 0\n else:\n if (self.seats[i]-last_seat)//2 > dist:\n dist = (self.seats[i]-last_seat)//2\n seat = (self.seats[i]+last_seat)//2\n idx = i\n last_seat = self.seats[i]\n \n if last_seat == -1:\n seat = 0\n idx = 0\n else:\n if n-1-last_seat > dist:\n dist = n-1-last_seat\n seat = n-1\n idx = len(self.seats)\n \n self.seats.insert(idx, seat)\n return seat\n \n def leave(self, p: int) -> None:\n self.seats.remove(p) # can use binary search and reduce to log(n)\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(N)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
1
0
[]
1
exam-room
Clean Python Solution
clean-python-solution-by-olivia_xie_93-onjj
This is question is similar to 849. Maximize Distance to Closest Person. Additionally, we need to know where Alex will take a seat (suppose choose the smaller i
olivia_xie_93
NORMAL
2020-04-17T20:43:53.554484+00:00
2020-04-17T20:43:53.554524+00:00
228
false
This is question is similar to [849. Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/). Additionally, we need to know where Alex will take a seat (suppose choose the smaller index when same maximum distances exist).\n\n\n```python\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n n = len(seats)\n start = -1\n res = 0\n seat = -1\n for i in range(n):\n if seats[i] == 0:\n continue\n if start == -1:\n if i > res:\n res = i\n seat = 0\n else:\n if (i-start)//2 > res:\n res = (i-start)//2\n seat = (i+start)//2\n start = i\n if n-1-start > res:\n res = n-1-start\n seat = n-1\n print("Alex will seat here: %d" % seat)\n return res\n```\n\nSo we can follow the same method. In order to save more space, we just apply a list to record the index of non-empty seats.\n\n```python\nclass ExamRoom:\n\n def __init__(self, N: int):\n self.seats = []\n self.total = N\n\n def seat(self) -> int:\n n = self.total\n start = -1\n idx = -1\n mx = 0\n \n for i in self.seats:\n if start == -1:\n if i > mx:\n mx = i\n idx = 0\n else:\n if (i-start)//2 > mx:\n mx = (i-start)//2\n idx = (i+start)//2\n start = i\n \t\n if start != -1:\n if n-1-start > mx:\n mx = n-1-start\n idx = n-1\n else:\n idx = 0\n \n bisect.insort(self.seats, idx)\n return idx\n\n def leave(self, p: int) -> None:\n self.seats.remove(p)\n \n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(N)\n# param_1 = obj.seat()\n# obj.leave(p)\n```\n\nWe can apply Binary Search to speed up the insert and delete process.\n\n```python\nclass ExamRoom:\n\n def __init__(self, N: int):\n self.seats = []\n self.total = N\n\n def seat(self) -> int:\n n = self.total\n start = -1\n idx = -1\n mx = 0\n \n for i in self.seats:\n if start == -1:\n if i > mx:\n mx = i\n idx = 0\n else:\n if (i-start)//2 > mx:\n mx = (i-start)//2\n idx = (i+start)//2\n start = i\n \t\n if start != -1:\n if n-1-start > mx:\n mx = n-1-start\n idx = n-1\n else:\n idx = 0\n \n j = self.search(self.seats, idx)\n self.seats.insert(j+1, idx)\n \n return idx\n\n def leave(self, p: int) -> None:\n j = self.search(self.seats, p)\n self.seats.pop(j+1)\n \n # find the largest index < target in a sorted array\n def search(self, nums, target):\n if len(nums) == 0:\n return -1\n \n start, end = 0, len(nums)-1\n while start+1 < end:\n mid = start+(end-start)//2\n if nums[mid] < target:\n start = mid\n else:\n end = mid\n if nums[end] < target:\n return end\n if nums[start] < target:\n return start\n return -1\n \n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(N)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
1
0
[]
0
select-cells-in-grid-with-maximum-score
Focus on uniqueness in values first, then uniqueness in rows | Full explanation
focus-on-uniqueness-in-values-first-then-vbva
So this one is a tricky one. Brute force suggests to try all possibilities on rows and maintain uniqueness through sets, which results in tle.\n\nThe optimisati
virujthakur01
NORMAL
2024-09-01T04:05:09.950549+00:00
2024-09-01T04:08:42.206673+00:00
7,900
false
So this one is a tricky one. Brute force suggests to try all possibilities on rows and maintain uniqueness through sets, which results in tle.\n\nThe optimisation lies in the fact that we can store values in increasing/ decreasing order and then only select values greater than / less than the previous value. This ensures uniqueness.\n\nAs for row uniqueness, we can store which row has been taken in previous states through a mask variable. The total possible values of this variable is 2^ (No. of rows) which fits well in the time constraints.\n```\nclass Solution {\npublic:\n int recur(vector<vector<int>>& values, int idx, int mask_row, map<pair<int,int>, int>& dp)\n {\n int n= values.size();\n if(idx == n)\n return 0;\n \n if(dp.find({idx, mask_row})!= dp.end())\n return dp[{idx, mask_row}];\n \n int ans = 0;\n int row = values[idx][1];\n if((1<<row) & mask_row)\n ans += recur(values, idx+1, mask_row, dp);\n else\n {\n int j = idx;\n while (j< n and values[idx][0]== values[j][0])\n j++;\n \n int ans1= values[idx][0]+ recur(values, j, mask_row | (1<<row), dp);\n int ans2 = recur(values, idx+1, mask_row, dp);\n \n ans= max(ans1, ans2);\n }\n \n return dp[{idx, mask_row}]= ans;\n \n }\n int maxScore(vector<vector<int>>& grid) {\n int n= grid.size();\n int m= grid[0].size();\n vector<vector<int>> values;\n for(int i=0; i<n; i++)\n {\n for(int j=0; j<m; j++)\n {\n values.push_back({grid[i][j], i, j});\n }\n }\n \n \n sort(values.begin(), values.end(), greater<vector<int>>());\n map<pair<int,int>, int> dp;\n \n return recur(values, 0, 0, dp);\n }\n};\n```\n\nTC: O(M*N* 2^M) SC: O(M*N*2^(M))
70
2
['Dynamic Programming', 'Bitmask', 'C++']
20
select-cells-in-grid-with-maximum-score
Python | Java DFS in descending orders with detailed explanation.
python-java-dfs-in-descending-orders-wit-m5c1
\n# Intuition\nThere are two constraints to consider:\n- Each row can only contain one value.\n- All values must be unique.\n\nThese constraints imply that, whe
leet_go
NORMAL
2024-09-01T04:03:57.424141+00:00
2024-09-01T05:43:59.655607+00:00
3,047
false
\n# Intuition\nThere are two constraints to consider:\n- Each row can only contain one value.\n- All values must be unique.\n\nThese constraints imply that, when aiming to maximize the values in all cells, the largest value in the grid must be included. This is because, for any set of values chosen from the grid that excludes the maximum value, substituting one selected value by the maximum value in the same row will not violate the constraints and will result in a higher score.\n\nGiven this, it makes sense to adopt a strategy that selects values from the grid in descending order. Thus, a DFS approach comes to mind.\n\n\n# Approach\nThere are 3 steps to follow:\n\n- Create a mapping from each unique value in the grid to the indexes of the rows containing that value.\n- Execute a DFS algorithm for each unique value in descending order.\n- For each value, iterate through the list of row indexes and determine the maximum score. During this process, keep track of rows that have already been selected, and ensure to skip these rows to adhere to the restriction of having only one value per row.\n\n# Code\n```python []\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n rows = len(grid)\n cols = len(grid[0])\n # flatten all the values in the grid and deduplicate\n value_set = set([grid[r][c] for r in range(rows) for c in range(cols)])\n \n # sort values from in descending order\n value_list = sorted(list(value_set))[::-1]\n\n # create a map mapping from each value to the list of row indexes with these values\n val_to_rows = defaultdict(list)\n for value in value_list:\n val_to_rows[value] = [r for r in range(rows) if value in grid[r]]\n\n # Run dfs on rows with cell values in descending order.\n def dfs(row_set, remaining_values, score):\n if not remaining_values:\n return score\n\n value = remaining_values[0]\n remaining_values = remaining_values[1:]\n\n score_list = []\n\n for row in val_to_rows[value]:\n if row not in row_set:\n score_list.append(dfs(row_set | {row}, remaining_values, score + value))\n if not score_list:\n score_list.append(dfs(row_set, remaining_values, score))\n return max(score_list)\n\n return dfs(set(), value_list, 0)\n \n```\n\n\n```java []\nclass Solution {\n private int dfs(\n final Set<Integer> rows, \n final List<Integer> sortedVals,\n final Map<Integer, Set<Integer>> valToIndex,\n final int score,\n int depth\n ) {\n if (++depth == sortedVals.size()) {\n return score;\n }\n final int value = sortedVals.get(depth);\n \n final List<Integer> scores = new ArrayList<>();\n final int nxt_depth = depth;\n valToIndex.get(value)\n .stream()\n .filter(row -> !rows.contains(row))\n .forEach(row -> {\n final Set<Integer> updatedRows = new HashSet<>(rows);\n updatedRows.add(row);\n scores.add(dfs(updatedRows, sortedVals, valToIndex, score + value, nxt_depth));\n });\n if (scores.isEmpty()) {\n return dfs(rows, sortedVals, valToIndex, score, depth);\n } else {\n return Collections.max(scores);\n }\n }\n\n public int maxScore(List<List<Integer>> grid) {\n final Set<Integer> vals = grid.stream().flatMap(List::stream).collect(Collectors.toSet());\n final Map<Integer, Set<Integer>> valToIndex = new HashMap<>();\n vals.forEach(val -> valToIndex.put(val, new HashSet<>()));\n IntStream.range(0, grid.size()).forEach(row -> {\n vals.forEach(val -> {\n if (grid.get(row).contains(val)) {\n valToIndex.get(val).add(row);\n }\n });\n });\n final List<Integer> sortedVals = new ArrayList<>(vals);\n Collections.sort(sortedVals, Collections.reverseOrder());\n return dfs(new HashSet<>(), sortedVals, valToIndex, 0, -1);\n }\n}\n```
28
1
['Depth-First Search', 'Java', 'Python3']
10
select-cells-in-grid-with-maximum-score
Min-Cost Max-Flow Solution (With Diagrams)
min-cost-max-flow-solution-with-diagrams-cz81
Intuition\n Matching problems can often be modeled into a flow network in which the min-cost max-flow represents the optimal solution.\n The key challenge here
whynot4
NORMAL
2024-09-01T05:06:45.634463+00:00
2024-09-08T06:07:28.978478+00:00
877
false
# Intuition\n* Matching problems can often be modeled into a flow network in which the min-cost max-flow represents the optimal solution.\n* The key challenge here is figuring out how to transform the input grid into such a network that respects the contstraints of the problem (i.e. uniqueness and the "1 selection per row" limit).\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nConsider example 1: \n![image.png](https://assets.leetcode.com/users/images/98fa22b5-2c2a-4dd2-9f9b-33f70e302b68_1725166484.0684252.png)\n\nThis example can be turned into the following flow network. \n\nNote:\n* The edges are labeled with cost/capacity. e.g. A "0/1" edge denotes to a cost of zero & capacity one edge.\n* We connect the source to each row, only giving it a capacity of 1. This is to enforce that each row only gets picked once.\n* We connect each row with the values found in that row, again, using a capacity of 1 to ensure we only pick once per row. \n* We then connect each unique value (the second column of nodes) to the sink with a capacity of 1 to ensure uniqueness. \n* Most of the costs are zero. The only costs occur when a row "selects" a specific value. The cost is `100 - x`.\n \n![image.png](https://assets.leetcode.com/users/images/72a6d6fc-470d-4db1-98a1-3ee7839c8141_1725166434.7422009.png)\n\nThe maximum flow of this flow \n\n\n\n is `3`. The minimum cost to achieve that flow is `96 + 97 + 99 = 292` (see the red edges below). \n\nIn order to convert this back into the max value that we\'re trying optimize for, we need to take `100 * max_flow` and subtract `292` (`100*3 - 292 = 8`). Hence, `8` is the maximum valid answer for example 1. \n\n![image.png](https://assets.leetcode.com/users/images/05c3c3dc-40ac-4f4c-88b3-2aa31de3ceea_1725167375.4760976.png)\n\n\nYou can solve the min-cost max-flow problem using a variety of algorithms, such as the Ford-Fulkerson, Edmonds-Karp, or the Dijkstra-based Min-Cost Max-Flow algorithm I\'ve used below. The exact specifics of how such algorithms work are out of scope for this tutorial. \n\n\n**Bonus**: If you\'re curious, here\'s how the flow network would look like for example 2.\n![image.png](https://assets.leetcode.com/users/images/b9327bf4-a002-4f0b-b447-6cd65f683c9e_1725456264.1705003.png)\n\n\n![image.png](https://assets.leetcode.com/users/images/14c5886d-852b-4081-bff6-471d527c2e70_1725456313.6583967.png)\n\nNote that node \'8\' cannot take in more than one flow, hence row0 gets rerouted to node \'7\'. Here the max-flow is `2` and the min-cost is `92 + 93 = 185`\n\n# Complexity\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Time complexity: `O( max_flow * n * m * log(n + m) )`\nNote: n & m are the dimensions of the grid, and the max_flow will be less than or equal to n. Hence the overall algorithm runs in: `O( n^2 * m * log(n + m) )`\n\n- Space complexity: `O(n+m)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\nStructure:\n* Build flow network, with inverted cost values per cell (`100-x`)\n* Invoke the min-cost max-flow helper function\n* Return: `100 * max_flow - min_cost`\n\n```java []\nclass Solution {\n public int maxScore(List<List<Integer>> grid) {\n int n = grid.size(); // first column of nodes\n int m = 100; // second column of nodes\n int size = n + m + 2;\n var f = new DijkstraMinCostMaxFlow(size);\n\n for (int i = 1; i <= n; i++) { // connect the source to first column\n f.addEdge(0, i, 1, 0);\n }\n\n for (int i = 0; i < n; i++) { // interconnections between columns\n for (int j : grid.get(i)) {\n f.addEdge(i + 1, j + n, 1, 100 - j);\n }\n }\n\n for (int i = 1; i <= 100; i++) { // connect the second column to the sink\n f.addEdge(i + n, size - 1, 1, 0);\n }\n\n int[] mf = f.minCostMaxFlow(0, size - 1);\n return 100 * mf[0] - mf[1]; // needed to convert back, sum(100-x) --> sum(x)\n }\n}\n\npublic class DijkstraMinCostMaxFlow {\n\n static class Edge {\n int from, to, capacity, cost, flow;\n Edge reverse;\n\n public Edge(int from, int to, int capacity, int cost) {\n this.from = from;\n this.to = to;\n this.capacity = capacity;\n this.cost = cost;\n this.flow = 0;\n }\n }\n\n private int n;\n private List<Edge>[] graph;\n private int[] potential;\n\n public DijkstraMinCostMaxFlow(int n) {\n this.n = n;\n graph = new ArrayList[n];\n for (int i = 0; i < n; i++) {\n graph[i] = new ArrayList<>();\n }\n potential = new int[n];\n }\n\n public void addEdge(int from, int to, int capacity, int cost) {\n Edge forward = new Edge(from, to, capacity, cost);\n Edge reverse = new Edge(to, from, 0, -cost);\n forward.reverse = reverse;\n reverse.reverse = forward;\n graph[from].add(forward);\n graph[to].add(reverse);\n }\n\n private boolean dijkstra(int source, int sink, int[] dist, Edge[] parentEdge) {\n Arrays.fill(dist, Integer.MAX_VALUE);\n dist[source] = 0;\n PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));\n pq.add(new int[] { source, 0 });\n\n while (!pq.isEmpty()) {\n int[] u = pq.poll();\n int current = u[0];\n int currentDist = u[1];\n\n if (currentDist > dist[current])\n continue;\n\n for (Edge edge : graph[current]) {\n int next = edge.to;\n int newDist = dist[current] + edge.cost + potential[current] - potential[next];\n\n if (edge.flow < edge.capacity && dist[next] > newDist) {\n dist[next] = newDist;\n parentEdge[next] = edge;\n pq.add(new int[] { next, dist[next] });\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n if (dist[i] < Integer.MAX_VALUE) {\n potential[i] += dist[i];\n }\n }\n\n return dist[sink] != Integer.MAX_VALUE;\n }\n\n public int[] minCostMaxFlow(int source, int sink) {\n int maxFlow = 0, minCost = 0;\n int[] dist = new int[n];\n Edge[] parentEdge = new Edge[n];\n\n Arrays.fill(potential, 0);\n\n while (dijkstra(source, sink, dist, parentEdge)) {\n int flow = Integer.MAX_VALUE;\n for (int v = sink; v != source; v = parentEdge[v].from) {\n flow = Math.min(flow, parentEdge[v].capacity - parentEdge[v].flow);\n }\n\n for (int v = sink; v != source; v = parentEdge[v].from) {\n parentEdge[v].flow += flow;\n parentEdge[v].reverse.flow -= flow;\n minCost += flow * parentEdge[v].cost;\n }\n\n maxFlow += flow;\n }\n\n return new int[] { maxFlow, minCost };\n }\n}\n```
26
0
['Graph', 'Java']
6
select-cells-in-grid-with-maximum-score
Easy Video Solution 🔥 || How to 🤔 in Interview || Focus on uniqueness || Memo + Bitmasking 🥲
easy-video-solution-how-to-in-interview-mpk5v
If you like the solution Please Upvote and subscribe to my youtube channel\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nTry to
ayushnemmaniwar12
NORMAL
2024-09-01T05:08:20.233935+00:00
2024-09-01T07:25:30.961610+00:00
2,462
false
***If you like the solution Please Upvote and subscribe to my youtube channel***\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry to think in terms of values, Ascending or Desending\n\n\n\n***Easy Video Explanation with Proofs***\n\nhttps://youtu.be/lvUte5NcTJ4\n \n\n# Code\n\n\n```C++ []\nclass Solution {\npublic:\n int dp[2001][101];\n int solve(int i,int n,vector<int>&t,map<int,vector<int>>&mp,int mask) {\n if(i==n)\n return 0;\n if(dp[mask][i]!=-1)\n return dp[mask][i];\n int ans=0;\n for(auto j:mp[t[i]]) {\n if((mask&(1<<j))==0) {\n ans=max(ans,t[i]+solve(i+1,n,t,mp,(mask|(1<<j))));\n }\n }\n ans=max(ans,solve(i+1,n,t,mp,mask));\n return dp[mask][i]=ans;\n }\n int maxScore(vector<vector<int>>& v) {\n int n = v.size();\n int m = v[0].size();\n set<int>s;\n for(int i=0;i<n;i++) {\n for(int j=0;j<m;j++) {\n s.insert(v[i][j]);\n }\n }\n vector<int>t;\n for(auto i:s)\n t.push_back(i);\n sort(t.begin(),t.begin(),greater<int>());\n map<int,vector<int>>mp;\n for(int i=0;i<n;i++) {\n for(int j=0;j<m;j++) {\n mp[v[i][j]].push_back(i);\n }\n }\n memset(dp,-1,sizeof(dp));\n return solve(0,t.size(),t,mp,0);\n }\n};\n```\n```python []\nfrom typing import List\nfrom collections import defaultdict\nimport functools\n\nclass Solution:\n def __init__(self):\n self.dp = [[-1] * 101 for _ in range(2001)]\n\n @functools.lru_cache(None)\n def solve(self, i: int, n: int, t: tuple, mp: dict, mask: int) -> int:\n if i == n:\n return 0\n if self.dp[mask][i] != -1:\n return self.dp[mask][i]\n\n ans = 0\n for j in mp[t[i]]:\n if not (mask & (1 << j)):\n ans = max(ans, t[i] + self.solve(i + 1, n, t, mp, mask | (1 << j)))\n ans = max(ans, self.solve(i + 1, n, t, mp, mask))\n self.dp[mask][i] = ans\n return ans\n\n def maxScore(self, v: List[List[int]]) -> int:\n n = len(v)\n m = len(v[0])\n s = set()\n\n for i in range(n):\n for j in range(m):\n s.add(v[i][j])\n\n t = sorted(s, reverse=True)\n\n mp = defaultdict(list)\n for i in range(n):\n for j in range(m):\n mp[v[i][j]].append(i)\n\n self.dp = [[-1] * 101 for _ in range(2001)]\n return self.solve(0, len(t), tuple(t), mp, 0)\n\n```\n```Java []\nimport java.util.*;\n\nclass Solution {\n int[][] dp = new int[2001][101];\n\n int solve(int i, int n, List<Integer> t, Map<Integer, List<Integer>> mp, int mask) {\n if (i == n) return 0;\n if (dp[mask][i] != -1) return dp[mask][i];\n\n int ans = 0;\n for (int j : mp.get(t.get(i))) {\n if ((mask & (1 << j)) == 0) {\n ans = Math.max(ans, t.get(i) + solve(i + 1, n, t, mp, (mask | (1 << j))));\n }\n }\n ans = Math.max(ans, solve(i + 1, n, t, mp, mask));\n return dp[mask][i] = ans;\n }\n\n public int maxScore(List<List<Integer>> v) {\n int n = v.size();\n int m = v.get(0).size();\n Set<Integer> s = new HashSet<>();\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n s.add(v.get(i).get(j));\n }\n }\n\n List<Integer> t = new ArrayList<>(s);\n Collections.sort(t, Collections.reverseOrder());\n\n Map<Integer, List<Integer>> mp = new HashMap<>();\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n mp.computeIfAbsent(v.get(i).get(j), k -> new ArrayList<>()).add(i);\n }\n }\n\n for (int[] row : dp) {\n Arrays.fill(row, -1);\n }\n\n return solve(0, t.size(), t, mp, 0);\n }\n}\n\n\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(2^10*1000*10)\n \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n# ***If you like the solution Please Upvote and subscribe to my youtube channel***\n***It Motivates me to record more videos***\n\n*Thank you* \uD83D\uDE00
25
1
['Memoization', 'Bitmask', 'C++', 'Java', 'Python3']
5
select-cells-in-grid-with-maximum-score
[Python] Hungarian, 5 lines
python-hungarian-5-lines-by-lee215-1a4d
Hungarian problem.\n\nTime O(100^3)\nSpace O(100^2)\n\n\n\nPython\npy\n def maxScore(self, grid: List[List[int]]) -> int:\n A = numpy.array([[0] * 101
lee215
NORMAL
2024-09-01T04:45:43.717460+00:00
2024-09-01T09:42:53.851742+00:00
1,565
false
Hungarian problem.\n\nTime `O(100^3)`\nSpace `O(100^2)`\n<br>\n\n\n**Python**\n```py\n def maxScore(self, grid: List[List[int]]) -> int:\n A = numpy.array([[0] * 101 for r in grid])\n for i,r in enumerate(grid):\n for a in r:\n A[i][a] = -a\n return int(-A[scipy.optimize.linear_sum_assignment(A)].sum())\n```\n
18
2
[]
4
select-cells-in-grid-with-maximum-score
DP - Bitmask without sorting (Simple rundown from 100) || Well explained || Easy
dp-bitmask-without-sorting-simple-rundow-tji2
Intuition\n Describe your first thoughts on how to solve this problem. \nNoticing the constrains, my first thoughts were backtracking. Then I observed that not
rubixxzone218
NORMAL
2024-09-01T12:23:53.191679+00:00
2024-09-05T08:04:27.593748+00:00
566
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> \nNoticing the constrains, my first thoughts were backtracking. Then I observed that not only the size of the grid has a small cap but also the value at every cell is also capped at 100. This naturally steered me to a bitmask dp approach.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHash the rows `num` (value in a cell) in an unordered map. Later, we will iterate over these rows by marking each row as visited in the bitmask and call `func` recursively.\n\n`dp[i][j]` represents the total sum to number `i` with mask `j`. `i` ranges from 0 to 100 based on the question. `j` represents the row masked by 1 << row. Calculate the maximum by iterating through all the combinations of a number and the rows it is present in.\n\n## Breaking Condition:\nWe break when `num == 0` i.e. all numbers in the cell have been considered.\n\n**Important caution**: </br>Pass the map and grid by reference, else you will get a TLE. \nReason - When you pass by value, a copy of the variable is made which takes $O(n^2)$ time for each recursive call. Hence, the TC would rather become $O(n^3 * 2^n * 101)$ which would result in a TLE\n\n# Complexity\n- Time complexity: $O(n * 2^n * 101)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(101*2^n)$\n# Code\n```cpp []\nclass Solution {\nprivate:\n int dp[101][1025]; \n int func(vector<vector<int>>& grid, int bitmask, int num, unordered_map<int, vector<int>>& mp) {\n if(num == 0)\n return 0;\n if(dp[num][bitmask] != -1)\n return dp[num][bitmask];\n\n // If num does not exist in the grid\n int res = func(grid, bitmask, num-1, mp);\n\n for(auto row: mp[num]) {\n // Skip if row has already been visited\n if(bitmask >> row & 1)\n continue;\n res = max(res, num + func(grid, (bitmask | (1<<row)), num-1, mp));\n }\n return dp[num][bitmask] = res;\n }\n\npublic:\n int maxScore(vector<vector<int>>& grid) {\n const int m = grid.size();\n const int n = grid[0].size();\n unordered_map<int, vector<int>> mp;\n memset(dp, -1, sizeof(dp));\n for(int i=0; i<m; ++i) {\n for(int j=0; j<n; ++j) {\n mp[grid[i][j]].push_back(i);\n }\n }\n return func(grid, 0, 100, mp);\n }\n};\n```\n\nPlease upvote if you found this helpful!\n\n![image.png](https://assets.leetcode.com/users/images/23c9f539-9f9a-414a-ba52-ce5c51140962_1725193419.3911104.png)\n\n
17
0
['Dynamic Programming', 'Bitmask', 'C++']
2
select-cells-in-grid-with-maximum-score
Bitmask DP mask of used rows
bitmask-dp-mask-of-used-rows-by-theabbie-xtq6
\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n n = len(grid)\n vals = {}\n for i in range(n):\n for
theabbie
NORMAL
2024-09-01T04:00:36.902058+00:00
2024-09-01T04:00:36.902091+00:00
2,105
false
```\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n n = len(grid)\n vals = {}\n for i in range(n):\n for h in grid[i]:\n if h not in vals:\n vals[h] = []\n vals[h].append(i)\n vals = list(vals.items())\n @lru_cache(maxsize = None)\n def maxval(i, mask):\n if i >= len(vals):\n return 0\n res = maxval(i + 1, mask)\n for j in vals[i][1]:\n if not mask & (1 << j):\n res = max(res, vals[i][0] + maxval(i + 1, mask | (1 << j)))\n return res\n return maxval(0, 0)\n```
17
1
['Python']
6
select-cells-in-grid-with-maximum-score
solution explained [recursion -> bitmask DP -> greedy + bitmasking]
solution-explained-recursion-bitmask-dp-t3ggk
Recursion \n\n#### approach \n\nWe will start by picking each element one by one from every row to see what is the maximum score we can get from all the combina
niti_n_n_itin
NORMAL
2024-09-01T06:01:41.705987+00:00
2024-09-01T07:26:36.056448+00:00
1,055
false
## Recursion \n\n#### approach \n\nWe will start by picking each element one by one from every row to see what is the maximum score we can get from all the combinations.\n\nNote: `We can even decide not to choose any number from a row.`\n\nfor ex : \n[5 , 5]\n[5, 5]\n[10, 1]\n\nIn the above case, we will not pick any number from the second row (otherwise, it will violate the second condition).\n\n```\nclass Solution {\npublic:\n int max_score ( vector<vector<int>> & ar, int i, unordered_map<int, int> &mp){\n int n = ar.size();\n if(i == n)\n return 0;\n int res = 0;\n for(auto x : ar[i])\n if(!mp[x]){\n\t\t\t // set mp[x] =1 , to not pick this number again for other rows.\n mp[x] = 1;\n res = max(res, max_score(ar, i + 1, mp) + x);\n\t\t\t\t// set mp[x] =0 , to make it pickable again.\n mp[x] = 0;\n }\n\t\t// Skip picking number from this row\n res = max(res, max_score(ar, i + 1, mp));\n return res;\n \n }\n int maxScore(vector<vector<int>>& ar) {\n\t // map to keep track of which number i have included \n unordered_map<int, int> mp;\n return max_score(ar, 0, mp);\n }\n};\n```\n\nTime complexity : `O ( N ^ N) )` , where N = size of the grid \nSpace complexity : `O ( N * N ) ` , where N = size of the grid , Why? Because this is the maximum number we can have which we will be storing in the map.\n\n\n## Adding greedy optimisation : \n\nNow, here are some observations we can use to optimize our above approach a little bit.\n\n1. `we can even decide to not choose any number from the row` -> We will only do this when we can\'t pick any element from that row; otherwise, it\'s always better to pick some number as they are greater than 0.\n2. It\'s better to always pick the largest number.\n\nBut the problem here is that it could be repeating in some other row, and picking it now may result in a lesser max score.\n\nfor ex. \n[\n[8,7,6],\n[8,3,2]\n]\n\nIt\'s a better choice to not pick 8 in the first row, as we then won\'t be able to pick 8 again in the second row.\n\nBUT what if the largest number is not repeating in any other row? Then it always makes sense to pick it.\n\n```\nclass Solution {\npublic:\n int max_score ( vector<vector<int>> & ar, int i, unordered_map<int, int> &mp, vector<unordered_map<int, int> > &mp2){\n int n = ar.size();\n if(i == n)\n return 0;\n int res = 0;\n bool cant_pick_number_from_row = true;\n for(auto x : ar[i]){\n int definately_pick = 0;\n // checking x occurrence in other rows.\n for (int j = 0 ; j < n; j ++){\n // leave the current row.\n if(i != j){\n definately_pick += mp2[j][x];\n }\n }\n \n if(!mp[x]){\n\t\t\t // set mp[x] =1 , to not pick this number again for other rows.\n mp[x] = 1;\n cant_pick_number_from_row = false;\n res = max(res, max_score(ar, i + 1, mp, mp2) + x);\n\t\t\t\t// set mp[x] =0 , to make it pickable again.\n mp[x] = 0;\n if(!definately_pick){\n // if it\'s not occurring in other rows , then there is no need to check for lesser number as they we always give less total score. \n break;\n }\n \n }\n }\n\t\t// Skip picking number from this row, only if we can not pick any number from this row.\n if(cant_pick_number_from_row)\n res = max(res, max_score(ar, i + 1, mp, mp2));\n return res;\n \n }\n int maxScore(vector<vector<int>>& ar) {\n\t // map to keep track of which number i have included \n unordered_map<int, int> mp;\n \n // Map to keep track of the number in every row, we will use to to check if we can\n // "DEFINITELY" pick the largest possible number\n vector<unordered_map<int, int> > mp2(ar.size());\n \n for(int i = 0; i < ar.size(); i++){\n // Sorting the array in descending order so that i can choice large number first. \n sort(ar[i].begin(), ar[i].end(), greater<>() );\n for(int x : ar[i])\n mp2[i][x]++;\n }\n \n \n return max_score(ar, 0, mp, mp2);\n }\n};\n```\n\nTime complexity : although we improve it a little but i think it\'s complexity in the wrost case is still O(N ^N ).\nspace complexity : O ( N ^ N )\n\nNOTE : This will still give TLE. So why do this? Because in DP bitmasking, I was using a string instead of an integer, which was also giving TLE, but after adding the above optimizations, it got passed.\n\n\n\n\n\n## DP with bitmask : \n\n`what is bitmask DP`\n\nIn normal DP, our result memorization depends on some value. For example, how many steps until we reach the top ( [problem link](https://leetcode.com/problems/climbing-stairs/) ), which house we are robbing, and whether we robbed the previous house or not ( [problem link](https://leetcode.com/problems/house-robber-ii/) ). \n\nBut in some questions, our memorization depends on some combinations. Like in this question, to decide whether we have computed the answer already, we need to know at what row we are (`i`) and what were the numbers we have chosen previously (`mp`). If we can somehow use the store and return the result based on i & mp, then we will reduce our repetitive computations. \n\n\nTo store combinations, we use bitmasking. (You don\'t need to know more; I\'m sure once you go through the code, you will understand it. Plus, I can\'t tell you more about it in this article. Just do 2-3 questions on bitmask DP to get more familiar with it.)\n\n[DP question list](https://leetcode.com/discuss/general-discussion/1000929/solved-all-dynamic-programming-dp-problems-in-7-months)\n\nNow to store the number I have picked, I will change mp from unordered_map to string, so that I can easily store it in `unordered_map<int, unordered_map<string, int>> dp;`\n\n```\nclass Solution {\npublic:\n int max_score ( vector<vector<int>> & ar, int i, string & mp, vector<unordered_map<int, int> > & mp2, unordered_map<int, unordered_map<string, int>> &dp )\n {\n int n = ar.size();\n if(i == n)\n return 0;\n if(dp[i][mp])\n // why re-compute when we already know the answer. \n return dp[i][mp];\n\n int res = 0;\n bool cant_pick_number_from_row = true;\n for(auto x : ar[i]){\n int definately_pick = 0;\n // checking x occurrence in other rows.\n for (int j = 0 ; j < n; j ++){\n // leave the current row.\n if(i != j){\n definately_pick += mp2[j][x];\n }\n }\n \n if(mp[x] == \'0\'){\n\t\t\t // set mp[x] =1 , to not pick this number again for other rows.\n mp[x] = \'1\';\n cant_pick_number_from_row = false;\n res = max(res, max_score(ar, i + 1, mp, mp2, dp) + x);\n\t\t\t\t// set mp[x] =0 , to make it pickable again.\n mp[x] = \'0\';\n if(!definately_pick){\n // if it\'s not occurring in other rows , then there is no need to check for lesser number as they we always give less total score. \n break;\n }\n \n }\n }\n\t\t// Skip picking number from this row, only if we can not pick any number from this row.\n if(cant_pick_number_from_row)\n res = max(res, max_score(ar, i + 1, mp, mp2, dp));\n \n // store to result to avoid repeatative computation.\n return dp[i][mp] = res;\n \n }\n int maxScore(vector<vector<int>>& ar) {\n\t // map to keep track of which number i have included \n int MAX_ELEMENT_LIMIT = 100;\n string mp(MAX_ELEMENT_LIMIT + 1, \'0\');\n \n // Map to keep track of the number in every row, we will use to to check if we can\n // "DEFINITELY" pick the largest possible number\n vector<unordered_map<int, int> > mp2(ar.size());\n \n for(int i = 0; i < ar.size(); i++){\n // Sorting the array in descending order so that i can choice large number first. \n sort(ar[i].begin(), ar[i].end(), greater<>() );\n for(int x : ar[i])\n mp2[i][x]++;\n }\n \n unordered_map<int, unordered_map<string, int>> dp;\n \n \n return max_score(ar, 0, mp, mp2, dp);\n }\n};\n```\n\n\nTime complexity : i think O ( N * S), where N = no of grids, S = number range.\nSpace : O( N * S ) \n\nplease correct me if i\'m wrong ^. \n\n\nmy journey : \n\nI first coded a recursive approach, then bitmask DP, but it was still giving TLE (maybe because I used a string instead of an integer for bitmask, but I was not sure how to do that). So, I added a greedy optimization, and it got passed.\n\nPlease comment if you have any doubts/questions or want to correct something.\n\n\n
14
0
['Greedy', 'Recursion', 'C', 'C++']
5
select-cells-in-grid-with-maximum-score
DP APPROACH || C++
dp-approach-c-by-_shivam_kmr-jf3b
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
_shivam_kmr_
NORMAL
2024-09-01T04:10:31.953260+00:00
2024-09-01T04:10:31.953297+00:00
2,658
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int dp[105][1030];\n int solve(int idx,int mask,map<int,vector<int> >&arr){\n if(idx==0){\n return 0;\n }\n \n if(dp[idx][mask] != -1){\n return dp[idx][mask];\n }\n \n int res=solve(idx-1,mask,arr);\n \n for(auto i:arr[idx]){\n if((mask & (1<<i))==0){\n res=max(res,idx+solve(idx-1,mask|(1<<i),arr));\n }\n }\n \n return dp[idx][mask]=res;\n }\n int maxScore(vector<vector<int>>& grid) {\n memset(dp,-1,sizeof(dp));\n map<int,vector<int> > arr;\n int n=grid.size(),m=grid[0].size();\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n arr[grid[i][j]].push_back(i);\n }\n }\n \n return solve(100,0,arr);\n }\n};\n```
13
0
['Dynamic Programming', 'Memoization', 'C++']
4
select-cells-in-grid-with-maximum-score
Python3 || recursion, cache, masks || T/S: 97% / 59%
python3-recursion-cache-masks-ts-97-59-b-rbuw
Here\'s the intuiton:\n\n1. We manually map the grid to d, a dictionary that maps each value in the grid to a bitmask, which indicates which rows contain that v
Spaulding_
NORMAL
2024-09-02T23:25:24.320680+00:00
2024-09-02T23:25:36.861716+00:00
250
false
Here\'s the intuiton:\n\n1. We manually map the grid to `d`, a dictionary that maps each value in the grid to a bitmask, which indicates which rows contain that value. \n\n1. We use recursion with caching to evaluate possible selections of values from the grid, moving from greater values to lesser values. \n\n1. We employ bitmasks to check which rows are available and to mark them as used when selecting a value in that row. We iterate through each value\'s bitmask and compare it with `cur`, the current selection\'s mask.\n2. Having the dictionary allows us to pass only the row index and a dictionary key (an integer as well) to the recursive function, so we can avoid passing big data structures and thereby using less space and time to recurse. Also, caching helps a little with those concerns as well.\n\n```python3 []\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n\n @lru_cache(None)\n def dp(i: int, mask: int)-> int:\n\n if i == len(values): return 0\n cur, value = mask, values[i]\n \n bits, j, res = d[value], 0, 0\n \n for _ in range(bits.bit_length()):\n\n if (bits%2,cur%2) == (1, 0):\n res = max(res, value + dp(i + 1, mask | (1 << j)))\n j, bits, cur = j + 1, bits//2, cur//2\n \n if not res: res = dp(i + 1, mask)\n\n return res\n \n\n d = defaultdict(int)\n\n for idx, row in enumerate(grid):\n for num in row: d[num]|= (1<<idx)\n\n values = sorted(d, reverse = True)\n return dp(0, 0)\n```\n[https://leetcode.com/problems/select-cells-in-grid-with-maximum-score/submissions/1377067207/](https://leetcode.com/problems/select-cells-in-grid-with-maximum-score/submissions/1377067207/)\n\nI could be wrong (and it\'s even more likely than usual with this problem), but I think that time complexity is *O*(*NK* * 2^*N*) and space complexity is O*(*K* * 2^*N*), in which *N* ~ `len(grid)` and *K* ~ `number of unique inters in.\n\n\n
9
0
['Python3']
0
select-cells-in-grid-with-maximum-score
Video Explanation (Optimising brute force solution step-by-step)
video-explanation-optimising-brute-force-6blz
Explanation\n\nClick here for the video\n\n# Code\ncpp []\nint dp[101][1024];\n\nclass Solution {\n \n int rows, cols;\n vector<vector<int>> grid;\n
codingmohan
NORMAL
2024-09-01T06:23:17.122347+00:00
2024-09-01T06:23:17.122382+00:00
271
false
# Explanation\n\n[Click here for the video](https://youtu.be/xDiSlVmMFTk)\n\n# Code\n```cpp []\nint dp[101][1024];\n\nclass Solution {\n \n int rows, cols;\n vector<vector<int>> grid;\n \n int Score (int val, int row_mask) {\n if (val > 100) return 0;\n \n int &ans = dp[val][row_mask];\n if (ans != -1) return ans;\n \n ans = Score (val+1, row_mask);\n for (int r = 0; r < rows; r ++) {\n if (row_mask & (1 << r)) continue;\n \n for (int c = 0; c < cols; c ++) {\n if (grid[r][c] != val) continue;\n \n ans = max (ans, val + Score (val+1, row_mask|(1<<r)));\n }\n }\n return ans;\n }\n \npublic:\n int maxScore(vector<vector<int>>& _grid) {\n memset(dp, -1, sizeof(dp));\n \n grid = _grid;\n rows = grid.size(), cols = grid[0].size();\n \n return Score (1, 0);\n }\n};\n```
8
1
['C++']
0
select-cells-in-grid-with-maximum-score
Hungarian Algorithm
hungarian-algorithm-by-iyerke-88eo
Intuition\nThe problem of selecting unique values from a 2D matrix such that no two selected cells are in the same row can be modeled as an assignment problem.
iyerke
NORMAL
2024-09-01T04:01:22.700172+00:00
2024-09-01T04:22:43.198006+00:00
972
false
### Intuition\nThe problem of selecting unique values from a 2D matrix such that no two selected cells are in the same row can be modeled as an [assignment problem](https://en.wikipedia.org/wiki/Assignment_problem). This is a classical optimization problem that can be effectively solved using graph theory. Specifically, the problem can be framed as finding a maximum-weight matching in a bipartite graph, which is equivalent to minimizing a cost function in the assignment problem.\n\n### Approach\nTo tackle this problem, we will:\n1. Construct a cost matrix where each entry represents the negative of the value to be maximized. This transformation allows us to use algorithms designed to minimize costs.\n2. Set up the cost matrix such that:\n - If a value `j` is present in row `i`, its cost is `-j` (since we aim to maximize `j`, we use its negative as the cost to be minimized).\n - If a value `j` is not present in row `i`, its cost is set to infinity (to signify that this value cannot be selected for this row).\n3. Incorporate dummy values with zero cost to handle cases where some rows might not have any eligible values, allowing the solution to include rows without selected values if necessary.\n4. Use the [Hungarian Algorithm](https://en.wikipedia.org/wiki/Hungarian_algorithm), implemented through `scipy.optimize.linear_sum_assignment`, to find the optimal assignment that minimizes the total cost.\n\n### Complexity\n- **Time Complexity**: O(n^3)\n- **Space Complexity**: O(n^2)\n### Code\n\n```python\nfrom scipy.optimize import linear_sum_assignment\n\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n # Convert each row of the grid into a set for efficient membership checking\n grid_set = list(map(set, grid))\n \n m, n = len(grid), len(grid[0])\n \n # Initialize cost matrix with large values (representing infinity)\n cost_matrix = [111 * [0] for _ in range(m)] # 101, ..., 110 are dummy values\n \n for i in range(m):\n for j in range(111):\n if j > 100:\n continue # Skip dummy values > 100\n if j in grid_set[i]:\n cost_matrix[i][j] = -j # Cost is negative of the value to maximize\n else:\n cost_matrix[i][j] = float(\'inf\') # Cannot assign this value to the row\n \n # Solve the assignment problem using the Hungarian Algorithm\n row_ind, col_ind = linear_sum_assignment(cost_matrix)\n \n # Return the maximum score by summing up the values corresponding to the selected cells\n return -sum(cost_matrix[i][j] for i, j in zip(row_ind, col_ind))\n```
8
1
['Python3']
1
select-cells-in-grid-with-maximum-score
Bitmask DP || All Bitmask DP Lists || Detail Explained || 100% common topics in today's contest!
bitmask-dp-all-bitmask-dp-lists-detail-e-4w0q
Bitmask DP Lists: https://leetcode.com/problem-list/mtxjny0h/\n\n# Code\ncpp []\n\n#define ll long long\n#define rep0(i,n) for(ll i = 0; i < n; i++)\n#define me
suvro_datta
NORMAL
2024-09-01T05:09:52.252540+00:00
2024-09-01T09:21:47.379031+00:00
667
false
Bitmask DP Lists: https://leetcode.com/problem-list/mtxjny0h/\n\n# Code\n```cpp []\n\n#define ll long long\n#define rep0(i,n) for(ll i = 0; i < n; i++)\n#define memo(a) memset(a, -1, sizeof(a));\n#define len(x) ((ll)x.size()) \n#define pb push_back\n\nclass Solution {\npublic:\n vector<vector<int>> nums;\n int dp[101][1025];\n\n int rec(int num, int bitmask) {\n if(num == 0) return 0;\n if(dp[num][bitmask] != -1) return dp[num][bitmask];\n\n //not take this number\n int ans = rec(num-1, bitmask); \n \n //take this number, we should get the number and which row it exists, number can be in multiple row \n for(auto row : nums[num]) { //which row this number belongs?\n int bit = 1 << row; \n if((bitmask & bit) == 0) { // if we never take item from this row, take from this row\n ans = max(ans, rec(num-1, bitmask | bit) + num); // add number with ans\n }\n }\n\n return dp[num][bitmask] = ans;\n }\n\n int maxScore(vector<vector<int>>& grid) {\n int rows = len(grid), cols = len(grid[0]);\n nums.resize(101);\n\n memo(dp);\n\n //keep track which row a number belongs to, a number can be in multiple row\n rep0(i, rows) {\n rep0(j, cols) {\n nums[grid[i][j]].pb(i);\n }\n }\n\n //number can be at max 100, so we will check all number and it\'s row\n ll ans = rec(100, 0);\n return ans;\n }\n};\n\n```\n\nA Gem for Beginners! I discussed Importance of DP here in contests and coding Interviews to Improve Ratings.\n<iframe width="560" height="315" src="https://www.youtube.com/embed/XAd0r5MvQiA" title="" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen><br>Powered by <a href="https://youtubeembedcode.com">html embed youtube video</a> and <a href="https://casinomga.se/">nya mga casino</a></iframe>\n\n100% questions is common in today\'s contest. I discussed few topics that would cover 80% coding contest and interviews problems. today 2nd one was priority queue, 3rd one was bitmask dp and 4th one was dp. All topics I discussed in my video. Feel free to watch those topics I discussed. It\'s a gem fro beginners.\n\n![0a95fea4-64f4-4502-82aa-41db6d77c05c_1676054939.8270252.jpeg](https://assets.leetcode.com/users/images/5c3c12f1-f521-4c7f-afec-337c965c1628_1725167389.0772295.jpeg)\n
5
0
['Dynamic Programming', 'Memoization', 'Bitmask', 'C++']
5
select-cells-in-grid-with-maximum-score
Beats 100% time , Beats 100% space: Greedy TreeMap
beats-100-time-beats-100-space-greedy-tr-robr
\n\n# Intution\n\nWe create a TreeMap in which the key is an element of the grid and the value is a set of rowIndexes that had the element.\n\nWe start from the
navid
NORMAL
2024-09-01T04:03:51.530765+00:00
2024-09-01T21:13:36.228111+00:00
1,120
false
![image.png](https://assets.leetcode.com/users/images/2959b070-4f16-4f12-84b2-206afa91278a_1725167093.7640224.png)\n\n# Intution\n\nWe create a TreeMap in which the key is an element of the grid and the value is a set of rowIndexes that had the element.\n\nWe start from the biggest number and keep going down. We also keep track of the visited rowIndexes. If the rowIndex for the current number is not visited, we can include that number. Otherwise, we skip it.\n\nPlease let me know if you\'d like a detailed explanation or if you have any questions.\n\n# Time Complexity\n\nIn general, it\'s O(row * uniqueElements)\n\nIf the number of unique elements is approximately equal to the number of columns, the time complexity is equal to the input size\n \n\n# Code\n```java [] \n TreeMap<Integer, Set<Integer>> treeMap = new TreeMap<>();\n\n public int maxScore(List<List<Integer>> grid) {\n createTreeMap(grid);\n Integer last = treeMap.lastKey();\n return getMax(last + 1, new HashSet<>());\n }\n\n private void createTreeMap(List<List<Integer>> grid) {\n for (int rowIndex = 0; rowIndex < grid.size(); rowIndex++) {\n List<Integer> list = grid.get(rowIndex);\n for (int columnIndex = 0; columnIndex < list.size(); columnIndex++) {\n int element = list.get(columnIndex);\n if (!treeMap.containsKey(element))\n treeMap.put(element, new HashSet<>());\n\n treeMap.get(element).add(rowIndex);\n }\n }\n }\n\n private int getMax(Integer biggerNumber, Set<Integer> visited) {\n Integer currentNumber = treeMap.lowerKey(biggerNumber);\n if (currentNumber == null) {\n return 0;\n }\n Set<Integer> rowIndexesSet = treeMap.get(currentNumber);\n boolean hadValidIndex = false;\n int max = 0;\n for (int rowIndex : rowIndexesSet) {\n if (visited.contains(rowIndex)) {\n continue;\n }\n hadValidIndex = true;\n visited.add(rowIndex);\n int maxSumOfLowerNumbers = getMax(currentNumber, visited);\n max = Math.max(max, maxSumOfLowerNumbers);\n visited.remove(rowIndex);\n }\n if (hadValidIndex) {\n return max + currentNumber;\n }\n return getMax(currentNumber, visited);\n }\n```
5
0
['Java']
3
select-cells-in-grid-with-maximum-score
bit-mask DP by limiting and enumerating the current largest element
bit-mask-dp-by-limiting-and-enumerating-jwh2l
Intuition\n1. Bit-mask DP takes care of the first condition: "no two selected cells are in the same row of the matrix."\n2. To satisfy the second requirement: "
lydxlx
NORMAL
2024-09-01T04:27:53.913809+00:00
2024-09-01T20:51:58.045437+00:00
164
false
# Intuition\n1. Bit-mask DP takes care of the first condition: "no two selected cells are in the same row of the matrix."\n2. To satisfy the second requirement: "the values in the set of selected cells are unique," we can require the selected value list is strictly decreasing. One way to achieve in DP is to add a new dimension `M` to cap the largest element we can select. \n\n# Approach\nLet `f[mask][M]` denote the largest sum we can achieve given a set of rows (denoted by bit-mask `mask`), where all the elements we choose are no greater than `M` and we always obey the two rules.\n\nThe base case is `f[0][M] = 0`.\nTo make the DP work, one idea is to enumerate the largest element from the current setup (say it\'s from `grid[i][j]`), where (i) `i` belongs to `mask` and `grid[i][j] <= M`. Then, we can recur on `f[mask - (1 << i)][grid[i][j] - 1]` since (i) row i has already been chosen and (ii) all the remaining elements now must be strictly less than `grid[i][j]`.\n\n# Complexity\n- Time complexity: $O(CRM2^R)$, where $R$ is the number of rows, $C$ is the number of columns, and $M$ is the largest element of the matrix ($M \\le 100$ for this problem). I believe the factor $R$ can be removed by carefully enumerating exactly those bits each `mask` contains, but the current complexity is already good enough to pass all the test cases while keeping the code simple.\n\n- Space complexity: $O(CM2^R)$\n\n# Code\n```python3\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n R = len(grid)\n C = len(grid[0])\n\n @cache\n def f(mask, M):\n if mask == 0:\n return 0\n ans = 0\n for i in range(R):\n if mask & (1 << i):\n for j in range(C):\n if grid[i][j] <= M:\n ans = max(ans, f(mask - (1 << i), grid[i][j] - 1) + grid[i][j])\n return ans\n\n ans = f((1 << R) - 1, 100)\n return ans\n```\n\n# Column Optimization - Binary Search\n\nNote that `f[mask][m] <= f[mask][M]` for any `m <= M`. Therefore, we only need to find the largest `grid[i][j] <= M` among all `j`s, which can be done quickly via binary search if we pre-sort all `grid[i]`s. This improves the runtime to $O(RM2^R\\log C + RC \\log C)$.\nIn practice, we approximately see runtime reduces to 1/5 of the previous version.\n\n\n```python3\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n R = len(grid)\n for i in range(R):\n grid[i].sort()\n\n @cache\n def f(mask, M):\n if mask == 0:\n return 0\n ans = 0\n for i in range(R):\n if mask & (1 << i):\n j = bisect.bisect_right(grid[i], M) - 1\n if j >= 0:\n ans = max(ans, f(mask - (1 << i), grid[i][j] - 1) + grid[i][j])\n return ans\n\n ans = f((1 << R) - 1, 100)\n return ans\n\n```\n\n# Row Optimization -- Greedy\nAccording to @porker2008\'s great comment, we can always pick the rows with the largest elements not greater than M instead of checking all the rows. This turns out to be a very strong pruning techinical in practice.\n```python3\nclass Solution:\n def maxScore(self, grid: List[List[int]]) -> int:\n R = len(grid)\n for i in range(R):\n grid[i].sort()\n\n @cache\n def f(mask, M):\n if mask == 0:\n return 0\n cand = []\n for i in range(R):\n if mask & (1 << i):\n j = bisect.bisect_right(grid[i], M) - 1\n if j >= 0:\n cand.append((grid[i][j], i))\n if not cand:\n return 0\n max_v = max(cand)[0]\n return max(f(mask - (1 << i), m - 1) + m for m, i in cand if m == max_v)\n\n return f((1 << R) - 1, 100)\n```\n\n\n\n
4
0
['Python3']
1
select-cells-in-grid-with-maximum-score
DP Bitmasking | Intuition Building | Full Explanation⚡⚡
dp-bitmasking-intuition-building-full-ex-hoqn
\nObservation:\n 1 <= row <= 10 and 1 <= value <= 100\n so we have to iterate over values,\n and we can mask the rows, \n (masking value will be a t
kaushalShinde
NORMAL
2024-09-02T06:50:53.181686+00:00
2024-09-02T06:55:53.430125+00:00
86
false
\n**Observation:**\n 1 <= row <= 10 and 1 <= value <= 100\n so we have to iterate over values,\n and we can mask the rows, \n (masking value will be a tedious task and gives tle, as we need to take `bitset<101>`)\n\n---\n\n**Intuition:**\nfor each value from 1 to 100 we will store in which row the value occured,\nand iterate over values from 101,\nand for each value val, we will see in which rows it occured,\nif that row is not considered earlier, we will take that value and make mask[row] = 0\nalso find for the condition when the value is not occured in any row\nso `dp(value, mask) => will store the max score till value` \n\n---\n\n**Recurrence:** \n `dp(value, mask) = dp(value - 1, mask ^ (1 << j))`,\n where j belongs to rowsOccurence[value]\n\n---\n\n**Note:** \n taken mask[row] = 1, if we have not considered row till now\n\n---\n\n**Complexity**\n - TC: O(m * 2^n)\n - SC: O(m * 2^n)\n\n# Code\n```cpp []\nclass Solution {\nprivate:\n map<int, vector<int>> occur; // {element, {rows in which element occured}}\n int dp[105][2050]; // {idx, mask}\nprivate:\n int solve(int idx, int mask) {\n if(idx == 0) {\n return 0;\n }\n\n if(dp[idx][mask] != -1) return dp[idx][mask];\n\n int mx = 0;\n for(int row: occur[idx]) {\n if(mask & (1 << row)) {\n mask = mask ^ (1 << row);\n\n int curr = idx + solve(idx - 1, mask);\n mx = max(mx, curr);\n\n mask = mask ^ (1 << row);\n }\n }\n \n int curr = 0 + solve(idx - 1, mask);\n mx = max(mx, curr);\n\n return dp[idx][mask] = mx;\n }\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n = grid.size(), m = grid[0].size();\n\n for(int row = 0; row < n; row++) {\n for(int col = 0; col < m; col++) {\n int ele = grid[row][col];\n occur[ele].push_back(row);\n }\n }\n\n memset(dp, -1, sizeof dp);\n\n int mask = (1 << 11) - 1;\n return solve(100, mask);\n }\n};\n\n
3
0
['Dynamic Programming', 'Bit Manipulation', 'Recursion', 'Bitmask', 'C++']
0
select-cells-in-grid-with-maximum-score
Easy Recursive dp solution
easy-recursive-dp-solution-by-kvivekcode-wt4c
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
kvivekcodes
NORMAL
2024-09-01T05:27:20.115701+00:00
2024-09-01T05:27:20.115727+00:00
535
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n int dp[101][102][1200];\n int solve(int i, int last, int hash, vector<vector<int> >& v) {\n if (i == -1) {\n return 0;\n }\n\n if(dp[i][last][hash] != -1) return dp[i][last][hash];\n\n int maxScore = 0;\n if(v[i][0] < last){\n if(((hash >> v[i][1]) & 1) == 0){\n maxScore = max(maxScore, v[i][0] + solve(i-1, v[i][0], hash | (1 << v[i][1]), v));\n }\n }\n maxScore = max(maxScore, solve(i-1, last, hash, v));\n return dp[i][last][hash] = maxScore;\n }\n\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n = grid.size(), m = grid[0].size();\n vector<vector<int> > v;\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n v.push_back({grid[i][j], i});\n }\n }\n sort(v.begin(), v.end());\n memset(dp, -1, sizeof(dp));\n return solve(v.size() - 1, 101, 0, v);\n }\n};\n```
3
0
['Dynamic Programming', 'Sorting', 'Bitmask', 'C++']
0
select-cells-in-grid-with-maximum-score
Intuition and Approach are commented in Code..
intuition-and-approach-are-commented-in-qs6ty
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Animesh_Maurya
NORMAL
2024-10-21T11:44:05.842872+00:00
2024-10-21T11:44:05.842896+00:00
16
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n//Good bit Mask question in why we are using bitmask because we need to keep the track \n//of the wchich row we had taken and the no of row maximimum is 10 so we only requrire 10 bits\n//and it will not give MLE and we need the maximum score so we tries to take the maximum one first\n//thts why we have to start from the maximum value..\nprivate:\n int maxPoints(int n,vector<vector<int>>& dp,vector<int> count[],int mask){\n if(n == 0)return 0;\n\n if(dp[n][mask] != -1) return dp[n][mask];\n\n int ans=maxPoints(n-1,dp,count,mask);//this means we are skipping this number\n //and we are going for the next number\n\n for(auto it:count[n]){\n if((mask & (1 << it) ) ) continue;//it is ensuring this we had not taken this row previously\n //because if it is taken then its value should be one and we are not able to take this row...\n ans=max(ans,n + maxPoints(n-1,dp,count,mask | (1 << it)));//if i am going to tkae this row then i am \n //going to mark this bit so that further no one can able to take this row again..\n\n }\n return dp[n][mask]=ans;\n }\npublic:\n int maxScore(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n //here we setting the size of the dp matirx like this because the maximum number is 100 and the number\n //of possible rows is (n) so the totla bits needed to represent the (n) rows we needed to take the \n //number (2^n) which will keep the track of which row has taken previously..\n vector<vector<int>> dp(101,vector<int>(1<<n,-1));\n //here we are storing the frequency of any number in which row it is present..\n vector<int> count[101];\n int maxi=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n //this means in which row this value is present.\n count[grid[i][j]].push_back(i);\n maxi=max(maxi,grid[i][j]);\n }\n }\n //it is meant that i hava options from where to take the number and what are the\n //previous rows i had taken in the starting we have the option to pick the maximum value\n //and till now we had not taken any row so the mask value is 0.\n //here we had to remember what are the previous values we had taken we are doing thos \n //the bitmask....\n return maxPoints(maxi,dp,count,0);\n\n }\n};\n```
2
0
['Array', 'Dynamic Programming', 'Bit Manipulation', 'Matrix', 'Bitmask', 'C++']
1
select-cells-in-grid-with-maximum-score
🔥Memoization with BitMasking⭐|| 💯Clean & Best Code⚡
memoization-with-bitmasking-clean-best-c-x6ai
Complexity\n\n- Time complexity:\nO((1 << m) * max(grid[i][j]) * m * n)\n\n- Space complexity:\nO((1 << m) * max(grid[i][j]))\n\n\n# Code\n# Please Upvote if it
aDish_21
NORMAL
2024-09-13T19:09:03.954492+00:00
2024-09-13T19:09:03.954515+00:00
36
false
# Complexity\n```\n- Time complexity:\nO((1 << m) * max(grid[i][j]) * m * n)\n\n- Space complexity:\nO((1 << m) * max(grid[i][j]))\n```\n\n# Code\n# Please Upvote if it helps\uD83E\uDD17\n```cpp []\nclass Solution {\npublic:\n int dp[101][1024];\n int helper(int prev_val, vector<vector<int>>& grid, int mask){\n if(dp[prev_val][mask] != -1)\n return dp[prev_val][mask];\n int maxi = 0;\n for(int row = 0 ; row < grid.size() ; row++){\n if(!(mask & (1 << row))){\n for(auto it : grid[row]){\n if(it > prev_val)\n maxi = max(maxi, it + helper(it, grid, mask | (1 << row)));\n }\n }\n }\n return dp[prev_val][mask] = maxi;\n }\n\n int maxScore(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n memset(dp, -1, sizeof(dp));\n return helper(0, grid, 0);\n }\n};\n```
2
0
['Array', 'Dynamic Programming', 'Bit Manipulation', 'Memoization', 'Matrix', 'Bitmask', 'C++']
0