Easy to Understand Java Solution with Explanation - TreeSet
What we really need in discussion section is  a readable solution with detailed comments possible to make it look easier to understand, rather than just talking
What we really need in discussion section is  a readable solution with detailed comments possible to make it look easier to understand, rather than just talking about the same constraints already mentioned in the question!  It is important to discuss the optimized solution, but it is also important to come up with a viable solution that can be formed within 20-25 minutes in the actual interview.\n\n```\n\nclass ExamRoom {\n\n    int capacity; // this is just to keep track of the max allowed size\n    TreeSet<Integer> seats; \n\t/* why treeset, because seats will be sorted automatically \n\t   and get first()/last() element in log(n) time. \n\t*/\n    \n    public ExamRoom(int n) {\n        this.capacity=n;\n        this.seats = new TreeSet<>();\n    }\n    \n    public int seat() {\n        int seatNumber=0;\n\t\t/*\n\t\t  Return 0 for first attempt ( as mentioned in question)\n\t\t  Otherwise, we need to calculate the max distance by checking the whole treeset : O(n) time. \n\t\t  Note that "distance" variable is initialized to first appearing seat,\n\t\t  why because the distance calculation is based on current seat and the seat before that. \n\t\t  Find the maximum distance and update the seat number accordingly.\n\t\t  distance calculation -> (current seat - previous seat )/ 2\n\t\t  Update the max distance at each step.\n\t\t  New seat number will be ->  previous seat number + max distance \n\t\t  \n\t\t  Now, before returning the end result,  check for one more edge case:\n\t\t  That is, if the max distance calculated is less than ->  capacity-1-seats.last()\n\t\t  \n\t\t  Why because -> if last seat number in treeset is far from last position, \n\t\t  then  the largest distance possible is the last position.\n\t\t  \n\t\t*/\n        if(seats.size() > 0){\n            Integer prev=null;\n            int distance = seats.first();\n            for(Integer seat : seats){\n                if(prev != null){\n                    int d = (seat-prev)/2;\n                    if(distance < d){\n                        distance=d;\n                        seatNumber=prev+distance;\n                    }\n                }\n                prev = seat;\n            }\n            \n            if(distance < capacity-1-seats.last()){\n                seatNumber = capacity-1;\n            }\n        }\n        seats.add(seatNumber);\n        return seatNumber;\n    }\n    \n    public void leave(int p) {\n        seats.remove(p); \n\t\t/* simply remove the seat number from treeset\n\t\t and treeset will be automatically adjust its order in log(n) time. \n\t\t*/\n    }\n}\n\n\n\n```
['Java']