#2043

Simple Bank System

Medium
ArrayHash TableDesignSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

This approach uses direct indexing to access account balances, ensuring efficient transactions with constant time complexity for each operation. We only check the necessary conditions without redundant checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize the bank with the given balance array.
  2. 2Step 2: For each transaction, validate the account numbers and check the balance only when necessary.
  3. 3Step 3: Update the balances directly if the transaction is valid.
solution.py22 lines
1class Bank:
2    def __init__(self, balance):
3        self.balance = balance
4
5    def transfer(self, account1, account2, money):
6        if 1 <= account1 <= len(self.balance) and 1 <= account2 <= len(self.balance) and self.balance[account1 - 1] >= money:
7            self.balance[account1 - 1] -= money
8            self.balance[account2 - 1] += money
9            return True
10        return False
11
12    def deposit(self, account, money):
13        if 1 <= account <= len(self.balance):
14            self.balance[account - 1] += money
15            return True
16        return False
17
18    def withdraw(self, account, money):
19        if 1 <= account <= len(self.balance) and self.balance[account - 1] >= money:
20            self.balance[account - 1] -= money
21            return True
22        return False

Complexity note: The complexity is O(n) for initializing the bank and O(1) for each transaction, as we directly access the balance array without nested loops.

  • 1Direct indexing allows for efficient access and updates to account balances.
  • 2Validating transactions requires careful checks on account numbers and balances.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.