Simple Bank System — LeetCode 2043 Python Solution

MediumDesignArrayHash TableSimulation
Problem
#2043
Pattern
Hash Map
Reading time
6 min

The problem

You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n.

Example

Input
["Bank", "withdraw", "transfer", "deposit", "transfer", "withdraw"]
Output
[null, true, true, true, false, false]
Explanation
Bank bank = new Bank([10, 100, 20, 50, 30]);

Python solution

Python
class Bank:
    def __init__(self, balance: List[int]):
        self.balance = balance
        self.n = len(balance)

    def transfer(self, account1: int, account2: int, money: int) -> bool:
        if account1 > self.n or account2 > self.n or self.balance[account1 - 1] < money:
            return False
        self.balance[account1 - 1] -= money
        self.balance[account2 - 1] += money
        return True

    def deposit(self, account: int, money: int) -> bool:
        if account > self.n:
            return False
        self.balance[account - 1] += money
        return True

    def withdraw(self, account: int, money: int) -> bool:
        if account > self.n or self.balance[account - 1] < money:
            return False
        self.balance[account - 1] -= money
        return True


# Your Bank object will be instantiated and called as such:
# obj = Bank(balance)
# param_1 = obj.transfer(account1,account2,money)
# param_2 = obj.deposit(account,money)
# param_3 = obj.withdraw(account,money)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2043. Simple Bank System is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2043. Simple Bank System?
LeetCode 2043. Simple Bank System is rated Medium on LeetCode.
What is the time complexity of LeetCode 2043. Simple Bank System?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2043. Simple Bank System?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2043. Simple Bank System cover?
LeetCode 2043. Simple Bank System is tagged Design, Array, Hash Table and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview