The challenge is:
Coding Interview Prep > Data Structures > Create a Circular Queue
My solution is:
class CircularQueue {
constructor(size) {
this.queue = [];
this.read = 0;
this.write = 0;
this.max = size - 1;
while (size > 0) {
this.queue.push(null);
size--;
}
}
print() {
return this.queue;
}
enqueue(item) {
// Only change code below this line
if (this.queue[this.write] == null) {
this.queue[this.write] = item;
if (this.write == this.max) {
this.write = 0;
} else {
this.write++;
}
}
// Only change code above this line
}
dequeue() {
// Only change code below this line
let result = "";
if (this.queue[this.read] != null) {
result = this.queue[this.read];
this.queue[this.read] = null;
if (this.read == this.max) {
this.read = 0;
} else {
this.read++;
}
return result;
} else {
return null;
}
// Only change code above this line
}
}
// tests
let cq = new CircularQueue(5);
let dequeued;
for (let i = 0; i <= 100; i++) {
cq.enqueue(i + 2 + "b");
console.log("enqueue")
console.log(cq.print())
console.log("write=> ", cq.write, " read=> ", cq.read);
console.log("")
cq.enqueue(i + 3 + "c");
console.log("enqueue")
console.log(cq.print())
console.log("write=> ", cq.write, " read=> ", cq.read);
console.log("")
dequeued = cq.dequeue();
console.log("dequeue")
console.log(cq.print())
console.log("write=> ", cq.write, " read=> ", cq.read, " dequeued=> ", dequeued);
console.log("")
dequeued = cq.dequeue();
console.log("dequeue")
console.log(cq.print())
console.log("write=> ", cq.write, " read=> ", cq.read, " dequeued=> ", dequeued);
console.log("")
dequeued = cq.dequeue();
console.log("dequeue")
console.log(cq.print())
console.log("write=> ", cq.write, " read=> ", cq.read, " dequeued=> ", dequeued);
console.log("")
}
It seems to me, looking at the output of the test code, that the code is working fine. But the system tests return the following error:
Trying to dequeue past the write pointer should return null
and does not advance the write pointer.
I repeat, looking at the test code it seems to me that this requirement is met: trying to dequeue past the write pointer it returns null and does not advance the write pointer. But obviously there is an error that I cannot see.
Thanks for your patience.