0
0
Blockchain / Solidityprogramming~5 mins

Withdrawal patterns in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Withdrawal patterns
O(n)
Understanding Time Complexity

When working with withdrawal patterns in blockchain, it's important to see how the time to process withdrawals changes as more users request funds.

We want to know how the number of withdrawal requests affects the work the system must do.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function withdrawAll(address[] memory users) public {
  for (uint i = 0; i < users.length; i++) {
    uint amount = balances[users[i]];
    if (amount > 0) {
      balances[users[i]] = 0;
      payable(users[i]).transfer(amount);
    }
  }
}
    

This code processes withdrawals for a list of users by sending them their balance one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the users array to process each withdrawal.
  • How many times: Once for each user in the list (users.length times).
How Execution Grows With Input

As the number of users increases, the number of withdrawal operations grows in the same way.

Input Size (n)Approx. Operations
1010 withdrawal checks and transfers
100100 withdrawal checks and transfers
10001000 withdrawal checks and transfers

Pattern observation: The work grows directly with the number of users; doubling users doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete all withdrawals grows in a straight line with the number of users.

Common Mistake

[X] Wrong: "The withdrawal time stays the same no matter how many users there are."

[OK] Correct: Each user requires a separate withdrawal step, so more users mean more work and more time.

Interview Connect

Understanding how withdrawal operations scale helps you explain how blockchain contracts handle many users efficiently and safely.

Self-Check

"What if we batch withdrawals so multiple users are paid in one transaction? How would the time complexity change?"