Design a class to keep track of time series data - interview

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

  • maintian a dict to keep track of <time: weight> pairs
  • This dict will simulate a discrete time-series function that maps the delta (cahnge in weight [y-axis] versus timestamp[x-axis])
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 w

Approach2

  • Use an OrderedDict to simulate a time-series function in which the y-axis is the accumlative weight at corresponding timestamp [x-axis]
  • retreval is O(1)
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] = v

I would appreciate any other thoughts

Comments (1)