493. Circular Buffer With Three Task Priority Levels
Circular Buffer With Three Task Priority Levels
Design a fixed-size circular buffer that stores tasks. Each task has a taskId and comes with one of three priority levels: 1, 2 or 3. Priority 1 is the highest and priority 3 is the lowest.

Tasks of all priority levels must be stored in one single contiguous buffer of size capacity. Any free slot can hold a task of any priority, so a slot freed by one priority can be reused by another.

A pop always removes a task with the highest priority currently present. Among tasks with the same priority, the task pushed earliest is removed first.

Methods

Constructor

PriorityCircularBuffer(int capacity)
  • Creates an empty buffer that can hold at most capacity tasks in total.

Push

boolean push(int taskId, int priority)
  • Adds a task with id taskId and the given priority into the buffer.
  • Returns true if the task was added.
  • Returns false and changes nothing if the buffer already holds capacity tasks.

Pop

int pop()
  • Removes and returns the taskId of the earliest pushed task with priority 1.
  • If no priority 1 task exists, it does the same for priority 2, and then for priority 3.
  • Returns -1 if the buffer is empty.

Constraints

  • 1 ≤ capacity ≤ 100,000
  • 1 ≤ priority ≤ 3
  • 0 ≤ taskId ≤ 1,000,000,000
  • At most 200,000 calls in total will be made to push and pop.
  • Each push and pop should run in O(1) time.

Examples

Example 1

PriorityCircularBuffer buffer = new PriorityCircularBuffer(capacity = 4)
buffer.push(taskId = 11, priority = 3) returns true
buffer.push(taskId = 12, priority = 1) returns true
buffer.push(taskId = 13, priority = 2) returns true
buffer.push(taskId = 14, priority = 1) returns true
buffer.push(taskId = 15, priority = 2) returns false, the buffer already holds 4 tasks.
buffer.pop() returns 12, tasks 12 and 14 have priority 1 and task 12 was pushed earlier.
buffer.pop() returns 14
buffer.push(taskId = 15, priority = 2) returns true, a freed slot is reused.
buffer.pop() returns 13, no priority 1 task is left and task 13 was pushed before task 15.
buffer.pop() returns 15
buffer.pop() returns 11
buffer.pop() returns -1, the buffer is empty.

Example 2

PriorityCircularBuffer buffer = new PriorityCircularBuffer(capacity = 2)
buffer.push(taskId = 7, priority = 2) returns true
buffer.push(taskId = 8, priority = 2) returns true
buffer.pop() returns 7, both tasks have priority 2 and task 7 was pushed first.
buffer.push(taskId = 9, priority = 3) returns true, the slot freed by a priority 2 task now holds a priority 3 task.
buffer.push(taskId = 10, priority = 1) returns false, the buffer holds tasks 8 and 9.
buffer.pop() returns 8, priority 2 comes before priority 3.
buffer.push(taskId = 10, priority = 1) returns true
buffer.pop() returns 10
buffer.pop() returns 9
buffer.pop() returns -1


Please use Laptop/Desktop or any other large screen to add/edit code.