0
0
Bash Scriptingscripting~5 mins

for loop with range ({1..10}) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: for loop with range ({1..10})
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a bash for loop changes as we increase the number of items it goes through.

Specifically, how does the loop with a range like {1..10} behave when the range grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

for i in {1..10}
do
  echo "Number: $i"
done

This code runs a loop from 1 to 10 and prints each number.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop runs the echo command once for each number in the range.
  • How many times: Exactly as many times as the numbers in the range (10 times here).
How Execution Grows With Input

As the range grows, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010 echo commands
100100 echo commands
10001000 echo commands

Pattern observation: The number of operations grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the loop grows in a straight line with the number of items in the range.

Common Mistake

[X] Wrong: "The loop runs in constant time no matter how big the range is."

[OK] Correct: Each number in the range causes the loop to run once, so more numbers mean more work.

Interview Connect

Understanding how loops grow with input size is a key skill. It helps you explain how your scripts will behave with bigger data, which is important in real work.

Self-Check

"What if we changed the loop to run from 1 to 10 but printed only every second number? How would the time complexity change?"