String to Integer atoi in DSA C++ - Time & Space Complexity
We want to understand how the time needed to convert a string to an integer grows as the string gets longer.
How does the number of steps change when the input string size increases?
Analyze the time complexity of the following code snippet.
int myAtoi(const std::string &s) {
int i = 0, n = s.size(), sign = 1, result = 0;
while (i < n && s[i] == ' ') i++;
if (i < n && (s[i] == '+' || s[i] == '-')) {
sign = (s[i] == '-') ? -1 : 1;
i++;
}
while (i < n && std::isdigit(s[i])) {
int digit = s[i] - '0';
// Check overflow omitted for simplicity
result = result * 10 + digit;
i++;
}
return sign * result;
}
This code converts a string to an integer by skipping spaces, checking sign, and reading digits until non-digit or end.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through characters of the string to process spaces, sign, and digits.
- How many times: Each character is visited at most once in order from start to end.
As the string length grows, the number of characters to check grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character checks |
| 100 | About 100 character checks |
| 1000 | About 1000 character checks |
Pattern observation: The work grows directly in proportion to the string length.
Time Complexity: O(n)
This means the time to convert grows linearly with the length of the input string.
[X] Wrong: "The function runs in constant time because it just converts a number."
[OK] Correct: The function must check each character until it finds a non-digit, so time depends on input length.
Understanding this helps you explain how simple string parsing scales and shows you can analyze loops carefully.
"What if we changed the code to stop after reading a fixed number of digits? How would the time complexity change?"
Practice
atoi function do in C++?Solution
Step 1: Understand the purpose of atoi
The functionatoistands for ASCII to integer and converts a numeric string to an integer value.Step 2: Differentiate from other string functions
It does not convert integers to strings, sort strings, or calculate string length.Final Answer:
Converts a string representing a number into an integer -> Option AQuick Check:
atoi = string to int conversion [OK]
- Confusing atoi with itoa (integer to string)
- Thinking atoi sorts or measures strings
- Assuming atoi handles non-numeric strings safely
atoi in C++?Solution
Step 1: Check the parameter type for atoi
Theatoifunction expects a C-style string (const char*), so the argument must be a string literal like "1234".Step 2: Analyze each option
int num = atoi("1234"); passes a string literal correctly. int num = atoi(1234); passes an integer, which is invalid. int num = atoi('1234'); uses single quotes, which denote a char, not a string. int num = atoi(\"1234\"); has escaped quotes incorrectly.Final Answer:
int num = atoi("1234"); -> Option AQuick Check:
atoi needs a string literal argument [OK]
- Passing integer instead of string
- Using single quotes instead of double quotes
- Incorrect escaping of quotes
char str[] = "-42abc"; int val = atoi(str); std::cout << val << std::endl;
Solution
Step 1: Understand atoi behavior with non-digit characters
atoi converts the initial part of the string that forms a valid integer. It stops reading when it encounters a non-digit after the number.Step 2: Analyze the string "-42abc"
It starts with '-', then '4', '2' which form -42. The characters 'a', 'b', 'c' are ignored after the number.Final Answer:
-42 -> Option DQuick Check:
atoi stops at first non-digit after number [OK]
- Expecting atoi to parse entire string including letters
- Assuming atoi returns 0 for strings with trailing letters
- Thinking it throws runtime error on letters
atoi:std::string s = "123"; int num = atoi(s); std::cout << num << std::endl;
Solution
Step 1: Check parameter type for atoi
atoi expects a C-style string (const char*), butsis a std::string object.Step 2: Correct usage
To use atoi with std::string, calls.c_str()to get a C-style string.Final Answer:
Cannot pass std::string directly to atoi -> Option CQuick Check:
atoi needs const char*, not std::string [OK]
- Passing std::string directly to atoi
- Ignoring need for c_str() method
- Assuming atoi accepts std::string
Solution
Step 1: Understand limitations of atoi
atoi returns 0 for invalid inputs but cannot distinguish between actual zero and error, so it is unsafe for error handling.Step 2: Use stoi with exception handling
stoi throws exceptions on invalid input, allowing safe detection and handling of errors using try-catch blocks.Final Answer:
Use stoi inside try-catch block to catch exceptions -> Option BQuick Check:
stoi with try-catch is safe for invalid input [OK]
- Relying on atoi to detect invalid input
- Ignoring exceptions from stoi
- Using printf to guess numbers
Ready to prove it?
Pass the test and this pattern moves unknown
