Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.
When withdrawing, the machine prioritizes using banknotes of larger values.
$300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.$600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.Implement the ATM class:
ATM() Initializes the ATM object.void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500.int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).Example 1:
Input
["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"]
[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]
Output
[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]
Explanation
ATM atm = new ATM();
atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,
// and 1 $500 banknote.
atm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote
// and 1 $500 banknote. The banknotes left over in the
// machine are [0,0,0,2,0].
atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.
// The banknotes in the machine are now [0,1,0,3,1].
atm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote
// and then be unable to complete the remaining $100,
// so the withdraw request will be rejected.
// Since the request is rejected, the number of banknotes
// in the machine is not modified.
atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote
// and 1 $500 banknote.
Constraints:
banknotesCount.length == 50 <= banknotesCount[i] <= 1091 <= amount <= 1095000 calls in total will be made to withdraw and deposit.withdraw and deposit.banknotesCount[i] in all deposits doesn't exceed 109Problem summary: There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of larger values. For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes. However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote. Implement the ATM class: ATM() Initializes the ATM object. void deposit(int[] banknotesCount) Deposits
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy · Design
["ATM","deposit","withdraw","deposit","withdraw","withdraw"] [[],[[0,0,1,2,1]],[600],[[0,1,0,1,1]],[600],[550]]
simple-bank-system)minimum-number-of-operations-to-convert-time)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2241: Design an ATM Machine
class ATM {
private int[] d = {20, 50, 100, 200, 500};
private int m = d.length;
private long[] cnt = new long[5];
public ATM() {
}
public void deposit(int[] banknotesCount) {
for (int i = 0; i < banknotesCount.length; ++i) {
cnt[i] += banknotesCount[i];
}
}
public int[] withdraw(int amount) {
int[] ans = new int[m];
for (int i = m - 1; i >= 0; --i) {
ans[i] = (int) Math.min(amount / d[i], cnt[i]);
amount -= ans[i] * d[i];
}
if (amount > 0) {
return new int[] {-1};
}
for (int i = 0; i < m; ++i) {
cnt[i] -= ans[i];
}
return ans;
}
}
/**
* Your ATM object will be instantiated and called as such:
* ATM obj = new ATM();
* obj.deposit(banknotesCount);
* int[] param_2 = obj.withdraw(amount);
*/
// Accepted solution for LeetCode #2241: Design an ATM Machine
var d = [...]int{20, 50, 100, 200, 500}
const m = len(d)
type ATM [m]int
func Constructor() ATM {
return ATM{}
}
func (this *ATM) Deposit(banknotesCount []int) {
for i, x := range banknotesCount {
this[i] += x
}
}
func (this *ATM) Withdraw(amount int) []int {
ans := make([]int, m)
for i := m - 1; i >= 0; i-- {
ans[i] = min(amount/d[i], this[i])
amount -= ans[i] * d[i]
}
if amount > 0 {
return []int{-1}
}
for i, x := range ans {
this[i] -= x
}
return ans
}
/**
* Your ATM object will be instantiated and called as such:
* obj := Constructor();
* obj.Deposit(banknotesCount);
* param_2 := obj.Withdraw(amount);
*/
# Accepted solution for LeetCode #2241: Design an ATM Machine
class ATM:
def __init__(self):
self.d = [20, 50, 100, 200, 500]
self.m = len(self.d)
self.cnt = [0] * self.m
def deposit(self, banknotesCount: List[int]) -> None:
for i, x in enumerate(banknotesCount):
self.cnt[i] += x
def withdraw(self, amount: int) -> List[int]:
ans = [0] * self.m
for i in reversed(range(self.m)):
ans[i] = min(amount // self.d[i], self.cnt[i])
amount -= ans[i] * self.d[i]
if amount > 0:
return [-1]
for i, x in enumerate(ans):
self.cnt[i] -= x
return ans
# Your ATM object will be instantiated and called as such:
# obj = ATM()
# obj.deposit(banknotesCount)
# param_2 = obj.withdraw(amount)
// Accepted solution for LeetCode #2241: Design an ATM Machine
/**
* [2241] Design an ATM Machine
*
* There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.
* When withdrawing, the machine prioritizes using banknotes of larger values.
*
* For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.
* However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.
*
* Implement the ATM class:
*
* ATM() Initializes the ATM object.
* void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500.
* int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).
*
*
* Example 1:
*
* Input
* ["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"]
* [[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]
* Output
* [null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]
* Explanation
* ATM atm = new ATM();
* atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,
* // and 1 $500 banknote.
* atm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote
* // and 1 $500 banknote. The banknotes left over in the
* // machine are [0,0,0,2,0].
* atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.
* // The banknotes in the machine are now [0,1,0,3,1].
* atm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote
* // and then be unable to complete the remaining $100,
* // so the withdraw request will be rejected.
* // Since the request is rejected, the number of banknotes
* // in the machine is not modified.
* atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote
* // and 1 $500 banknote.
*
* Constraints:
*
* banknotesCount.length == 5
* 0 <= banknotesCount[i] <= 10^9
* 1 <= amount <= 10^9
* At most 5000 calls in total will be made to withdraw and deposit.
* At least one call will be made to each function withdraw and deposit.
* Sum of banknotesCount[i] in all deposits doesn't exceed 10^9
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/design-an-atm-machine/
// discuss: https://leetcode.com/problems/design-an-atm-machine/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
struct ATM {
banknotes: [i64; 5],
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl ATM {
fn new() -> Self {
Self { banknotes: [0; 5] }
}
fn deposit(&mut self, banknotes_count: Vec<i32>) {
for (i, &x) in banknotes_count.iter().enumerate() {
self.banknotes[i] += x as i64;
}
}
fn withdraw(&mut self, amount: i32) -> Vec<i32> {
let mut banknotes_count = vec![0; 5];
let mut amount = amount as i64;
for (i, &x) in self.banknotes.iter().enumerate().rev() {
let count = amount / [20, 50, 100, 200, 500][i];
let count = count.min(x);
banknotes_count[i] = count;
amount -= count * [20, 50, 100, 200, 500][i];
}
if amount == 0 {
for (i, &x) in banknotes_count.iter().enumerate() {
self.banknotes[i] -= x;
}
banknotes_count.iter().map(|&x| x as i32).collect()
} else {
vec![-1]
}
}
}
/**
* Your ATM object will be instantiated and called as such:
* let obj = ATM::new();
* obj.deposit(banknotesCount);
* let ret_2: Vec<i32> = obj.withdraw(amount);
*/
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2241_example_1() {
let mut atm = ATM::new();
atm.deposit(vec![0, 0, 1, 2, 1]); // Deposits 1 $100 banknote, 2 $200 banknotes,
// and 1 $500 banknote.
assert_eq!(atm.withdraw(600), vec![0, 0, 1, 0, 1]); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote
// and 1 $500 banknote. The banknotes left over in the
// machine are [0,0,0,2,0].
atm.deposit(vec![0, 1, 0, 3, 1]); // Deposits 1 $50, $200, and $500 banknote.
// The banknotes in the machine are now [0,1,0,3,1].
assert_eq!(atm.withdraw(600), vec![-1]); // Returns [-1]. The machine will try to use a $500 banknote
// and then be unable to complete the remaining $100,
// so the withdraw request will be rejected.
// Since the request is rejected, the number of banknotes
// in the machine is not modified.
assert_eq!(atm.withdraw(550), vec![0, 1, 0, 0, 1]); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote
// and 1 $500 banknote.
}
}
// Accepted solution for LeetCode #2241: Design an ATM Machine
const d: number[] = [20, 50, 100, 200, 500];
const m = d.length;
class ATM {
private cnt: number[];
constructor() {
this.cnt = Array(m).fill(0);
}
deposit(banknotesCount: number[]): void {
for (let i = 0; i < banknotesCount.length; ++i) {
this.cnt[i] += banknotesCount[i];
}
}
withdraw(amount: number): number[] {
const ans: number[] = Array(m).fill(0);
for (let i = m - 1; i >= 0; --i) {
ans[i] = Math.min(Math.floor(amount / d[i]), this.cnt[i]);
amount -= ans[i] * d[i];
}
if (amount > 0) {
return [-1];
}
for (let i = 0; i < m; ++i) {
this.cnt[i] -= ans[i];
}
return ans;
}
}
/**
* Your ATM object will be instantiated and called as such:
* var obj = new ATM()
* obj.deposit(banknotesCount)
* var param_2 = obj.withdraw(amount)
*/
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.