Withdrawal patterns in Blockchain / Solidity - Time & Space 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.
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 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).
As the number of users increases, the number of withdrawal operations grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 withdrawal checks and transfers |
| 100 | 100 withdrawal checks and transfers |
| 1000 | 1000 withdrawal checks and transfers |
Pattern observation: The work grows directly with the number of users; doubling users doubles the work.
Time Complexity: O(n)
This means the time to complete all withdrawals grows in a straight line with the number of users.
[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.
Understanding how withdrawal operations scale helps you explain how blockchain contracts handle many users efficiently and safely.
"What if we batch withdrawals so multiple users are paid in one transaction? How would the time complexity change?"