Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created October 26, 2025 22:52
Show Gist options
  • Select an option

  • Save Ifihan/6fb7038add9b1d0eea2c0c5f42312d7f to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/6fb7038add9b1d0eea2c0c5f42312d7f to your computer and use it in GitHub Desktop.
Simple Bank System

Question

Approach

I store the balances in a zero-indexed Python list but treat account numbers as 1-indexed. For every operation I first check that the account indices are within [1, n]. For withdraw and transfer I additionally check that the source account has enough balance. All updates are done in-place, and each operation runs in constant time.

Implementation

class Bank:

    def __init__(self, balance: List[int]):
        self.balance = balance

    def _valid(self, account: int) -> bool:
        return 1 <= account <= len(self.balance)

    def transfer(self, account1: int, account2: int, money: int) -> bool:
        if not (self._valid(account1) and self._valid(account2)):
            return False
        i, j = account1 - 1, account2 - 1
        if self.balance[i] < money:
            return False
        self.balance[i] -= money
        self.balance[j] += money
        return True

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

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

Complexities

  • Time: O(1)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment