Staking mechanisms in Blockchain / Solidity - Time & Space Complexity
When we look at staking mechanisms in blockchain, we want to know how the time to process grows as more users stake tokens.
We ask: How does the system handle more stakers efficiently?
Analyze the time complexity of the following code snippet.
function distributeRewards(stakers) {
let totalStake = 0;
for (let i = 0; i < stakers.length; i++) {
totalStake += stakers[i].amount;
}
for (let i = 0; i < stakers.length; i++) {
stakers[i].reward = (stakers[i].amount / totalStake) * 1000;
}
}
This code calculates the total tokens staked and then distributes rewards proportionally to each staker.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two separate loops over the stakers array.
- How many times: Each loop runs once over all stakers, so twice in total.
As the number of stakers grows, the code does more work by looping through all stakers twice.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (2 loops x 10) |
| 100 | About 200 operations (2 loops x 100) |
| 1000 | About 2000 operations (2 loops x 1000) |
Pattern observation: The operations grow roughly in direct proportion to the number of stakers.
Time Complexity: O(n)
This means the time to distribute rewards grows linearly as more people stake tokens.
[X] Wrong: "Because there are two loops, the time complexity is O(n²)."
[OK] Correct: The loops run one after another, not nested, so their times add up, not multiply.
Understanding how staking reward calculations scale helps you explain efficient blockchain designs clearly and confidently.
What if we combined the two loops into one? How would the time complexity change?