https://leetcode.com/problems/exam-room/description/
https://leetcode.com/problems/exam-room/discuss/148595/Java-PriorityQueue-with-customized-object.-seat:-O(logn)-leave-O(n)-with-explanation
#### PriorityQueue
- Use priority queue to sort by customized class interval{int dist; int x, y;}.
- Sort by larger distance and then sort by start index
- seat(): pq.poll() to find interval of largest distance. Split and add new intervals back to queue.
- leave(x): one seat will be in 2 intervals: remove both from pq, and merge to a new interval.
- 主方程写出来其实很好写, 就是 split + add interval, 然后 find + delete interval 而已. 最难的是构建data structure
- seat(): O(logn), leave(): O(n)
##### Trick: 构建虚拟 boundary
- 如果是开头的seat, 或者是结尾的seat, 比较难handle: 一开始坐在seat=0的时候, 没有interval啊!
- Trick就是, 我们自己定义个虚拟的座位 `seat=-1`, `seat=N`
- 一开始有一个 interval[-1, N] 然后就建立了boundary.
- 从此以后, 每次split成小interval的时候:
- 遇到 `interval[-1, y]`, distance就是 `(y - 0)`
- 遇到 `interval[x, N]`, distance就是 `(N - 1 - x)`
- 当然正常的interval dist 就是 `(y - x) / 2`
##### distance 中间点
- Interval.dist 我们其实做的是 distance的中间点 `(y - x) / 2`
- 这里的dist是 `距离两边的距离` 而不是 x, y 之间的距离. 这里要特别注意.
#### TreeSet
- https://leetcode.com/problems/exam-room/discuss/139885/Java-Solution-based-on-treeset/153588
https://leetcode.com/problems/exam-room/discuss/139885/Java-Solution-based-on-treeset
Approach 1: Maintain Sorted Positions
https://leetcode.com/problems/exam-room/discuss/139862/C++JavaPython-Straight-Forward
1. find the biggest distance at the start, at the end and in the middle.
2. insert index of seat
3. return index
In an exam room, there are
N
seats in a single row, numbered 0, 1, 2, ..., N-1
.
When 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. (Also, if no one is in the room, then the student sits at seat number 0.)
Return a class
ExamRoom(int N)
that exposes two functions: ExamRoom.seat()
returning an int
representing what seat the student sat in, and ExamRoom.leave(int p)
representing that the student in seat number p
now leaves the room. It is guaranteed that any calls to ExamRoom.leave(p)
have a student sitting in seat p
.Input: ["ExamRoom","seat","seat","seat","seat","leave","seat"], [[10],[],[],[],[],[4],[]] Output: [null,0,9,4,2,null,5] Explanation: ExamRoom(10) -> null seat() -> 0, no one is in the room, then the student sits at seat number 0. seat() -> 9, the student sits at the last seat number 9. seat() -> 4, the student sits at the last seat number 4. seat() -> 2, the student sits at the last seat number 2. leave(4) -> null seat() -> 5, the student sits at the last seat number 5.
Note:
1 <= N <= 10^9
ExamRoom.seat()
andExamRoom.leave()
will be called at most10^4
times across all test cases.- Calls to
ExamRoom.leave(p)
are guaranteed to have a student currently sitting in seat numberp
.
The major idea is to store intervals into the TreeMap, every time when we add a seat, we get the longest interval and put a seat in the middle, then break the interval into two parts. Notice that for intervals with odd length, we simply trim it into even length using len -= len & 1.
TreeMap<Integer, TreeSet<Integer>> map = new TreeMap<>();
TreeSet<Integer> set = new TreeSet<>();
int N;
public ExamRoom(int N) {
this.N = N;
}
public int seat() {
int res = 0;
if (set.size() == 0) {
res = 0;
} else {
int first = set.first(), last = set.last();
Integer max = map.isEmpty() ? null : map.lastKey();
if (max == null || first >= max / 2 || N - 1 - last > max / 2) {
if (first >= N - 1 - last) {
addInterval(0, first);
res = 0;
} else {
addInterval(last, N - 1 - last);
res = N - 1;
}
} else {
TreeSet<Integer> temp = map.get(max);
int index = temp.first();
int next = set.higher(index);
int mid = (next + index) / 2;
removeInterval(index, max);
addInterval(index, mid - index);
addInterval(mid, next - mid);
res = mid;
}
}
set.add(res);
return res;
}
public void leave(int p) {
Integer pre = set.lower(p);
Integer next = set.higher(p);
set.remove(p);
if (next != null) {
removeInterval(p, next - p);
}
if (pre != null) {
removeInterval(pre, p - pre);
if (next != null) {
addInterval(pre, next - pre);
}
}
}
private void addInterval(int index, int len) {
len -= len & 1; // trim to even number
map.putIfAbsent(len, new TreeSet<>());
map.get(len).add(index);
}
private void removeInterval(int index, int len) {
len -= len & 1;
Set<Integer> temp = map.get(len);
if (temp == null) {
return;
}
temp.remove(index);
if (temp.size() == 0) {
map.remove(len);
}
}
The hardest part of the problem is to build the right data structure. More explanations here: https://github.com/awangdev/LintCode/blob/master/Java/Exam Room.java
A few concepts to discover:
- Need to measure the distance between seated students: O(n) is trivial, but not as fast. Use
PriorityQueue to store the potential candidate as interval
, and also calculate the candidate's mid-distance to both side. - seat(): pq.poll() to find interval of largest distance. Split and add new intervals back to queue.
- leave(x): one seat will be in 2 intervals: remove both from pq, and merge to a new interval.
- Trick: there is no interval when adding for first student, so we need to create boundary/fake seats
[-1, N]
, which simplifies the edge case a lot. (I spent hours on edge case, and finally saw a smart abstraction using boundary seats).
#### PriorityQueue
- Use priority queue to sort by customized class interval{int dist; int x, y;}.
- Sort by larger distance and then sort by start index
- seat(): pq.poll() to find interval of largest distance. Split and add new intervals back to queue.
- leave(x): one seat will be in 2 intervals: remove both from pq, and merge to a new interval.
- 主方程写出来其实很好写, 就是 split + add interval, 然后 find + delete interval 而已. 最难的是构建data structure
- seat(): O(logn), leave(): O(n)
##### Trick: 构建虚拟 boundary
- 如果是开头的seat, 或者是结尾的seat, 比较难handle: 一开始坐在seat=0的时候, 没有interval啊!
- Trick就是, 我们自己定义个虚拟的座位 `seat=-1`, `seat=N`
- 一开始有一个 interval[-1, N] 然后就建立了boundary.
- 从此以后, 每次split成小interval的时候:
- 遇到 `interval[-1, y]`, distance就是 `(y - 0)`
- 遇到 `interval[x, N]`, distance就是 `(N - 1 - x)`
- 当然正常的interval dist 就是 `(y - x) / 2`
##### distance 中间点
- Interval.dist 我们其实做的是 distance的中间点 `(y - x) / 2`
- 这里的dist是 `距离两边的距离` 而不是 x, y 之间的距离. 这里要特别注意.
#### TreeSet
- https://leetcode.com/problems/exam-room/discuss/139885/Java-Solution-based-on-treeset/153588
PriorityQueue<Interval> pq;
int N;
class Interval {
int x, y, dist;
public Interval(int x, int y) {
this.x = x;
this.y = y;
if (x == -1) {
this.dist = y;
} else if (y == N) {
this.dist = N - 1 - x;
} else {
this.dist = Math.abs(x - y) / 2;
}
}
}
public ExamRoom(int N) {
this.pq = new PriorityQueue<>((a, b) -> a.dist != b.dist? b.dist - a.dist : a.x - b.x);
this.N = N;
pq.add(new Interval(-1, N));
}
// O(logn): poll top candidate, split into two new intervals
public int seat() {
int seat = 0;
Interval interval = pq.poll();
if (interval.x == -1) seat = 0;
else if (interval.y == N) seat = N - 1;
else seat = (interval.x + interval.y) / 2;
pq.offer(new Interval(interval.x, seat));
pq.offer(new Interval(seat, interval.y));
return seat;
}
// O(n)Find head and tail based on p. Delete and merge two ends
public void leave(int p) {
Interval head = null, tail = null;
List<Interval> intervals = new ArrayList<>(pq);
for (Interval interval : intervals) {
if (interval.x == p) tail = interval;
if (interval.y == p) head = interval;
if (head != null && tail != null) break;
}
// Delete
pq.remove(head);
pq.remove(tail);
// Merge
pq.offer(new Interval(head.x, tail.y));
}
Idea is to Use a TreeSet to store the current seat index in use. Whenever we want to add a seat, check the max distance adjacent indices in the treeset, whichever is the max that is our answer.
For edge cases :
When zero student: return 0;
When there is one student., return 0 if the student is in second half or return N - 1 if the student is in first half.
Otherwise, apply the idea,
For edge cases :
When zero student: return 0;
When there is one student., return 0 if the student is in second half or return N - 1 if the student is in first half.
Otherwise, apply the idea,
TreeSet<Integer> s = new TreeSet<>();
int N;
public ExamRoom(int N) {
this.N = N;
}
public int seat() {
//When no student
if (s.isEmpty()) {
s.add(0);
return 0;
}
//When One student
if (s.size() == 1) {
int num = s.first();
if (num < (N / 2)) {
s.add(N - 1);
return N - 1;
} else {
s.add(0);
return 0;
}
}
//When more than one student
Iterator<Integer> it = s.iterator();
int dist = -1;
int position = -1;
int left = it.next();
//check the distance between 0 and first student
if (left > 0) {
position = 0;
dist = left;
}
int right = -1;
//Check the distance between adjacent indices,(already sorted)
while (it.hasNext()) {
right = it.next();
if ((right - left) / 2 > dist) {
dist = (right - left) / 2;
position = left + dist;
}
left = right;
}
//check the distance between last student and (N - 1)
if ((N - 1) - left > dist) {
position = N - 1;
}
s.add(position);
return position;
}
public void leave(int p) {
s.remove(p);
}
We'll maintain
ExamRoom.students
, a sorted list
(or TreeSet
in Java) of positions the students are currently seated in.
Algorithm
The
ExamRoom.leave(p)
operation is clear - we will just list.remove
(or TreeSet.remove
) the student from ExamRoom.students
.
Let's focus on the
ExamRoom.seat() : int
operation. For each pair of adjacent students i
and j
, the maximum distance to the closest student is d = (j - i) / 2
, achieved in the left-most seat i + d
. Otherwise, we could also sit in the left-most seat, or the right-most seat.
Finally, we should handle the case when there are no students separately.
- Time Complexity: Each
seat
operation is , (where is the number of students sitting), as we iterate through every student. Eachleave
operation is ( in Java). - Space Complexity: , the space used to store the positions of each student sitting
int N;
TreeSet<Integer> students;
public ExamRoom(int N) {
this.N = N;
students = new TreeSet();
}
public int seat() {
// Let's determine student, the position of the next
// student to sit down.
int student = 0;
if (students.size() > 0) {
// Tenatively, dist is the distance to the closest student,
// which is achieved by sitting in the position 'student'.
// We start by considering the left-most seat.
int dist = students.first();
Integer prev = null;
for (Integer s : students) {
if (prev != null) {
// For each pair of adjacent students in positions (prev, s),
// d is the distance to the closest student;
// achieved at position prev + d.
int d = (s - prev) / 2;
if (d > dist) {
dist = d;
student = prev + d;
}
}
prev = s;
}
// Considering the right-most seat.
if (N - 1 - students.last() > dist)
student = N - 1;
}
// Add the student to our sorted TreeSet of positions.
students.add(student);
return student;
}
public void leave(int p) {
students.remove(p);
}
https://leetcode.com/problems/exam-room/discuss/139862/C++JavaPython-Straight-Forward
Use a list
L
to record the index of seats where people sit.seat()
:1. find the biggest distance at the start, at the end and in the middle.
2. insert index of seat
3. return index
leave(p)
: pop out p
Time Complexity:
O(N) for
O(N) for
seat()
and leave()
int N;
ArrayList<Integer> L = new ArrayList<>();
public ExamRoom(int n) {
N = n;
}
public int seat() {
if (L.size() == 0) {
L.add(0);
return 0;
}
int d = Math.max(L.get(0), N - 1 - L.get(L.size() - 1));
for (int i = 0; i < L.size() - 1; ++i) d = Math.max(d, (L.get(i + 1) - L.get(i)) / 2);
if (L.get(0) == d) {
L.add(0, 0);
return 0;
}
for (int i = 0; i < L.size() - 1; ++i)
if ((L.get(i + 1) - L.get(i)) / 2 == d) {
L.add(i + 1, (L.get(i + 1) + L.get(i)) / 2);
return L.get(i + 1);
}
L.add(N - 1);
return N - 1;
}
public void leave(int p) {
for (int i = 0; i < L.size(); ++i) if (L.get(i) == p) L.remove(i);
}