[Daily Coding Problem] 16. Last N order ids implementation
This problem was asked by Twitter.
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 log
- get_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.
Implementing a circular buffer suffices the requirement. It takes O(1) to record and get last ith.
1 public class LogDataStructure { 2 private int maxSize; 3 private int[] circularBuffer; 4 private int currIdx; 5 6 public LogDataStructure(int n) { 7 this.maxSize = n; 8 this.circularBuffer = new int[n]; 9 this.currIdx = 0; 10 } 11 12 public void record(int orderId) { 13 circularBuffer[currIdx] = orderId; 14 currIdx = (currIdx + 1) % maxSize; 15 } 16 17 public int getLast(int i) { 18 return circularBuffer[(currIdx - i + maxSize) % maxSize]; 19 } 20 }