0
0
Bash Scriptingscripting~5 mins

Brace expansion ({1..10}) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Brace expansion ({1..10})
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a bash script using brace expansion changes as the range grows.

Specifically, how does the number of generated items affect the script's work?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

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

This script prints numbers from 1 to 10 using brace expansion to generate the list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop iterates over each number generated by the brace expansion.
  • How many times: Exactly once for each number in the range (here, 10 times).
How Execution Grows With Input

As the range increases, the loop runs more times, so the work grows directly with the number of items.

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

Pattern observation: The number of operations grows in a straight line with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the script grows directly in proportion to how many numbers are in the range.

Common Mistake

[X] Wrong: "Brace expansion runs instantly no matter how big the range is."

[OK] Correct: The shell must generate and loop over each item, so more items mean more work and longer time.

Interview Connect

Understanding how loops scale with input size is a key skill in scripting and automation, helping you write efficient scripts that handle bigger tasks smoothly.

Self-Check

"What if we replaced brace expansion with a command that generates numbers dynamically, like seq? How would the time complexity change?"