LeetCode 855 - Exam Room


https://leetcode.com/problems/exam-room/description/
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. 1 <= N <= 10^9
  2. ExamRoom.seat() and ExamRoom.leave() will be called at most 10^4 times across all test cases.
  3. Calls to ExamRoom.leave(p) are guaranteed to have a student currently sitting in seat number p.


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);
        }
    }

https://leetcode.com/problems/exam-room/discuss/148595/Java-PriorityQueue-with-customized-object.-seat:-O(logn)-leave-O(n)-with-explanation
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).
https://github.com/awangdev/LintCode/blob/master/Java/Exam%20Room.java
#### 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));
    }
https://leetcode.com/problems/exam-room/discuss/139885/Java-Solution-based-on-treeset


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,
    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);
    }

Approach 1: Maintain Sorted Positions
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 O(P), (where P is the number of students sitting), as we iterate through every student. Each leave operation is O(P) (\log P in Java).
  • Space Complexity: O(P), 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 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);
    }






Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts