A print server keeps waiting jobs in a first-in, first-out queue that can never hold more than a fixed number of jobs. Build the class BoundedQueue:
BoundedQueue(capacity)creates an empty queue that holds at mostcapacityvalues (capacity >= 1).enqueue(value) -> booladdsvalueat the back and returnsTrue, or returnsFalseand changes nothing if the queue is full.dequeue() -> intremoves and returns the value at the front, or returns-1if the queue is empty.front() -> intandback() -> intreturn the value at the front / back without removing it, or-1if the queue is empty.size() -> intreturns how many values are waiting.is_full() -> boolreturns whethersize() == capacity.
q = BoundedQueue(2)
q.enqueue(5) # True
q.enqueue(8) # True
q.enqueue(1) # False (full)
q.is_full() # True
q.dequeue() # 5
q.enqueue(1) # True
q.front() # 8
q.back() # 1
q.size() # 2
q.dequeue() # 8
q.dequeue() # 1
q.dequeue() # -1
q.back() # -1
Constraints: capacity <= 200,000; values are integers from 0 to 10^9; up to 600,000 calls. Every method must run in O(1) time and the queue should use O(capacity) memory however many values pass through it. Removing from the front of a Python list (pop(0), del q[0]) shifts every other element, so it is too slow here. Don't use collections.deque or the queue module: the point is to build the structure yourself.
Show hint
Either chain the values together as nodes with a pointer to each end, or keep a fixed-size array with an index for the front and a count, letting positions wrap past the end back to the start.