0
0
Blockchain / Solidityprogramming~5 mins

Mappings in Blockchain / Solidity - Time & Space Complexity

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

When working with mappings in blockchain, it's important to know how fast we can find or store data.

We want to understand how the time to access or update a mapping changes as it grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


mapping(address => uint) public balances;

function updateBalance(address user, uint amount) public {
    balances[user] = amount;
}

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

This code stores and retrieves a user's balance using a mapping from addresses to numbers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Direct access to mapping entries by key (address).
  • How many times: Each access or update happens once per call, no loops involved.
How Execution Grows With Input

Accessing or updating a mapping entry takes about the same time no matter how many entries exist.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays constant even as the mapping grows larger.

Final Time Complexity

Time Complexity: O(1)

This means accessing or updating a mapping entry takes the same short time no matter how many items are stored.

Common Mistake

[X] Wrong: "Accessing a mapping gets slower as it stores more data."

[OK] Correct: Mappings use a hash-like structure that lets the program jump directly to the data, so size does not slow access.

Interview Connect

Understanding that mappings provide quick access helps you explain efficient data handling in blockchain smart contracts.

Self-Check

"What if we replaced the mapping with an array and searched for the user each time? How would the time complexity change?"