String to Integer atoi in DSA Python - Time & Space Complexity
We want to understand how the time taken 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.
def myAtoi(s: str) -> int:
i, n = 0, len(s)
while i < n and s[i] == ' ':
i += 1
sign = 1
if i < n and s[i] in ['+', '-']:
sign = -1 if s[i] == '-' else 1
i += 1
result = 0
while i < n and s[i].isdigit():
result = result * 10 + (ord(s[i]) - ord('0'))
i += 1
return sign * result
This code converts a string to an integer by skipping spaces, handling sign, and reading digits.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two while loops scanning characters in the string.
- How many times: Each loop runs at most once over the string characters, total scanning each character at most once.
The code scans the string from start to end, checking characters one by one.
| 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 string length.
Time Complexity: O(n)
This means the time to convert the string grows linearly with the length of the input string.
[X] Wrong: "The time complexity is constant because we only read until the first non-digit character."
[OK] Correct: In the worst case, the entire string can be digits, so the code must check every character, making time grow with input size.
Understanding this linear time complexity helps you explain how your solution scales with input size, a key skill in interviews.
"What if the input string was given as a linked list of characters instead of a string? 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 is designed to convert a string that represents a number into an integer type.Step 2: Compare options with function behavior
Only Converts the string to an integer number matches the behavior of converting string to integer. Others describe different operations.Final Answer:
Converts the string to an integer number -> Option AQuick Check:
atoi = string to integer [OK]
- Thinking atoi converts to float
- Confusing atoi with string reversal
- Assuming atoi counts characters
s to an integer similar to atoi?Solution
Step 1: Identify Python function for string to integer
Python's built-inint()function converts a string representing a number into an integer.Step 2: Check other options
str()converts to string,float()converts to float, andlen()returns length, so they are incorrect.Final Answer:
int(s) -> Option BQuick Check:
int() converts string to integer [OK]
- Using str() instead of int()
- Using float() when integer is needed
- Using len() expecting number conversion
def my_atoi(s):
s = s.strip()
sign = 1
if s and s[0] == '-':
sign = -1
s = s[1:]
num = 0
for char in s:
if not char.isdigit():
break
num = num * 10 + (ord(char) - ord('0'))
return sign * num
print(my_atoi(' -123abc'))Solution
Step 1: Analyze string trimming and sign detection
The string ' -123abc' is stripped to '-123abc'. The sign is detected as negative and removed from string, leaving '123abc'.Step 2: Convert digits until non-digit character
Loop reads '1', '2', '3' converting to number 123. Stops at 'a' which is not digit.Final Answer:
-123 -> Option CQuick Check:
Parsed number with sign = -123 [OK]
- Ignoring sign and returning positive number
- Parsing entire string including letters
- Raising error on non-digit characters
atoi implementation and choose the correct fix:def atoi_buggy(s):
s = s.strip()
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
num = 0
for char in s:
if not char.isdigit():
return 0
num = num * 10 + int(char)
return sign * num
print(atoi_buggy(' -42abc'))Solution
Step 1: Identify potential error with empty string
If input is empty or only spaces,s[0]access causes IndexError. Need to check ifsis not empty before accessing.Step 2: Evaluate other fixes
Changingreturn 0tobreakis good but does not fix crash on empty string. Removing sign loses negative support. Usingord(char)is incorrect for digit conversion.Final Answer:
Add check if string is empty before accessing s[0] -> Option AQuick Check:
Check empty string before indexing [OK]
- Not checking empty string before s[0]
- Returning 0 instead of stopping parse
- Ignoring negative sign handling
atoi that handles leading spaces, optional sign, digits, and clamps output to 32-bit signed integer range [-2^31, 2^31-1]. Which approach correctly applies this?Solution
Step 1: Understand requirements for atoi with clamping
We must parse string carefully: skip spaces, detect sign, convert digits until non-digit, then clamp to 32-bit integer range.Step 2: Evaluate options for correctness
Parse string, convert digits, apply sign, then clamp result between -2147483648 and 2147483647 correctly describes parsing and clamping. Convert entire string to int directly and then clamp risks error if string has invalid chars. Ignore sign and clamp only positive values ignores sign which is wrong. Return 0 if string contains any non-digit characters returns 0 too aggressively.Final Answer:
Parse string, convert digits, apply sign, then clamp result between -2147483648 and 2147483647 -> Option DQuick Check:
Parse, sign, clamp = correct atoi [OK]
- Clamping before applying sign
- Not handling non-digit characters properly
- Ignoring integer overflow limits
Ready to prove it?
Pass the test and this pattern moves unknown
