Smart contract concept in Blockchain / Solidity - Time & Space Complexity
When working with smart contracts, it is important to understand how the time to run them changes as the input grows.
We want to know how the contract's execution time scales when it processes more data or users.
Analyze the time complexity of the following code snippet.
contract SimpleStorage {
uint[] public data;
function addData(uint value) public {
data.push(value);
}
function sumData() public view returns (uint) {
uint total = 0;
for (uint i = 0; i < data.length; i++) {
total += data[i];
}
return total;
}
}
This contract stores numbers and sums all stored numbers when asked.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through all stored numbers in the
sumDatafunction. - How many times: It runs once for each number stored in the
dataarray.
As the number of stored numbers grows, the time to sum them grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The time to sum grows directly with the number of stored numbers.
Time Complexity: O(n)
This means the time to run the sum grows in a straight line as more numbers are stored.
[X] Wrong: "The sum function runs instantly no matter how many numbers are stored."
[OK] Correct: The sum function must look at each number once, so more numbers mean more work and more time.
Understanding how smart contract functions scale with input size helps you write efficient contracts and explain your reasoning clearly.
"What if we stored the running total each time we add a number? How would the time complexity of summing change?"
Practice
smart contract in blockchain technology?Solution
Step 1: Understand the definition of smart contracts
Smart contracts are computer programs that run on blockchains to automate and enforce agreements without middlemen.Step 2: Compare options with the definition
Only A program that runs on a blockchain to automate agreements describes a program on blockchain automating agreements. Other options describe unrelated concepts.Final Answer:
A program that runs on a blockchain to automate agreements -> Option BQuick Check:
Smart contract = automated blockchain program [OK]
- Confusing smart contracts with physical contracts
- Thinking smart contracts are wallets or mining tools
- Assuming smart contracts require middlemen
Solution
Step 1: Recall Solidity syntax for defining contracts
In Solidity, smart contracts start with the keywordcontractfollowed by the contract name and braces.Step 2: Check each option's syntax
contract MyContract { } usescontractkeyword correctly. Options A, B, and C use keywords from other languages or incorrect syntax.Final Answer:
contract MyContract { } -> Option AQuick Check:
Solidity contracts start with 'contract' keyword [OK]
- Using 'class' instead of 'contract' keyword
- Confusing functions with contract declarations
- Using module or other unrelated keywords
function getValue() public pure returns (uint) { return 5 + 3; }Solution
Step 1: Analyze the function logic
The function returns the sum of 5 and 3, which is 8.Step 2: Understand Solidity return behavior
The function is markedpureand returns a uint, so it will output the calculated value 8 without errors.Final Answer:
8 -> Option CQuick Check:
5 + 3 = 8 [OK]
- Thinking '5 + 3' concatenates as '53'
- Expecting runtime error due to missing state
- Assuming default return is zero
contract Test {
uint value;
function setValue(uint _value) public {
value = _value
}
}Solution
Step 1: Check syntax line by line
The linevalue = _valueis missing a semicolon at the end, which is required in Solidity.Step 2: Verify other parts
Function visibility 'public' is correct, variable can be private, and function naming is valid. So only missing semicolon is error.Final Answer:
Missing semicolon after assignment -> Option AQuick Check:
Semicolons end statements in Solidity [OK]
- Ignoring missing semicolon errors
- Thinking function visibility is wrong
- Assuming variable must be public
Solution
Step 1: Check input validation for positive amount
function deposit(uint amount) public { require(amount > 0, "Amount must be positive"); balances[msg.sender] += amount; } usesrequire(amount > 0)to ensure only positive deposits are accepted.Step 2: Compare other options for correctness
function deposit(uint amount) public { if(amount >= 0) { balances[msg.sender] = amount; } } allows zero and overwrites balance instead of adding. function deposit(int amount) public { balances[msg.sender] += amount; } uses signed int allowing negative deposits. function deposit(uint amount) public { balances[msg.sender] += amount; } lacks any check.Final Answer:
function deposit(uint amount) public { require(amount > 0, "Amount must be positive"); balances[msg.sender] += amount; } -> Option DQuick Check:
Use require() to enforce positive deposits [OK]
- Not validating input amounts
- Using signed integers for balances
- Overwriting balances instead of adding
Ready to prove it?
Pass the test and this pattern moves unknown
