0
0
Blockchain / Solidityprogramming~5 mins

For and while loops in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For and while loops
O(n)
Understanding Time Complexity

When we use loops in blockchain code, the time it takes to run depends on how many times the loop repeats.

We want to know how the running time grows as the number of loop steps increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function processTransactions(transactions) {
  for (let i = 0; i < transactions.length; i++) {
    while (transactions[i].needsProcessing) {
      process(transactions[i]);
      transactions[i].needsProcessing = false;
    }
  }
}
    

This code goes through a list of transactions and processes each one if it needs processing.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The outer for loop runs once for each transaction.
  • Secondary operation: The inner while loop runs until the current transaction is processed, usually once per transaction.
  • Dominant operation: The for loop over all transactions dominates because it scales with the number of transactions.
How Execution Grows With Input

As the number of transactions grows, the total steps grow roughly the same amount.

Input Size (n)Approx. Operations
10About 10 times processing steps
100About 100 times processing steps
1000About 1000 times processing steps

Pattern observation: The work grows directly with the number of transactions.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of transactions, the time to process roughly doubles.

Common Mistake

[X] Wrong: "The inner while loop makes this code run much slower, like squared time."

[OK] Correct: The inner loop usually runs only once per transaction, so it does not multiply the total steps by the number of transactions.

Interview Connect

Understanding how loops affect time helps you explain your code clearly and shows you can think about efficiency in blockchain programs.

Self-Check

"What if the inner while loop could run multiple times per transaction? How would the time complexity change?"