Skip to main content
Back to problems
#2043
Medium Algorithms

Simple bank system

Array Hash Table Design Simulation
69.8% acceptance
Feb 25, 2026
630
318
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. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initial balance of balance[i]. Execute all the valid transactions. A transaction is valid if: The given account number(s) are between 1 and n, and The amount of money withdrawn or transferred from is less than or equal to the balance of the account. Implement the Bank class: Bank(long[] balance) Initializes the object with the 0-indexed integer array balance. boolean transfer(int account1, int account2, long money) Transfers money dollars from the account numbered account1 to the account numbered account2. Return true if the transaction was successful, false otherwise. boolean deposit(int account, long money) Deposit money dollars into the account numbered account. Return true if the transaction was successful, false otherwise. boolean withdraw(int account, long money) Withdraw money dollars from the account numbered account. Return true if the transaction was successful, false otherwise.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
struct Bank {
  balance: Vec<i64>,
}

impl Bank {
  fn new(balance: Vec<i64>) -> Self {
    Bank { balance }
  }

  fn valid(&self, account: i32) -> bool {
    let a = account as usize;
    a >= 1 && a <= self.balance.len()
  }

  fn transfer(&mut self, account1: i32, account2: i32, money: i64) -> bool {
    if !self.valid(account1) || !self.valid(account2) {
      return false;
    }
    let a1 = account1 as usize - 1;
    let a2 = account2 as usize - 1;
    if self.balance[a1] < money {
      return false;
    }
    self.balance[a1] -= money;
    self.balance[a2] += money;
    true
  }

  fn deposit(&mut self, account: i32, money: i64) -> bool {
    if !self.valid(account) {
      return false;
    }
    self.balance[account as usize - 1] += money;
    true
  }

  fn withdraw(&mut self, account: i32, money: i64) -> bool {
    if !self.valid(account) {
      return false;
    }
    let a = account as usize - 1;
    if self.balance[a] < money {
      return false;
    }
    self.balance[a] -= money;
    true
  }
}