Streaming VWAP
Updated
Problem statement
The volume-weighted average price (VWAP) of a group of trades is the total money traded divided by the total number of shares traded. For trades with prices p1, p2, ... and quantities q1, q2, ... it is (p1 × q1 + p2 × q2 + ...) / (q1 + q2 + ...). Large trades count for more than small ones.
Trades arrive one at a time. You are given operations, a list of operations to apply in order to a trade stream that starts empty. Each operation is one of:
["trade", p, q]: a trade ofqshares at pricephappens. Both are positive integers written as decimal strings.["vwap"]: report the VWAP of all trades so far.
Return an array with one value for each "vwap" operation, in the order the operations appear. A value is accepted if it differs from the exact VWAP v by at most 10^-9 × max(1, |v|).
Function
streamingVwap(operations: String[][]) → double[]Examples
Example 1
operations = [["trade","100","10"],["trade","102","30"],["vwap"],["trade","98","60"],["vwap"]]return = [101.5,99.4]- After two trades the total value is
100 × 10 + 102 × 30 = 4060over40shares, so the VWAP is4060 / 40 = 101.5. - The third trade adds
98 × 60 = 5880over60shares:(4060 + 5880) / (40 + 60) = 9940 / 100 = 99.4.
Example 2
operations = [["trade","50","7"],["vwap"],["vwap"]]return = [50.0,50.0]- With one trade the VWAP is its price,
50. Asking again without a new trade gives the same value.
Example 3
operations = [["trade","10","1"],["trade","11","2"],["vwap"]]return = [10.666666666666666](10 × 1 + 11 × 2) / (1 + 2) = 32 / 3, about10.6667. The plain average of the two prices would be10.5.
Constraints
2 <= operations.length <= 5000- Each
operations[i]is either["trade", p, q]or["vwap"]. - Each price
pand each quantityqis an integer from1to10^6, written in decimal digits with no leading zeros. - Between
1and500of the operations are"vwap", and the first operation is a"trade".
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