String functions overview in C++ - Time & Space Complexity
When using string functions, it's important to know how their running time changes as the string gets longer.
We want to understand how the cost of these functions grows with the size of the input string.
Analyze the time complexity of the following code snippet.
#include <string>
#include <iostream>
int main() {
std::string s = "hello world";
auto length = s.length();
auto pos = s.find('o');
auto substr = s.substr(0, 5);
s.append("!!!");
std::cout << substr << std::endl;
return 0;
}
This code uses common string functions: length, find, substr, and append.
Look at what each function does repeatedly:
- length(): Checks the stored size, no loop.
- find(): Scans characters until it finds the target.
- substr(): Copies a part of the string, character by character.
- append(): Adds characters to the end, copying them.
The dominant operations are the ones that scan or copy characters.
Let's see how the number of operations changes as the string size grows.
| Input Size (n) | Approx. Operations for find() | Approx. Operations for substr() |
|---|---|---|
| 10 | Up to 10 checks | Copies up to 5 chars |
| 100 | Up to 100 checks | Copies up to 5 chars |
| 1000 | Up to 1000 checks | Copies up to 5 chars |
Notice that find() grows with the string length, but substr() depends on the substring size, not the whole string.
Time Complexity: O(n)
This means the time to run these string functions grows roughly in direct proportion to the string length.
[X] Wrong: "All string functions run in constant time regardless of string size."
[OK] Correct: Some functions like find() need to look at many characters, so their time grows with string length. substr() time grows with the substring size.
Understanding how string functions scale helps you write efficient code and explain your choices clearly in interviews.
"What if we changed substr() to copy the entire string instead of a part? How would the time complexity change?"
Practice
Solution
Step 1: Understand string length function
Thelength()function returns how many characters are in the string.Step 2: Compare with other functions
append()adds text,substr()extracts part,find()searches for text.Final Answer:
length() -> Option CQuick Check:
String length = length() [OK]
- Confusing length() with append()
- Using substr() to get length
- Thinking find() returns length
str in C++?Solution
Step 1: Identify correct append syntax
In C++,append()adds text to the end of a string:str.append(" world");.Step 2: Check other options
add()andconcat()are not string methods in C++.push_back()adds a single character, not a string.Final Answer:
str.append(" world"); -> Option AQuick Check:
Use append() to add text [OK]
- Using add() or concat() which don't exist
- Using push_back() with string argument
- Missing semicolon at end
std::string s = "hello world"; std::cout << s.substr(6, 5);
Solution
Step 1: Understand substr parameters
substr(6, 5)means start at index 6 and take 5 characters.Step 2: Extract substring from "hello world"
Index 6 is 'w', next 5 characters are "world".Final Answer:
world -> Option DQuick Check:
substr(6,5) = "world" [OK]
- Starting count at 1 instead of 0
- Taking wrong number of characters
- Confusing substr with find
std::string s = "example"; s = s.substr(3, 10);
Solution
Step 1: Check substr parameters
Start index 3 is valid. Length 10 is longer than remaining string length.Step 2: Understand substr behavior with long length
substr returns substring from index 3 to end without error even if length is too big.Final Answer:
substr length exceeds string length but no error occurs -> Option AQuick Check:
substr handles long length safely [OK]
- Expecting runtime error for long length
- Thinking start index is invalid
- Confusing substr arguments count
text = "Hello C++ World", which code snippet converts it to all uppercase letters?Solution
Step 1: Identify correct uppercase conversion
Looping over each character and applyingtoupper()converts all letters to uppercase.Step 2: Check other options
toUpperCase()andupper()are not C++ string methods. transform(text.begin(), text.end(), text.begin(), tolower); usestolowerwhich converts to lowercase.Final Answer:
for (auto &c : text) c = toupper(c); -> Option BQuick Check:
Use loop + toupper() for uppercase [OK]
- Using non-existent string methods
- Using tolower instead of toupper
- Not using reference in loop to modify string
Ready to prove it?
Pass the test and this pattern moves unknown
