Asked at Wolverine Trading, Marshall Wace
Theory: Parsing and Data HygieneRead the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.
Available in Python and C++. You are solving it in C++. Switch to Python
Implement parse_order(s), a parser for order shorthand. B 100 AAPL @ 152.35
means buy 100 shares of AAPL at 152.35, and S 50 TSLA @ MKT means sell 50
TSLA at market. The parser never guesses: anything that does not match the
grammar exactly is rejected, not repaired.
Desks still pass orders around in this shorthand, in chat, in test fixtures and in legacy tools.
parse_order returns four values: side, which is "BUY"
or "SELL"; qty, an integer; symbol, the string; and price, which is
absent for a market order. If s is invalid, return nothing at all (the whole
result, not a field).
using Order = std::tuple<std::string, long long, std::string, std::optional<long long>>;
std::optional<Order> parse_order(const std::string& s);
A valid string returns {side, qty, symbol, price} with the price in
integer cents (152.35 is 15235, 7 is 700) and std::nullopt for a
market order; an invalid string returns std::nullopt for the whole
result.
A valid string is exactly five fields separated by single spaces, with
no leading or trailing whitespace: SIDE QTY SYMBOL @ PRICE.
SIDE: exactly B or S (case-sensitive; BUY or b are invalid).QTY: one or more digits, no leading zero, value greater than 0.SYMBOL: 1 to 6 uppercase letters A-Z only.@.PRICE: either exactly MKT (a market order, with no price), or one or more
digits optionally followed by . and one or two decimal digits, with
numeric value strictly greater than 0. So 152.35, 7 and 0.50 are
valid; .35, 152., 152.345, 0 and 0.00 are not.parse_order("B 100 AAPL @ 152.35");
// {"BUY", 100, "AAPL", 15235}
parse_order("S 50 TSLA @ MKT");
// {"SELL", 50, "TSLA", std::nullopt}
parse_order("B 100 aapl @ 152.35"); // std::nullopt, a lowercase symbol is invalid
parse_order("S 5 MSFT @ 401.10");
// {"SELL", 5, "MSFT", 40110}
s has length at most 100; a single pass is plenty.@, trailing
characters) must also be rejected.