0
0
Rustprogramming~5 mins

Variable shadowing in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Variable shadowing
O(n)
Understanding Time Complexity

Let's explore how variable shadowing affects the time it takes for a program to run.

We want to see if creating new variables with the same name changes how long the code takes as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn sum_numbers(numbers: &[i32]) -> i32 {
    let mut sum = 0;
    for &num in numbers {
        let sum = sum + num; // shadowing sum
    }
    sum
}

This code tries to add all numbers in a list, but it uses variable shadowing inside the loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the list.
  • How many times: Once for every number in the input list.
How Execution Grows With Input

Each number in the list is processed once, even with shadowing.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items; shadowing does not add extra loops.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the size of the input list, regardless of shadowing.

Common Mistake

[X] Wrong: "Variable shadowing makes the code slower because it creates new variables each time."

[OK] Correct: Shadowing just reuses the name but does not add extra loops or repeated work; it does not increase the number of operations.

Interview Connect

Understanding how variable shadowing affects performance shows you can separate naming from actual work done, a useful skill in coding and interviews.

Self-Check

"What if the shadowed variable was used to call a function inside the loop? How would that affect the time complexity?"