Critical Order Buffer
Blinkit's order processing system utilizes a pre-processing buffer to manage incoming orders efficiently. This buffer has a fixed capacity and is designed to prioritize critical orders, ensuring they are accepted even when the buffer is full, by displacing less critical orders.
Implement the OrderBuffer class with the following specifications:
constructor(capacity: number): Initializes the buffer with a specified maximum capacity.
addOrder(orderId: number, isCritical: boolean): number | null: Attempts to add a new order to the buffer. The behavior depends on the buffer's current state and the isCritical flag of the new order:
capacity), the new order is simply added to the end of the buffer.size === capacity):
The method should return the orderId of any order that was displaced (either an existing order removed from the buffer, or the new order itself if it was rejected). If no order was displaced (i.e., the new order was simply added to an available slot), return null.
OrderBuffer(capacity: number)
capacity: The maximum number of orders the buffer can hold.addOrder(orderId: number, isCritical: boolean): number | null
orderId: A unique identifier for the incoming order (number).isCritical: A boolean flag indicating if the order is critical (true) or non-critical (false).number | null. The orderId of the displaced order, or null if no order was displaced.orderId: All orderIds provided will be unique.capacity = 0: If capacity is 0, all addOrder calls will result in the new order being rejected (displaced).Examples
Example 1
Input:
operations = ["OrderBuffer","addOrder","addOrder","addOrder"] params = [[2],[101,false],[102,true],[103,false]]
Output:
[null,null,null,103]
Note:
Initialize buffer with capacity 2.
Example 2
Input:
operations = ["OrderBuffer","addOrder","addOrder","addOrder"] params = [[2],[201,false],[202,true],[203,true]]
Output:
[null,null,null,201]
Note:
Initialize buffer with capacity 2.
Example 3
Input:
operations = ["OrderBuffer","addOrder","addOrder","addOrder","addOrder"] params = [[1],[301,true],[302,true],[303,false],[304,true]]
Output:
[null,null,302,303,304]
Note:
Initialize buffer with capacity 1.
Constraints
1 <= capacity <= 2001 <= orderId <= 10^9addOrder will not exceed 10^5.addOrder should be efficient enough to pass within typical time limits (e.g., O(capacity) is acceptable).capacity of 1.addOrder operation performs within acceptable time limits given the constraints.Loading editor...