0
0
Bash Scriptingscripting~5 mins

while loop in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: while loop
O(n)
Understanding Time Complexity

We want to understand how the time a while loop takes changes as the input size grows.

Specifically, how many times does the loop run when input gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


count=0
limit=100
while [ $count -lt $limit ]
do
  echo "Count is $count"
  ((count++))
done
    

This code prints numbers from 0 up to one less than the limit using a while loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs the echo and increment commands repeatedly.
  • How many times: It runs once for each number from 0 up to limit minus one, so limit times.
How Execution Grows With Input

As the limit grows, the number of loop runs grows the same way.

Input Size (limit)Approx. Operations (loop runs)
1010
100100
10001000

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

Final Time Complexity

Time Complexity: O(n)

This means the time taken grows in a straight line as the input size increases.

Common Mistake

[X] Wrong: "The while loop runs a fixed number of times no matter the input."

[OK] Correct: The loop count depends on the limit variable, so if limit grows, the loop runs more times.

Interview Connect

Understanding how loops grow with input helps you explain script performance clearly and confidently.

Self-Check

"What if we changed the increment from 1 to 2 each time? How would the time complexity change?"