0
0
Blockchain / Solidityprogramming~5 mins

Short-circuiting in conditions in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Short-circuiting in conditions
O(n)
Understanding Time Complexity

When we use conditions that stop checking early, it can change how long the code runs.

We want to see how this early stopping affects the time it takes as inputs grow.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function checkTransactions(transactions) {
  for (let i = 0; i < transactions.length; i++) {
    if (transactions[i].isValid && transactions[i].isConfirmed) {
      return true;
    }
  }
  return false;
}

This code checks a list of transactions and stops as soon as it finds one that is valid and confirmed.

Identify Repeating Operations
  • Primary operation: Loop through the transactions array.
  • How many times: Up to the length of the transactions list, but may stop early.
How Execution Grows With Input

As the number of transactions grows, the loop might check fewer items if it finds a match early.

Input Size (n)Approx. Operations
10Between 1 and 10 checks
100Between 1 and 100 checks
1000Between 1 and 1000 checks

Pattern observation: The loop can stop early, so the work done depends on where the first valid transaction appears.

Final Time Complexity

Time Complexity: O(n)

This means in the worst case, the code checks every transaction once as the list grows.

Common Mistake

[X] Wrong: "Because of short-circuiting, the code always runs fast no matter the input size."

[OK] Correct: Sometimes the matching transaction is at the end or missing, so the loop checks all items, making time grow with input size.

Interview Connect

Understanding how early stopping affects time helps you explain code efficiency clearly and shows you think about real-world data behavior.

Self-Check

"What if the condition checked two separate arrays instead of one? How would the time complexity change?"