Problem
You run an e-commerce website and want to record the last N
order
ids in a log. Implement a data structure to accomplish this, with the following API:
record(order_id)
: adds the order_id to the logget_last(i)
: gets the ith last element from the log. i is guaranteed to be smaller than or equal to N.
You should be as efficient with time and space as possible.
Examples
Example 1:
|
|
Solution
Method 1 - Using Circular Array
We can first define following:
OrderLog
: The class representing the log.N
: The maximum number of order IDs to store.orders
: A circular array to store the order IDs.head
: Index pointing to the oldest order ID in the array.
Record method
First we implement record method.
record(order_id)
: Adds the new order ID to the log.- It updates the
head
index using modulo (%
) to achieve circular behavior within the array. - This ensures that the latest order ID is always stored at the most recently accessed position.
- It updates the
get_last(i)
: Retrieves thei
th last order ID from the log.- It checks for invalid index values.
- It calculates the actual index in the array by considering the
head
position and the requested position (i
). - The modulo operation is used again to handle cases where the requested position might be beyond the beginning of the array (due to the circular nature).
Code
|
|
|
|
Complexity
record()
- ⏰ Time complexity:
O(1)
, due to the constant-time array access and update. - 🧺 Space complexity:
O(n)
, as we are storing the elements in array
getLast()
- ⏰ Time complexity:
O(1)
, Runs in constant time (O(1)) as well, because the calculation of the actual index using modulo is also a constant-time operation. - 🧺 Space complexity:
O(n)
, as we are storing the elements in array