Capital Gains Tax from Trades
Learn this problemProblem statement
Process chronological stock trades and calculate the tax on realized profit. Each trade is a comma-separated string:
date,ticker,side,shares,pricesideisBfor a buy orSfor a sell.sharesis a positive integer.priceis a non-negative decimal amount with at most two digits after the decimal point.
Track positions separately by ticker and match closing shares against open lots in first-in, first-out order. A sell closes long shares before opening a short position; a buy closes short shares before opening a long position. A single trade may close an existing position and open the opposite position with its remaining shares.
For a closed long share, realized profit is sell price - buy price. For a closed short share, realized profit is short-sale price - cover price. Open lots do not contribute realized profit.
Add realized profit across every ticker. Tax is 25% of the positive total; when the total is zero or negative, tax is zero. Return the tax as US currency with a leading $, comma separators, and exactly two decimal places.
Function
calculateTax(trades: String[]) → StringExamples
Example 1
trades = ["2024-01-01,ABC,B,10,100.00","2024-01-02,ABC,S,4,120.00"]return = "$20.00"Selling four shares realizes 4 * (120 - 100) = $80. Tax is 25%, or $20.00.
Example 2
trades = ["2024-01-01,ABC,S,5,50.00","2024-01-02,ABC,B,5,60.00"]return = "$0.00"Covering the short realizes a loss of 5 * (50 - 60) = -$50, so the tax is zero.
Constraints
trades.length >= 1.- Trades are ordered chronologically.
- Every trade uses the five-field format described above.
- Every testcase produces a tax amount that is an exact number of cents.
More Arcesium problems
- Ordered Payload ReleaseONSITE INTERVIEW · Seen Jul 2026
- Decode Numeric StringONSITE INTERVIEW · Seen Jun 2026
- Tree Ancestor QueriesONSITE INTERVIEW · Seen Jun 2026
- City Infection NumberOA · Seen Jul 2025
- Minimum Tunnel Crossing TimeOA · Seen Jul 2025
- Product of Subset MaximaOA · Seen Jul 2025
- Reconstruct the Root StreamOA · Seen Jul 2025
- Add DigitsOA · Seen Aug 2023