0
0
Bash Scriptingscripting~5 mins

String length (${#var}) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String length (${#var})
O(1)
Understanding Time Complexity

We want to understand how the time it takes to get the length of a string changes as the string gets longer.

Specifically, how does using ${#var} behave when the string size grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


mystring="Hello, world!"
length=${#mystring}
echo "Length is $length"
    

This code gets the length of the string stored in mystring and prints it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Counting each character in the string to find its length.
  • How many times: Once per character in the string.
How Execution Grows With Input

As the string gets longer, the time to count its length grows in direct proportion.

Input Size (n)Approx. Operations
1010 character checks
100100 character checks
10001000 character checks

Pattern observation: The work grows linearly as the string length increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to get the string length grows directly with the number of characters in the string.

Common Mistake

[X] Wrong: "Getting the string length is instant no matter how long the string is."

[OK] Correct: The system must check each character to count length, so longer strings take more time.

Interview Connect

Knowing how simple operations like string length scale helps you reason about script performance and write efficient code.

Self-Check

"What if the string length was stored in a variable and updated as the string changes? How would that affect the time complexity of getting the length?"