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.
Implementation:
class LogData:
def __init__(self,size):
self.maxSize = size
self.circularBuffer = [None] * size
self.index = 0
def record(self,orderId):
self.circularBuffer[self.index] = orderId
self.index = (self.index + 1) % self.maxSize
def getLast(self,i):
return self.circularBuffer[
(self.index - i + self.maxSize)% self.maxSize]
#Size Of Log
data = LogData(5)
#Giving Input
data.record(5)
data.record(4)
data.record(6)
data.record(9)
data.record(12)
data.record(90)
data.record(120)
#Get the last third order Id
print(data.getLast(3)) #Output Should be 12
Follow us on Instagram @programmersdoor
Join us on Telegram @programmersdoor
Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem
Follow Programmers Door for more.
Comments