Payment Approval and Partial Capture
Problem statement
Process a finite ordered batch of payment commands. Every command has exactly five string fields, in these forms:
["CREATE", id, payer, payee, amount]["APPROVE", id, "", "", amount]["CAPTURE", id, "", "", amount]["CANCEL", id, "", "", ""]
For this exercise, each payment starts absent. Apply the following deterministic rules:
CREATErequires an unused ID, nonempty payer and payee, and a positive amount. Its state becomesCREATED. A used ID cannot be reused, even after cancellation.APPROVEis valid only inCREATED. It records one positive approved amount no greater than the created amount and changes the state toAPPROVED.CAPTUREis valid only inAPPROVEDorPARTIALLY_CAPTURED. Its positive amount adds to the captured total without exceeding the approved amount. The new state isSUCCEEDEDwhen the total equals the approved amount, otherwisePARTIALLY_CAPTURED.CANCELacts only on its named ID and is valid only inCREATED. Its state becomesCANCELLED.
Return one string per command: the resulting state for a valid command, or "ERROR" for an invalid command. Invalid commands do not change any payment. Unknown IDs, repeated approval, over-capture and actions after success or cancellation are invalid. Do not add balances, refunds, fees, or external payment-provider behavior.
Function
processPayments(commands: String[][]) → String[]Examples
Example 1
commands = [["CREATE","p1","alice","bob","100"],["APPROVE","p1","","","80"],["CAPTURE","p1","","","30"],["CAPTURE","p1","","","50"],["CANCEL","p1","","",""]]return = ["CREATED","APPROVED","PARTIALLY_CAPTURED","SUCCEEDED","ERROR"]The payment is approved for 80 units, then captures 30 and 50. It succeeds and cannot then be cancelled.
Example 2
commands = [["CREATE","p1","a","b","10"],["CAPTURE","p1","","","3"],["APPROVE","p1","","","11"],["CANCEL","p1","","",""],["CREATE","p1","a","b","5"]]return = ["CREATED","ERROR","ERROR","CANCELLED","ERROR"]Capture before approval and approval beyond the created amount leave the payment unchanged. It can then be cancelled, but its ID remains used.
Example 3
commands = []return = []An empty batch produces no responses.
Constraints
- For this exercise, assume
0 <= commands.length <= 10^4. - Every row has five fields and uses one of the four command names above.
- IDs are nonempty ASCII strings of at most 20 characters. Payer/payee fields for CREATE have at most 20 characters; unused fields are empty.
- Every nonempty amount field is a decimal integer in
[-10^9,10^9]. Currency amounts are integral units.