String variables in Bash Scripting - Time & Space Complexity
We want to understand how the time to work with string variables changes as the string gets longer.
How does the script's running time grow when we use bigger strings?
Analyze the time complexity of the following code snippet.
string="hello"
length=${#string}
for (( i=0; i
This code prints each character of a string one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the string.
- How many times: Once for each character in the string (length of the string).
As the string gets longer, the loop runs more times, once per character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The number of operations grows directly with the string length.
Time Complexity: O(n)
This means the time to process the string grows in a straight line as the string gets longer.
[X] Wrong: "Accessing each character in a string is constant time regardless of string length."
[OK] Correct: Each character access happens inside a loop that runs once per character, so total time grows with string length.
Understanding how string operations scale helps you write scripts that handle data efficiently and avoid slowdowns as input grows.
"What if we replaced the loop with a command that processes the whole string at once? How would the time complexity change?"