String methods (upcase, downcase, strip) in Ruby - Time & Space Complexity
We want to understand how long it takes for string methods like upcase, downcase, and strip to finish as the string gets longer.
How does the time needed change when the string size grows?
Analyze the time complexity of the following code snippet.
str = " Hello World "
up = str.upcase
down = str.downcase
clean = str.strip
This code changes the string to all uppercase, all lowercase, and removes spaces from the start and end.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each method goes through the string characters one by one.
- How many times: Once for each character in the string.
As the string gets longer, the time to change case or remove spaces grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows evenly with the string length.
Time Complexity: O(n)
This means the time to run these methods grows directly with the string size.
[X] Wrong: "These methods run instantly no matter how long the string is."
[OK] Correct: Each character must be checked or changed, so longer strings take more time.
Knowing how string methods scale helps you explain your code's speed clearly and shows you understand how computers handle text.
"What if we used a method that only changed the first character? How would the time complexity change?"