Whole-Share Rebalancing for a Fractional Stock Ledger
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Simulate customer buy and sell orders against fractional inventory, trading only whole shares with the market, and emit ordered transfer logs and final balances.
A brokerage holds a stock inventory per symbol, measured in hundredths of a share. For example, 50 means 0.50 shares. Customers buy from it and sell to it, but the outside market only accepts whole shares, so every market trade must be a multiple of 100 hundredths. After every order, each symbol's inventory must be in the range 0 <= q < 100.
Implement rebalance_ledger(orders, holdings). It returns a list of exactly two lists:
- The final inventory strings, in the same order as
holdings. - The ordered list of transfer log strings.
Input format
holdings: a list of stringsSYMBOL/quantity. The quantity is an integer number of hundredths of a share in[0, 99]. Symbols are unique, nonempty, and made of ASCII letters, digits, and underscores.orders: a list of stringsSYMBOL/SIDE/amount/price, processed in the given order.SIDEisB(the customer buys from the brokerage) orS(the customer sells to the brokerage).amountis either a plain positive integer, meaning that many hundredths of a share, or a positive integer prefixed with$, meaning that many cents of money.priceis a positive integer number of cents per whole share.- For a
$order, the share quantity in hundredths iscents * 100 / price. Test data guarantees this is always an exact integer, so no rounding is needed. - Every order symbol appears in
holdings.
Processing rules
Let q be the symbol's current inventory and a the order quantity in hundredths.
Customer buy (B)
- If
q < a, the brokerage first buys from the market the smallest multiple of 100 that makesq + m >= a. Log it as a market buy only ifm > 0. - Then it delivers all
ato the customer, logged as a customer sell. - New inventory is
q + m - a.
Customer sell (S)
- The brokerage first receives
afrom the customer, logged as a customer buy. Inventory becomesq + a. - It then sells to the market the largest multiple of 100 not exceeding that inventory. Log it only if that amount is greater than 0.
- New inventory is the remainder.
Log format
Each log entry is SYMBOL/quantity/side/contra:
quantityis a positive integer in hundredths. Never emit a zero-quantity log.sideisBorSfrom the brokerage's perspective (what the brokerage did).contraisMARKETorCUSTOMER.
Per order, logs appear in this order:
- Buy order: optional
SYMBOL/m/B/MARKET, thenSYMBOL/a/S/CUSTOMER. - Sell order:
SYMBOL/a/B/CUSTOMER, then optionalSYMBOL/m/S/MARKET.
Final inventory strings use the form SYMBOL/quantity. Symbols with no orders still appear, unchanged.
This models quantity accounting only; prices, fees, and settlement are not simulated.
Constraints
- At most 100000 orders and 1000 symbols.
- All numeric values in the input are at most 1000000, and order quantities are positive.
- Use integer arithmetic only; do not use floating point.
$orders always convert to a whole number of hundredths.
Examples
Example 1
Input: rebalance_ledger(['ABC/B/150/1000', 'ABC/B/40/1000', 'ABC/S/75/1000'], ['ABC/0', 'XYZ/75'])
Output: [['ABC/85', 'XYZ/75'], ['ABC/200/B/MARKET', 'ABC/150/S/CUSTOMER', 'ABC/40/S/CUSTOMER', 'ABC/75/B/CUSTOMER']]
Example 2
Input: rebalance_ledger(['ABC/B/50/1000'], ['ABC/20'])
Output: [['ABC/70'], ['ABC/100/B/MARKET', 'ABC/50/S/CUSTOMER']]
Example 3
Input: rebalance_ledger(['ABC/S/50/1000'], ['ABC/75'])
Output: [['ABC/25'], ['ABC/50/B/CUSTOMER', 'ABC/100/S/MARKET']]
Hints
Hint 1
Keep everything as integers in hundredths of a share. Parse the `$` prefix separately and convert cents to hundredths with `cents * 100 // price`.
Hint 2
For a buy, only the shortfall `a - q` matters. The smallest multiple of 100 covering a positive shortfall is a ceiling division, and if there is no shortfall the market trade is zero.
Hint 3
For a sell, add the shares first, then sell off `(q // 100) * 100`. Only append market logs when the amount is positive, and keep a separate list of symbols to preserve the final output order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Maintain one invariant per symbol: after each order, inventory q satisfies 0 <= q < 100. Because the market only trades multiples of 100, each order has exactly one valid market trade.
- Customer buy of
a: we needq + m >= awithma multiple of 100. Choosing the smallest suchmism = max(0, ceil((a - q) / 100)) * 100. Using integer arithmetic,ceil(x / 100)is(x + 99) // 100forx > 0. Log the market buy ifm > 0, then log the customer delivery ofa. The new inventory isq + m - a. - Customer sell of
a: log the customer intake, setq' = q + a, then sellm = (q' // 100) * 100to the market, logging only ifm > 0. The new inventory isq' - m = q' mod 100.
For $ orders, convert cents to hundredths with cents * 100 // price (guaranteed exact), then process like any other order.
Why it is correct
- In the buy case,
q + m >= aby construction, so inventory never goes negative. Sincemis minimal, the leftover is under 100, otherwise one fewer share would have sufficed. - In the sell case, the leftover is
q' mod 100, which is in[0, 100)by definition. - For a fixed customer transfer, exactly one residual in
[0, 100)is congruent to the new inventory modulo 100, so the market quantity is uniquely determined and matches the expected output. - Logs are emitted in the required order, and zero-quantity logs are suppressed by the
ifguards. - In languages where
/and%truncate toward zero, negative operands need care. Here the ceiling expression is only applied to a positive shortfall, andmax(0, ...)handles the rest.
Keep a separate list of symbols so the final output follows the input order, including symbols that never traded.
Complexity
- Time: O(N + S) for N orders and S symbols, plus the string parsing and formatting cost. Each order is O(1).
- Space: O(S) for the inventory map, plus up to 2N log strings in the output.
Reference solution
from typing import List
def rebalance_ledger(orders: List[str], holdings: List[str]) -> List[List[str]]:
symbols = []
qty = {}
for entry in holdings:
sym, q = entry.split('/')
symbols.append(sym)
qty[sym] = int(q)
logs = []
for order in orders:
sym, side, amount_text, price_text = order.split('/')
price = int(price_text)
if amount_text.startswith('$'):
cents = int(amount_text[1:])
numerator = cents * 100
if numerator % price != 0:
raise ValueError('Dollar order must convert to whole hundredths')
amount = numerator // price
else:
amount = int(amount_text)
cur = qty[sym]
if side == 'B':
market_buy = max(0, (amount - cur + 99) // 100) * 100
if market_buy:
logs.append(f'{sym}/{market_buy}/B/MARKET')
logs.append(f'{sym}/{amount}/S/CUSTOMER')
cur = cur + market_buy - amount
else:
logs.append(f'{sym}/{amount}/B/CUSTOMER')
cur += amount
market_sell = (cur // 100) * 100
if market_sell:
logs.append(f'{sym}/{market_sell}/S/MARKET')
cur -= market_sell
qty[sym] = cur
final = [f'{s}/{qty[s]}' for s in symbols]
return [final, logs]