What is the best way to design a data structure/class to store and keep track of time-series data that supports O(1) addition and retrival (in an interview/online assessemnt context)?
For example, if I need to design a Truck class and a Container class and also retrieve the weight of the truck at a given time, what is the best way to go about it during the time crunch of an interivew or an online test?
I have two apporahes in mind;
Approach1
class Truck:
def __init__(self, maxSize, maxWeight):
self.weightMap = dict() # k:v = time : weight
self.weight = 0
def getWeight(self, time):
# will have to accumlate the changes to return weight at a given timestamp (O(N) retrieval)
w = 0
for k in self.weightMap:
if k <= time:
w += self.weightMap[k]
return wApproach2
def __init__(self):
# self.weightMap = dict() # k:v = time : weight
from collections import OrderedDict
self.d = OrderedDict()
def load(self, container):
# fetch time from system
import datetime
time = datetime.datetime.now()
if len(self.d) == 0:
self.d[time] = container.weight
else:
# get most recent val
k = list(self.d.keys())[-1]
v = self.d[k]
v += container.weight # ADD
self.d[time] = vI would appreciate any other thoughts