Interview Question: Store Last N order Ids

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.


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
#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.

#blog #interview #placement #Interview #twitter #MNC #dailycoddingproblem

45 views0 comments

Recent Posts

See All

        Contact Us

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door