0
0
Blockchain / Solidityprogramming~5 mins

Interfaces in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Interfaces
O(n)
Understanding Time Complexity

When working with interfaces in blockchain, it's important to see how the code runs as input grows.

We want to know how the time to execute changes when using interfaces.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

interface IToken {
    function balanceOf(address owner) external view returns (uint);
}

contract Wallet {
    IToken token;
    address[] owners;

    function totalBalance() public view returns (uint) {
        uint total = 0;
        for (uint i = 0; i < owners.length; i++) {
            total += token.balanceOf(owners[i]);
        }
        return total;
    }
}

This code defines an interface to check token balances and sums balances for a list of owners.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that calls balanceOf for each owner.
  • How many times: Once for each owner in the owners array.
How Execution Grows With Input

As the number of owners grows, the total calls to balanceOf grow the same way.

Input Size (n)Approx. Operations
1010 calls to balanceOf
100100 calls to balanceOf
10001000 calls to balanceOf

Pattern observation: The work grows directly with the number of owners.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the number of owners increases.

Common Mistake

[X] Wrong: "Using an interface makes the code run instantly regardless of input size."

[OK] Correct: Calling interface functions still takes time for each call, so more owners mean more calls and more time.

Interview Connect

Understanding how interface calls scale helps you write efficient blockchain contracts and explain your reasoning clearly.

Self-Check

What if we changed the owners array to a mapping and tried to sum balances? How would the time complexity change?