927. Ledger Bank

Medium3.5 points estimatedDesignArraySimulation4 hints

A tiny ledger keeps the balances of n accounts numbered from 1. Build LedgerBank whose constructor receives balance, where balance[i-1] is the money in account i.

  • transfer(src, dst, money) moves money from src to dst. It fails if either account number is outside 1..n, if the two accounts are the same, or if src holds less than money.
  • deposit(account, money) adds money; it fails only if the account does not exist.
  • withdraw(account, money) removes money; it fails if the account does not exist or holds too little.

Each method returns true when the operation was carried out and false when it was rejected. A rejected call changes nothing.

Example 1

Input:
operations = ["LedgerBank","withdraw","transfer","transfer","deposit","withdraw","deposit"]arguments = [[[40,15,0]],[2,20],[1,3,25],[3,2,26],[2,5],[2,20],[4,10]]
Output:
[null,false,true,false,true,true,false]
Explanation:

Account 2 holds 15 so a 20 withdrawal fails. Moving 25 from account 1 to 3 works, but account 3 then has 25 and cannot send 26. After depositing 5 into account 2 it holds 20, so withdrawing 20 now succeeds, while account 4 does not exist.

Example 2

Input:
operations = ["LedgerBank","transfer","withdraw","withdraw","deposit"]arguments = [[[7]],[1,1,3],[1,7],[1,1],[1,1000000000000]]
Output:
[null,false,true,false,true]
Explanation:

A transfer from an account to itself is rejected. Withdrawing all 7 works, withdrawing one more fails, and a huge deposit is accepted.

Constraints

1 ≤ n ≤ 105

0 ≤ balance[i] ≤ 1012

1 ≤ money ≤ 1012; account numbers may be any int in 0..n+1

At most 2000 calls; balances always stay below 9 * 1015

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.

Expected complexity

Time
O(1) per call
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.