0
0
Blockchain / Solidityprogramming~5 mins

Using for directive in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Using for directive
O(n)
Understanding Time Complexity

When we use a for directive in blockchain code, it usually means repeating some steps for many items. Understanding how long this takes helps us write faster programs.

We want to know: how does the time to run grow when we have more items to process?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

for (uint i = 0; i < transactions.length; i++) {
    processTransaction(transactions[i]);
}

This code goes through each transaction in a list and processes it one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop that runs processTransaction on each item.
  • How many times: Exactly once for each transaction in the list.
How Execution Grows With Input

As the number of transactions grows, the total steps grow in the same way.

Input Size (n)Approx. Operations
1010 times processing
100100 times processing
10001000 times processing

Pattern observation: If you double the number of transactions, the work doubles too.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the number of transactions.

Common Mistake

[X] Wrong: "The loop runs only once no matter how many transactions there are."

[OK] Correct: The loop actually runs once for each transaction, so more transactions mean more work.

Interview Connect

Knowing how loops affect time helps you explain your code clearly and shows you understand how programs grow with data size. This skill is useful in many blockchain tasks.

Self-Check

"What if we nested another for loop inside this one to process pairs of transactions? How would the time complexity change?"