LeetCode 2066: Account Balance Solution

Master LeetCode problem 2066 (Account Balance), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2066. Account Balance

Medium

Problem Explanation

Explanation:

To solve this problem, we can use a hashmap to keep track of each account's balance. We will iterate through each transaction and update the balance for both the sender and receiver accordingly. Finally, we can iterate through the hashmap and return the account balances.

Algorithm:

  1. Create a hashmap balances to store the balance of each account.
  2. Iterate through each transaction:
    • Decrement the sender's balance by the transaction amount.
    • Increment the receiver's balance by the transaction amount.
  3. Iterate through the hashmap balances and add the account balances to a list.
  4. Return the list of account balances.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the number of transactions.

Space Complexity:

The space complexity of this algorithm is O(n), where n is the number of unique accounts.

:

Solution Code

import java.util.*;

class Solution {
    public List<Integer> accountBalances(List<List<Integer>> transactions) {
        Map<Integer, Integer> balances = new HashMap<>();
        
        for (List<Integer> transaction : transactions) {
            int sender = transaction.get(0);
            int receiver = transaction.get(1);
            int amount = transaction.get(2);
            
            balances.put(sender, balances.getOrDefault(sender, 0) - amount);
            balances.put(receiver, balances.getOrDefault(receiver, 0) + amount);
        }
        
        List<Integer> result = new ArrayList<>();
        for (int balance : balances.values()) {
            result.add(balance);
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2066 (Account Balance)?

This page provides optimized solutions for LeetCode problem 2066 (Account Balance) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2066 (Account Balance)?

The time complexity for LeetCode 2066 (Account Balance) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2066 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2066 in Java, C++, or Python.

Back to LeetCode Solutions