0

Suppose there is a real time feed of stock prices, how do you calculate the average of a subset of it (say over the past week)?

This was an interview question. I can come up with an algorithm to do it in O(n^2), but the interviewer wanted an algorithm that was O(n).

user84405
  • 23
  • 1
  • 5

2 Answers2

2

A useful approach is to compute the cumulative sum of your array.

This means that each entry in the cumulative sum array is the sum of all previous prices.

This is useful because you can then generate the sum over any particular subarray of your input using a single subtraction.

Note that when a new input arrives, you only need 1 addition to compute the new cumulative sum (because you simply add the new element to the old cumulative sum).

Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75
  • Interesting concept. You are saying to create another array with same number of entries as the stock prices, but the values containing the cumulative sum? That way, if I want to compute the sum over the past week, all I have to do is take the latest value of the cumulative sum array and subtract it by the value corresponding to one week ago, and average it over the number of entries. Thank you. – user84405 Oct 20 '17 at 14:07
  • 1
    That's a nice approach but requires some maintenance mechanism to handle eventual overflow (you can't add forever). – Amit Oct 20 '17 at 14:10
  • @Amit Good point: If you scale the prices to become integers you can use standard wraparound arithmetic and it should compute the right answer (providing the sum fits within the size of the datatype) – Peter de Rivaz Oct 20 '17 at 14:44
0

Another approach is akin to computing skew in Genomics.

If you want to compute the average over the past week, create a variable that contains the sum over a moving window. When an entry is created, add the entry to the above sum variable, and subtract the oldest entry in the moving window from it. Since the size of the window is constant, the average over the past week is just the moving sum over the number of entries in the past week.

user84405
  • 23
  • 1
  • 5