Efficient data structures in Blockchain / Solidity - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When working with blockchain, choosing the right data structure helps your program run faster. We want to see how the time to do tasks changes as the data grows.
How does the choice of data structure affect the speed of common operations?
Analyze the time complexity of the following code snippet.
// Simple mapping to store balances
mapping(address => uint) 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 user balances using a mapping, which is like a fast lookup table.
- Primary operation: Direct access to mapping entries (no loops)
- How many times: Each access happens once per call, no repeated scanning
Looking up or updating a balance takes about the same time no matter how many users there are.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant even as the number of users grows.
Time Complexity: O(1)
This means each balance update or lookup takes the same short time, no matter how many users exist.
[X] Wrong: "Looking up a user's balance takes longer as more users are added because the data grows."
[OK] Correct: Mappings in blockchain work like a direct address book, so each lookup is quick and does not slow down with more users.
Understanding how data structures affect speed shows you can write smart, efficient blockchain code. This skill helps you build apps that work well even as they grow.
"What if we replaced the mapping with an array and searched for the user's balance each time? How would the time complexity change?"
Practice
Solution
Step 1: Understand the need for quick lookup
We want to find a balance by address fast, so we need a structure that supports direct access by key.Step 2: Identify the best data structure
Mappings provide key-value pairs allowing O(1) access by address, unlike arrays or structs which require searching.Final Answer:
Mapping (key-value pairs) -> Option BQuick Check:
Fast key-based lookup = Mapping [OK]
- Choosing arrays which require looping to find an address
- Using structs alone without a key for lookup
- Thinking linked lists are efficient for random access
Solution
Step 1: Recall Solidity mapping syntax
Mappings use the syntax mapping(keyType => valueType) variableName;Step 2: Match the correct syntax
mapping(address => uint) balances; matches this exactly: mapping(address => uint) balances;Final Answer:
mapping(address => uint) balances; -> Option AQuick Check:
Correct mapping syntax uses '=>' [OK]
- Using commas instead of '=>' in mapping
- Using square brackets or curly braces incorrectly
- Omitting the semicolon at the end
struct User { uint id; string name; }
User[] users;
users.push(User(1, "Alice"));
users.push(User(2, "Bob"));
string memory name = users[1].name;Solution
Step 1: Understand array indexing
Arrays start at index 0, so users[0] is Alice, users[1] is Bob.Step 2: Identify the accessed element
The code accesses users[1].name, which is "Bob".Final Answer:
"Bob" -> Option DQuick Check:
Index 1 in array = "Bob" [OK]
- Confusing index 1 with index 0
- Assuming structs print as variable names
- Expecting compilation error due to string usage
mapping(address => uint) balances;
function addBalance(address user, uint amount) public {
balances[user] += amount;
}
Solution
Step 1: Check mapping usage
Mappings default to zero for uint values if key not set, so no initialization needed.Step 2: Verify function and operation
Using '+=' on balances[user] is valid; function has public visibility.Final Answer:
No initialization needed for mapping values -> Option CQuick Check:
Mapping uint defaults to 0, so '+=' works [OK]
- Thinking mapping values must be initialized before use
- Confusing visibility modifiers
- Assuming keys must be uint instead of address
Solution
Step 1: Analyze the need for quick lookup by id
Quick lookup by id requires direct access, which arrays or linked lists cannot provide efficiently.Step 2: Choose the best data structure
Mapping from id to struct allows O(1) access to user profiles by id, combining grouping (struct) and fast lookup (mapping).Final Answer:
Mapping from id to struct -> Option AQuick Check:
Fast key access + grouped data = mapping to struct [OK]
- Using arrays which require looping to find id
- Using linked lists which are slow for random access
- Embedding arrays inside structs without mapping
