0
0
Blockchain / Solidityprogramming~5 mins

If-else statements in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If-else statements
O(1)
Understanding Time Complexity

We want to see how the time it takes to run if-else statements changes as the input changes in blockchain code.

Are these statements making the program slower when inputs grow?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function checkBalance(address user) {
  if (balanceOf(user) > 1000) {
    return "Rich";
  } else {
    return "Not rich";
  }
}
    

This code checks if a user's balance is greater than 1000 and returns a message based on that.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single if-else check.
  • How many times: Exactly once per function call.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

Pattern observation: Exactly one check per function call, independent of input size, so operations remain constant.

Final Time Complexity

Time Complexity: O(1)

This means the time remains constant regardless of the input size.

Common Mistake

[X] Wrong: "If-else statements scale linearly with input size like O(n)."

[OK] Correct: There are no loops or repetitions; the if-else executes exactly once per call, so it's O(1).

Interview Connect

Understanding how simple decisions add up helps you explain code efficiency clearly and confidently.

Self-Check

"What if we added a loop inside the if-else? How would the time complexity change?"