0
0
Blockchain / Solidityprogramming~5 mins

Balance checking in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Balance checking
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of accounts grows, the time to find a balance grows roughly the same way.

Input Size (n)Approx. Operations
10Up to 10 checks
100Up to 100 checks
1000Up to 1000 checks

Pattern observation: The number of checks grows directly with the number of accounts.

Final Time Complexity

Time Complexity: O(n)

This means the time to find a balance grows in a straight line with the number of accounts.

Common Mistake

[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.

Interview Connect

Understanding how balance checking scales helps you explain how blockchain systems handle many users efficiently.

Self-Check

"What if we stored accounts in a map (key-value store) instead of a list? How would the time complexity change?"