String to Integer atoi in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to convert a string to an integer grows as the string gets longer.
Specifically, how does the number of steps change when the input string size increases?
Analyze the time complexity of the following code snippet.
function myAtoi(s: string): number {
let i = 0, sign = 1, result = 0;
while (i < s.length && s[i] === ' ') i++;
if (i < s.length && (s[i] === '+' || s[i] === '-')) {
sign = s[i] === '-' ? -1 : 1;
i++;
}
while (i < s.length && s[i] >= '0' && s[i] <= '9') {
result = result * 10 + (s.charCodeAt(i) - 48);
i++;
}
return sign * result;
}
This code converts a string to an integer by skipping spaces, checking for a sign, and then reading digits until a non-digit is found.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two while loops that scan through parts of the string.
- How many times: Each loop runs at most once over the string characters, together covering the string length.
As the input string gets longer, the code checks each character once or twice in sequence.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and conversions |
| 100 | About 100 checks and conversions |
| 1000 | About 1000 checks and conversions |
Pattern observation: The number of steps grows roughly in direct 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 stops once digits end."
[OK] Correct: The function may need to scan many characters before digits start or after, so in the worst case it checks every character.
Understanding this linear time behavior helps you explain how your code handles input size efficiently and prepares you for similar string parsing tasks.
"What if we changed the code to parse the string backwards? How would the time complexity change?"
Practice
atoi function do when given a string input?Solution
Step 1: Understand the purpose of atoi
The atoi function stands for ASCII to integer and converts a string representing a number into an integer value.Step 2: Compare options with function behavior
Only Converts the string to an integer number correctly describes this conversion. Other options describe different operations unrelated to atoi.Final Answer:
Converts the string to an integer number -> Option CQuick Check:
atoi converts string to integer [OK]
- Thinking atoi converts to float
- Confusing atoi with string reversal
- Assuming atoi counts characters
Solution
Step 1: Identify input and output types for atoi
atoi takes a string input and returns a number (integer).Step 2: Match function signature with correct types
function atoi(str: string): number matches this: input is string, output is number. Other options have wrong input/output types or no parameters.Final Answer:
function atoi(str: string): number -> Option AQuick Check:
Input string, output number [OK]
- Swapping input and output types
- Using no parameters
- Using wrong parameter types
function atoi(str: string): number {
let i = 0, num = 0, sign = 1;
while (str[i] === ' ') i++;
if (str[i] === '-' || str[i] === '+') {
sign = str[i] === '-' ? -1 : 1;
i++;
}
while (i < str.length && str[i] >= '0' && str[i] <= '9') {
num = num * 10 + (str.charCodeAt(i) - 48);
i++;
}
return num * sign;
}
console.log(atoi(" -42abc"));Solution
Step 1: Skip leading spaces and detect sign
The code skips spaces, finds '-', so sign = -1, index moves past '-'.Step 2: Parse digits until non-digit
Reads '4' and '2', converts to number 42, stops at 'a'.Step 3: Apply sign and return
Returns 42 * -1 = -42.Final Answer:
-42 -> Option AQuick Check:
Parsed number with sign = -42 [OK]
- Not skipping spaces
- Ignoring sign character
- Parsing non-digit characters
function atoi(str: string): number {
let num = 0;
let i = 0;
while (i < str.length && str[i] === ' ') i++;
for (; i < str.length; i++) {
if (str[i] < '0' || str[i] > '9') break;
num = num * 10 + (str.charCodeAt(i) - 48);
}
return num;
}Solution
Step 1: Check for sign handling
The code does not check for '+' or '-' signs before parsing digits.Step 2: Verify other behaviors
It skips leading spaces, stops parsing at first non-digit and returns number, so no issue there. The main bug is missing sign handling.Final Answer:
Does not handle negative or positive signs -> Option DQuick Check:
Missing sign handling in atoi [OK]
- Assuming spaces are main bug
- Thinking it parses non-digit characters
- Confusing return type
INT_MIN = -2147483648 and INT_MAX = 2147483647. Which code snippet correctly clamps the value before returning?const INT_MIN = -2147483648;
const INT_MAX = 2147483647;
function atoi(str: string): number {
let i = 0, num = 0, sign = 1;
while (str[i] === ' ') i++;
if (str[i] === '-' || str[i] === '+') {
sign = str[i] === '-' ? -1 : 1;
i++;
}
while (i < str.length && str[i] >= '0' && str[i] <= '9') {
num = num * 10 + (str.charCodeAt(i) - 48);
i++;
}
num = num * sign;
// Clamp here
// ???
return num;
}Solution
Step 1: Understand clamping logic
If number is less than INT_MIN, return INT_MIN; if greater than INT_MAX, return INT_MAX.Step 2: Match correct condition and return
if (num < INT_MIN) return INT_MIN; if (num > INT_MAX) return INT_MAX; correctly checks and returns clamped values. Other options have incorrect comparisons or swap min/max.Final Answer:
if (num < INT_MIN) return INT_MIN; if (num > INT_MAX) return INT_MAX; -> Option BQuick Check:
Clamp below min and above max correctly [OK]
- Swapping INT_MIN and INT_MAX in conditions
- Using equality instead of inequality
- Returning wrong clamp value
Ready to prove it?
Pass the test and this pattern moves unknown
