0
0
Blockchain / Solidityprogramming~5 mins

Staking mechanisms in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Staking mechanisms
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As the number of stakers grows, the code does more work by looping through all stakers twice.

Input Size (n)Approx. Operations
10About 20 operations (2 loops x 10)
100About 200 operations (2 loops x 100)
1000About 2000 operations (2 loops x 1000)

Pattern observation: The operations grow roughly in direct proportion to the number of stakers.

Final Time Complexity

Time Complexity: O(n)

This means the time to distribute rewards grows linearly as more people stake tokens.

Common Mistake

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

Interview Connect

Understanding how staking reward calculations scale helps you explain efficient blockchain designs clearly and confidently.

Self-Check

What if we combined the two loops into one? How would the time complexity change?