Scope of variables in Rust - Time & Space Complexity
We want to see how the time a program takes changes when variables are declared in different places.
Does where a variable lives affect how long the program runs?
Analyze the time complexity of the following code snippet.
fn sum_numbers(n: i32) -> i32 {
let mut sum = 0;
for i in 1..=n {
let temp = i; // variable inside loop
sum += temp;
}
sum
}
This code adds numbers from 1 to n, declaring a variable inside the loop each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs from 1 to n.
- How many times: The loop runs n times, and inside it, a variable is created each time.
Each time n grows, the loop runs more times, creating the variable each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop steps and 10 variable creations |
| 100 | About 100 loop steps and 100 variable creations |
| 1000 | About 1000 loop steps and 1000 variable creations |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time grows in a straight line with the size of n.
[X] Wrong: "Declaring a variable inside the loop makes the program slower in a way that changes the time complexity."
[OK] Correct: Creating a simple variable inside the loop adds a small fixed cost each time, but the overall time still grows linearly with n.
Understanding how variable placement affects time helps you write clear and efficient code, a skill valued in many coding challenges.
"What if we moved the variable declaration outside the loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand the meaning of scope
Scope means the part of the code where a variable is valid and can be used.Step 2: Identify what scope controls
Scope controls access to the variable, not its type, value, or memory size.Final Answer:
Where the variable can be accessed or used -> Option AQuick Check:
Scope = access area [OK]
- Confusing scope with variable type
- Thinking scope controls variable value
- Mixing scope with memory size
Solution
Step 1: Recall Rust variable declaration syntax
Rust usesletkeyword to declare variables.Step 2: Check each option
Onlylet x = 5;is valid Rust syntax; others are from other languages or invalid.Final Answer:
let x = 5; -> Option BQuick Check:
Rust variables start with let [OK]
- Using var instead of let
- Using type declarations like int
- Using declare keyword
fn main() {
let x = 10;
{
let x = 20;
println!("{}", x);
}
println!("{}", x);
}Solution
Step 1: Identify variable shadowing inside inner block
Inside the inner block,xis redefined as 20, shadowing outerx.Step 2: Trace the print statements
First print shows innerx= 20; second print shows outerx= 10.Final Answer:
20 10 -> Option DQuick Check:
Inner shadow = 20, outer original = 10 [OK]
- Ignoring shadowing and printing outer value twice
- Assuming inner variable changes outer variable
- Confusing print order
fn main() {
{
let y = 5;
}
println!("{}", y);
}Solution
Step 1: Check where y is declared and used
Variableyis declared inside inner block and goes out of scope after block ends.Step 2: Analyze usage of y outside block
Usingyinprintln!outside block causes error becauseyis not visible there.Final Answer:
Variable y is used outside its scope -> Option AQuick Check:
Use inside scope only [OK]
- Thinking semicolon is missing
- Assuming println! is wrong
- Ignoring variable scope rules
fn main() {
let mut count = 0;
for i in 0..3 {
let count = count + i;
println!("{}", count);
}
println!("Final count: {}", count);
}
What will be the output and why?Solution
Step 1: Understand variable shadowing inside the loop
Inside the loop,countis shadowed by a new variablecountequal to outercountplusi. Outercountremains unchanged.Step 2: Trace loop iterations and prints
Iterations: i=0 -> inner count=0, print 0; i=1 -> inner count=1, print 1; i=2 -> inner count=2, print 2. Outer count stays 0.Step 3: Final print shows outer count
After loop, outercountis still 0, so prints "Final count: 0".Final Answer:
0 1 2 Final count: 0 -> Option CQuick Check:
Shadowing hides outer count, outer unchanged [OK]
- Assuming outer count changes inside loop
- Confusing shadowing with mutation
- Expecting sum accumulation in outer count
Ready to prove it?
Pass the test and this pattern moves unknown
