String to Integer atoi in DSA C - Time & Space Complexity
We want to know how the time 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(char * s) {
int i = 0, sign = 1, result = 0;
while (s[i] == ' ') i++;
if (s[i] == '-' || s[i] == '+') {
sign = (s[i] == '-') ? -1 : 1;
i++;
}
while (s[i] >= '0' && s[i] <= '9') {
result = result * 10 + (s[i] - '0');
i++;
}
return sign * result;
}
This code converts a string to an integer by skipping spaces, handling sign, and reading digits until a non-digit is found.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The two while loops that scan characters in the string.
- How many times: Each loop runs at most once over parts of the string, together covering up to all characters.
As the string length grows, the code checks each character once until it stops at a non-digit or end.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character checks |
| 100 | About 100 character checks |
| 1000 | About 1000 character checks |
Pattern observation: The number of steps grows roughly in direct proportion to the input size.
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 string length.
Understanding this helps you explain how simple string processing scales, a common skill in coding interviews.
"What if the input string is guaranteed to have only digits and no spaces or signs? How would the time complexity change?"
Practice
atoi function do in C programming?Solution
Step 1: Understand the purpose of atoi
Theatoifunction stands for ASCII to integer, which means it converts a string of digits into an integer value.Step 2: Compare options with definition
Only Converts a string representing a number into an integer correctly describes this conversion from string to integer.Final Answer:
Converts a string representing a number into an integer -> Option BQuick Check:
atoi = string to integer conversion [OK]
- Confusing atoi with itoa (integer to ASCII)
- Thinking atoi calculates string length
- Assuming atoi validates string digits
atoi in C?Solution
Step 1: Check function parameter type
Theatoifunction takes a single argument of typeconst char *, which is a string pointer.Step 2: Validate correct syntax
int num = atoi(str); correctly shows callingatoiwith a string variablestrwithout specifying type in call.Final Answer:
int num = atoi(str); -> Option DQuick Check:
atoi takes string variable as argument [OK]
- Including type in function call parentheses
- Calling atoi without arguments
- Passing integer instead of string
char str[] = "-123abc";
int val = atoi(str);
printf("%d", val);Solution
Step 1: Analyze atoi behavior with mixed string
atoi converts initial numeric part including sign until non-digit character. Here, "-123" is converted, stops at 'a'.Step 2: Determine output value
So,valbecomes -123 andprintfprints -123.Final Answer:
-123 -> Option AQuick Check:
atoi stops at first non-digit, returns -123 [OK]
- Expecting atoi to ignore leading sign
- Thinking atoi returns 0 on trailing letters
- Assuming runtime error due to letters
atoi:char *str = NULL;
int num = atoi(str);
printf("%d", num);Solution
Step 1: Check argument passed to atoi
The code passes a NULL pointer toatoi, which expects a valid string pointer.Step 2: Understand consequences of NULL argument
Passing NULL leads to undefined behavior, often causing a crash or runtime error.Final Answer:
Passing NULL pointer to atoi causes undefined behavior -> Option AQuick Check:
atoi needs valid string pointer, NULL causes error [OK]
- Ignoring NULL pointer checks
- Assuming atoi handles NULL safely
- Confusing missing header with runtime error
Solution
Step 1: Understand limitation of atoi
atoi converts initial number but does not provide info about leftover invalid characters.Step 2: Use strtol for better control
strtol converts string to long and returns pointer to first invalid character, allowing validation.Step 3: Choose best approach
Usestrtolwhich provides end pointer to check leftover characters uses strtol with end pointer to detect invalid trailing characters safely.Final Answer:
Use strtol which provides end pointer to check leftover characters -> Option CQuick Check:
strtol + end pointer = safe string to int with validation [OK]
- Relying only on atoi for input validation
- Ignoring leftover characters after number
- Using printf incorrectly for conversion
Ready to prove it?
Pass the test and this pattern moves unknown
