Short-circuiting in conditions in Blockchain / Solidity - Time & Space 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.
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.
- Primary operation: Loop through the transactions array.
- How many times: Up to the length of the transactions list, but may stop early.
As the number of transactions grows, the loop might check fewer items if it finds a match early.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Between 1 and 10 checks |
| 100 | Between 1 and 100 checks |
| 1000 | Between 1 and 1000 checks |
Pattern observation: The loop can stop early, so the work done depends on where the first valid transaction appears.
Time Complexity: O(n)
This means in the worst case, the code checks every transaction once as the list grows.
[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.
Understanding how early stopping affects time helps you explain code efficiency clearly and shows you think about real-world data behavior.
"What if the condition checked two separate arrays instead of one? How would the time complexity change?"