0
0
Bash Scriptingscripting~5 mins

for loop (list-based) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: for loop (list-based)
O(n)
Understanding Time Complexity

When we use a for loop to go through a list in bash, we want to know how the time it takes changes as the list gets bigger.

We ask: How does the work grow when the list has more items?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


items=(apple banana cherry date elderberry)
for item in "${items[@]}"; do
  echo "Processing $item"
done
    

This code goes through each item in a list and prints a message for each one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop runs once for each item in the list.
  • How many times: Exactly as many times as there are items in the list.
How Execution Grows With Input

As the list gets longer, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010 times
100100 times
10001000 times

Pattern observation: The work grows directly with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items in the list.

Common Mistake

[X] Wrong: "The loop runs a fixed number of times no matter how big the list is."

[OK] Correct: The loop runs once for each item, so if the list grows, the loop runs more times.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how to write efficient scripts.

Self-Check

"What if we nested another for loop inside this one to process pairs of items? How would the time complexity change?"