Balance checking in Blockchain / Solidity - Time & Space Complexity
When checking a balance on a blockchain, it is important to know how the time to get that balance changes as the number of accounts grows.
We want to understand how long it takes to find the balance for one account when many accounts exist.
Analyze the time complexity of the following code snippet.
function getBalance(user) {
for (let i = 0; i < accounts.length; i++) {
if (accounts[i].address === user) {
return accounts[i].balance;
}
}
return 0;
}
This code looks through a list of accounts to find the balance of the given user address.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A loop that checks each account's address one by one.
- How many times: Up to the total number of accounts in the list.
As the number of accounts grows, the time to find a balance grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the number of accounts.
Time Complexity: O(n)
This means the time to find a balance grows in a straight line with the number of accounts.
[X] Wrong: "Checking a balance always takes the same time no matter how many accounts there are."
[OK] Correct: Because this code looks through each account one by one, more accounts mean more checks and more time.
Understanding how balance checking scales helps you explain how blockchain systems handle many users efficiently.
"What if we stored accounts in a map (key-value store) instead of a list? How would the time complexity change?"