0
0
Bash Scriptingscripting~5 mins

Variable assignment (no spaces around =) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Variable assignment (no spaces around =)
O(n)
Understanding Time Complexity

Let's see how the time it takes to run a simple variable assignment changes as we run it multiple times.

We want to know how the cost grows when we assign values repeatedly.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

for i in {1..1000}
do
  value=$i
  echo $value
done

This code assigns a number to a variable and prints it, repeating 1000 times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Variable assignment and printing inside a loop.
  • How many times: The loop runs exactly n times, where n is the number of iterations.
How Execution Grows With Input

Each time we increase the number of loop runs, the total work grows directly with it.

Input Size (n)Approx. Operations
1010 assignments and prints
100100 assignments and prints
10001000 assignments and prints

Pattern observation: Doubling the input doubles the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of assignments we do.

Common Mistake

[X] Wrong: "Variable assignment is instant and does not add to time complexity."

[OK] Correct: Even simple assignments inside a loop add up as the loop runs more times, so total time grows with input size.

Interview Connect

Understanding how simple repeated steps add up helps you explain script performance clearly and confidently.

Self-Check

"What if we replaced the loop with a function call inside the loop? How would the time complexity change?"