0
0
Blockchain / Solidityprogramming~5 mins

Return values in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Return values
O(1)
Understanding Time Complexity

When we look at return values in blockchain code, we want to know how the time to get that value changes as the input grows.

We ask: How long does it take to produce the return value when the input size changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

function getBalance(address user) public view returns (uint) {
    return balances[user];
}

This code returns the balance of a user from a stored mapping.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Direct lookup in a mapping (like a dictionary).
  • How many times: Exactly once per call, no loops or repeated steps.
How Execution Grows With Input

Getting the balance is a simple lookup that does not depend on how many users or balances exist.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays the same no matter how many users there are.

Final Time Complexity

Time Complexity: O(1)

This means the time to get a return value is constant and does not grow with input size.

Common Mistake

[X] Wrong: "Looking up a user's balance takes longer if there are more users."

[OK] Correct: The lookup uses a direct key access, so it takes the same time regardless of total users.

Interview Connect

Understanding that return values from mappings are constant time helps you explain efficient data access in blockchain contracts clearly and confidently.

Self-Check

"What if the return value was computed by summing all balances instead of a direct lookup? How would the time complexity change?"