Task 3
solution(trades) should compute the volume-weighted average price (VWAP) per
instrument, using only trades with positive quantity:
VWAP = sum(price_i * quantity_i) / sum(quantity_i)
(instrument, price, quantity).
price is never negative. quantity may be positive, negative, zero, or
fractional.null, or placeholder entry.#include <vector>
#include <string>
#include <tuple>
#include <map>
using namespace std;
// Trade = {instrument, price, quantity}
using Trade = tuple<string, double, double>;
// Result: instrument -> volume-weighted average price, using only trades
// with positive quantity (see README)
using Result = map<string, double>;
Result solution(vector<Trade>& trades) {
map<string, double> totals;
map<string, double> quantities;
for (auto& [instrument, price, quantity] : trades) {
if (quantity < 0) continue; // <-- BUG
totals[instrument] += price * quantity;
quantities[instrument] += quantity;
}
Result result;
for (auto& [instrument, total] : totals) {
result[instrument] = total / quantities[instrument];
}
return result;
}
The filter is if (quantity < 0) continue;, which only skips negative
quantities. The spec says to use only trades with positive quantity —
i.e. strictly > 0. Since quantity can also be exactly 0, the buggy
filter lets zero-quantity trades slip through.
A zero-quantity trade contributes price * 0 = 0 to totals[instrument]
and 0 to quantities[instrument]. That alone looks harmless — but if an
instrument has no trades with positive quantity (only zero and/or
negative ones), the buggy code still creates an entry for it in totals
(via the += on a zero-quantity trade), which means:
result loop (which iterates
over totals), violating "must be omitted entirely."0 / 0 → NaN, which gets returned to the
caller as the instrument's price.vector<Trade> trades = {
{"AAPL", 100.0, 0.0}, // only a zero-quantity trade
{"MSFT", 50.0, 10.0},
{"MSFT", 60.0, -5.0} // negative, correctly excluded either way
};
Buggy output:
Result size: 2
AAPL -> -nan
MSFT -> 50
AAPL should not appear at all — it has no trade with strictly positive
quantity.
LSEG - London Stock Exchange • Pending
LSEG - London Stock Exchange • Pending
LSEG - London Stock Exchange • Pending
LSEG - London Stock Exchange • Pending