Streaming Average
Updated
Problem statement
A trading system receives a stream of integer readings, for example price changes measured in ticks, which can be negative. At any moment someone may ask for the average of every reading so far.
You are given operations, a list of operations to apply in order to a stream that starts empty. Each operation is one of:
["add", v]: a new value arrives.vis an integer written as a decimal string, such as"12"or"-7".["average"]: report the average (arithmetic mean) of all values added so far: their sum divided by how many there are.
Every value counts, including repeated ones. Return an array with one value for each "average" operation, in the order the operations appear. A value is accepted if it differs from the exact average a by at most 10^-9 × max(1, |a|).
Function
streamingAverage(operations: String[][]) → double[]Examples
Example 1
operations = [["add","4"],["add","10"],["average"],["add","-2"],["average"]]return = [7.0,4.0]- After 4 and 10 the average is
(4 + 10) / 2 = 7. - After -2 it is
(4 + 10 - 2) / 3 = 12 / 3 = 4.
Example 2
operations = [["add","1"],["add","2"],["add","2"],["average"],["average"]]return = [1.6666666666666667,1.6666666666666667](1 + 2 + 2) / 3 = 5 / 3, about1.6667. Asking again without a new value gives the same answer.
Example 3
operations = [["add","-3"],["add","-4"],["average"]]return = [-3.5](-3 - 4) / 2 = -3.5. Integer division would give-3or-4, depending on the language.
Constraints
2 <= operations.length <= 5000- Each
operations[i]is either["add", v]or["average"]. - Each value
vis an integer from-10^9to10^9, written in decimal digits with no leading zeros and a minus sign in front when it is negative. Zero is written as"0". - Between
1and500of the operations are"average", and the first operation is an"add".
More Xantium Phone Screen questions
Similar questions at other companies
- Constant-Time Weighted Pick with an Alias TableEtched · PHONE SCREEN
- Text Embedding and Vector SearchNike, Inc. · PHONE SCREEN · ONSITE INTERVIEWNike, Inc. interview questions
- In-Memory URL ShortenerRevolut · PHONE SCREENRevolut interview questions
- Accumulate Numeric Value ObjectsSquarepoint Capital · ONSITE INTERVIEWSquarepoint Capital interview questions
- REST API: Discounted PriceOracle · OAOracle interview questions
- Real-Time Temperature Window StatisticsGoogle · ONSITE INTERVIEWGoogle interview questions
- Pro-Rata Order BookIMC Trading · ONSITE INTERVIEWIMC Trading interview questions
- Stock System with Updates and Percentage ChangeLead Bank · ONSITE INTERVIEWLead Bank interview questions
- Equity Price History with O(1) StatisticsBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Shuffle With Given Random DrawsMicrosoft · ONSITE INTERVIEWMicrosoft interview questions