KatInterview

Ledger Replay: Deposits, Withdrawals and Percentage Rewards

Data Structure DesignAuto-graded · 20 test cases
EasyAuto-gradedData Structure Designsimulationstate-managementvalidation

Last updated

Simulate a single account balance across a sequence of operations, silently rejecting invalid ones, and report the balance after each step.

You are given a starting account balance and a list of operations to run against it, in order. Each operation has a name and a numeric amount. Return the account balance observed after each operation.

Inputs

  • start_balance (float): the balance before any operation runs.
  • actions (list of strings): the operation names.
  • values (list of floats): values[i] is the amount for actions[i].

Operations

NameAllowed whenEffect on the balance
"Deposit"value >= 0add value
"Withdraw"value >= 0 and value <= balancesubtract value
"CashBack"value >= 0add balance * value / 100.0 (value is a percentage of the current balance)

Rules

  • If an operation's condition is not met, it is rejected. A rejected operation leaves the balance unchanged and does not raise an error.
  • After every processed operation, accepted or rejected, append the current balance to the result. The result therefore has one entry per processed operation.
  • Operations are paired with amounts by position. If the two lists have different lengths, only the first min(len(actions), len(values)) pairs are processed and the rest are ignored.
  • If an operation name is anything other than the three above, raise ValueError.
  • Use ordinary floating-point arithmetic with no rounding, and apply the formulas exactly as written above.
  • Withdrawing exactly the current balance is allowed and leaves 0.
  • A zero amount is valid for every operation, subject to the conditions in the table.
  • Order matters, because CashBack uses the balance at the moment it runs.

Return a list of floats (or numbers) with the balance after each processed operation.

Constraints

  • 0 <= len(actions), len(values) <= 10^5
  • Amounts are finite numbers and may be negative (such amounts are rejected).
  • Operation names are case-sensitive strings.
  • Do not round results.

Examples

Example 1

Input: replay_account_actions(100, ['Deposit', 'Withdraw', 'CashBack'], [50, 30, 10])

Output: [150, 120, 132]

Example 2

Input: replay_account_actions(100, ['Withdraw', 'Deposit', 'Withdraw'], [150, 50, 100])

Output: [100, 150, 50]

Hints

Hint 1

Only one value changes over time: the current balance. Walk through the pairs of (action, value) in order and keep updating it.

Hint 2

Decide validity before changing anything. A rejected action must still add the unchanged balance to the output so the output length matches the number of processed pairs.

Hint 3

Use `<=` when comparing a withdrawal to the balance so the full balance can be withdrawn, divide the cashback percentage by 100, and raise `ValueError` for any unrecognized name.