Exam Room LeetCode solution in JavaScript

1
/**
2
* @param {number} n
3
*/
4
var ExamRoom = function (n) {
5
this.n = n;
6
this.list = [];
7
};
8

9
/**
10
* @return {number}
11
*/
12
ExamRoom.prototype.seat = function () {
13
// if nothing in the list, seat the first student at index 0.
14
if (this.list.length === 0) {
15
this.list.push(0);
16
return 0;
17
}
18

19
// find the largest distance between left wall and first student, and right wall and last student
20
let distance = Math.max(
21
this.list[0],
22
this.n - 1 - this.list[this.list.length - 1]
23
);
24
// update the largest distance by considering the distance between students
25
for (let i = 0; i < this.list.length - 1; i++) {
26
distance = Math.max(
27
distance,
28
Math.floor((this.list[i + 1] - this.list[i]) / 2)
29
);
30
}
31

32
// in case the largest distance is between left wall and first student, we seat next student at the left wall
33
if (distance === this.list[0]) {
34
this.list.unshift(0);
35
return 0;
36
}
37

38
// in case the largest distance is between two student, we seat the next student in between these two students
39
for (let i = 0; i < this.list.length - 1; i++) {
40
if (distance === Math.floor((this.list[i + 1] - this.list[i]) / 2)) {
41
let insertIndex = Math.floor((this.list[i + 1] + this.list[i]) / 2);
42
this.list.splice(i + 1, 0, insertIndex);
43
return insertIndex;
44
}
45
}
46

47
// in case the largest distance is between the last student and the right wall, we seat the next student at the right wall
48
this.list.push(this.n - 1);
49
return this.n - 1;
50
};
51

52
/**
53
* @param {number} p
54
* @return {void}
55
*/
56
ExamRoom.prototype.leave = function (p) {
57
// We iterate through the list and find the index where the student p sit at, then remove that index.
58
for (let i = 0; i < this.list.length; i++) {
59
if (this.list[i] === p) {
60
this.list.splice(i, 1);
61
break;
62
}
63
}
64
};
65

66
/**
67
* Your ExamRoom object will be instantiated and called as such:
68
* var obj = new ExamRoom(n)
69
* var param_1 = obj.seat()
70
* obj.leave(p)
71
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0