for loop (list-based) in Bash Scripting - Time & Space 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?
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 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.
As the list gets longer, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items in the list.
[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.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how to write efficient scripts.
"What if we nested another for loop inside this one to process pairs of items? How would the time complexity change?"