0
0
Rustprogramming~5 mins

Scope of variables in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Scope of variables
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time n grows, the loop runs more times, creating the variable each time.

Input Size (n)Approx. Operations
10About 10 loop steps and 10 variable creations
100About 100 loop steps and 100 variable creations
1000About 1000 loop steps and 1000 variable creations

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the size of n.

Common Mistake

[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.

Interview Connect

Understanding how variable placement affects time helps you write clear and efficient code, a skill valued in many coding challenges.

Self-Check

"What if we moved the variable declaration outside the loop? How would the time complexity change?"