Bird
Raised Fist0
Blockchain / Solidityprogramming~10 mins

Efficient data structures in Blockchain / Solidity - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Efficient data structures
Start
Choose data structure
Check operation needs
Fast lookup?
YesUse Hash Map
Use Linked List
Fast insertion?
YesUse Linked List
No
Use Array
Implement in blockchain
Test performance
End
This flow shows how to pick and use efficient data structures in blockchain by checking operation needs like lookup and insertion speed.
Execution Sample
Blockchain / Solidity
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 Solidity code uses a mapping (hash map) to efficiently store and retrieve user balances by address.
Execution Table
StepActionData Structure StateOperationResult
1Initialize empty mappingbalances = {}N/AEmpty mapping created
2Call updateBalance(user1, 100)balances = {user1: 100}Insert/updateBalance for user1 set to 100
3Call updateBalance(user2, 50)balances = {user1: 100, user2: 50}Insert/updateBalance for user2 set to 50
4Call getBalance(user1)balances unchangedLookupReturns 100
5Call getBalance(user3)balances unchangedLookupReturns 0 (default)
💡 No more operations; mapping stores balances efficiently with O(1) lookup.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5
balances{}{user1: 100}{user1: 100, user2: 50}{user1: 100, user2: 50}{user1: 100, user2: 50}
return value (getBalance user1)N/AN/AN/A100100
return value (getBalance user3)N/AN/AN/AN/A0
Key Moments - 2 Insights
Why does getBalance(user3) return 0 even though user3 was never added?
In the execution_table row 5, the mapping returns 0 by default for keys not present, which is Solidity's default behavior for uint values.
How does the mapping allow fast lookup compared to an array?
As shown in steps 4 and 5, the mapping provides O(1) lookup time by directly accessing the value via the key, unlike arrays which require searching.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the state of balances?
A{user1: 100, user2: 50}
B{user1: 50, user2: 100}
C{}
D{user1: 100}
💡 Hint
Check the 'Data Structure State' column at step 3 in the execution_table.
At which step does the mapping first contain two users?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Data Structure State' column to see when two keys appear.
If updateBalance(user1, 200) is called after step 3, what will balances[user1] be?
A100
B200
C50
D0
💡 Hint
Updating a key in mapping overwrites the previous value, see step 2 and 3 for similar insert/update.
Concept Snapshot
Efficient data structures in blockchain:
- Use mappings for fast key-value lookup (O(1))
- Use arrays or linked lists for ordered data
- Choose based on operation needs: lookup, insertion, iteration
- Mappings return default values for missing keys
- Efficient structures save gas and improve performance
Full Transcript
This visual execution shows how efficient data structures like mappings work in blockchain programming. We start with an empty mapping and add user balances. Each update inserts or updates a key-value pair. Lookups return stored values or default zero if missing. This approach provides fast access and efficient storage, important for blockchain smart contracts. The execution table tracks each step, showing how balances change and how lookups behave. Key moments clarify default values and lookup speed. The quiz tests understanding of mapping state and updates. The snapshot summarizes key points for choosing and using efficient data structures in blockchain.

Practice

(1/5)
1. Which data structure is best for quickly finding a user's balance by their blockchain address?
easy
A. Array
B. Mapping (key-value pairs)
C. Struct
D. Linked list

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Mapping (key-value pairs) -> Option B
  4. Quick Check:

    Fast key-based lookup = Mapping [OK]
Hint: Use mappings for direct key lookups in blockchain [OK]
Common Mistakes:
  • 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
2. Which of the following is the correct syntax to declare a mapping from address to uint in Solidity?
easy
A. mapping(address => uint) balances;
B. mapping(address, uint) balances;
C. mapping[address] uint balances;
D. mapping{address: uint} balances;

Solution

  1. Step 1: Recall Solidity mapping syntax

    Mappings use the syntax mapping(keyType => valueType) variableName;
  2. Step 2: Match the correct syntax

    mapping(address => uint) balances; matches this exactly: mapping(address => uint) balances;
  3. Final Answer:

    mapping(address => uint) balances; -> Option A
  4. Quick Check:

    Correct mapping syntax uses '=>' [OK]
Hint: Remember mapping uses '=>' between key and value types [OK]
Common Mistakes:
  • Using commas instead of '=>' in mapping
  • Using square brackets or curly braces incorrectly
  • Omitting the semicolon at the end
3. What will be the output of this Solidity code snippet?
struct User { uint id; string name; }
User[] users;
users.push(User(1, "Alice"));
users.push(User(2, "Bob"));
string memory name = users[1].name;
medium
A. "Alice"
B. Empty string
C. Compilation error
D. "Bob"

Solution

  1. Step 1: Understand array indexing

    Arrays start at index 0, so users[0] is Alice, users[1] is Bob.
  2. Step 2: Identify the accessed element

    The code accesses users[1].name, which is "Bob".
  3. Final Answer:

    "Bob" -> Option D
  4. Quick Check:

    Index 1 in array = "Bob" [OK]
Hint: Remember arrays start at zero index [OK]
Common Mistakes:
  • Confusing index 1 with index 0
  • Assuming structs print as variable names
  • Expecting compilation error due to string usage
4. Identify the error in this Solidity code snippet:
mapping(address => uint) balances;
function addBalance(address user, uint amount) public {
balances[user] += amount;
}
medium
A. Cannot use '+=' on mapping values
B. Function lacks visibility modifier
C. No initialization needed for mapping values
D. Mapping keys must be uint, not address

Solution

  1. Step 1: Check mapping usage

    Mappings default to zero for uint values if key not set, so no initialization needed.
  2. Step 2: Verify function and operation

    Using '+=' on balances[user] is valid; function has public visibility.
  3. Final Answer:

    No initialization needed for mapping values -> Option C
  4. Quick Check:

    Mapping uint defaults to 0, so '+=' works [OK]
Hint: Mapping values default to zero, no init needed [OK]
Common Mistakes:
  • Thinking mapping values must be initialized before use
  • Confusing visibility modifiers
  • Assuming keys must be uint instead of address
5. You want to store user profiles with id, name, and balance, and quickly find a profile by id. Which data structure combination is most efficient in Solidity?
hard
A. Mapping from id to struct
B. Array of structs only
C. Struct with embedded array
D. Linked list of structs

Solution

  1. 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.
  2. 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).
  3. Final Answer:

    Mapping from id to struct -> Option A
  4. Quick Check:

    Fast key access + grouped data = mapping to struct [OK]
Hint: Use mapping from id to struct for fast profile lookup [OK]
Common Mistakes:
  • Using arrays which require looping to find id
  • Using linked lists which are slow for random access
  • Embedding arrays inside structs without mapping