0
0
DSA Pythonprogramming

String to Integer atoi in DSA Python

Choose your learning style9 modes available
Mental Model
Convert a string of characters into a number by reading each digit one by one and building the number step by step.
Analogy: Like reading a number written on a paper from left to right, ignoring spaces and signs, and stopping when you see something that is not a digit.
Input string: "  -42abc"
Parsing steps:
[ ] -> ' ' -> '-' -> '4' -> '2' -> 'a' -> 'b' -> 'c'
Result number: 0 -> -4 -> -42 -> stop at 'a'
Dry Run Walkthrough
Input: string: " -42abc"
Goal: Convert the string to the integer -42 by ignoring spaces, reading sign, digits, and stopping at first non-digit
Step 1: Skip leading spaces
"-42abc" (start parsing at '-')
Why: Spaces do not affect the number, so we ignore them
Step 2: Read sign '-' and set sign to negative
sign = -1, next chars: '4' -> '2' -> 'a' -> 'b' -> 'c'
Why: Sign tells if the number is positive or negative
Step 3: Read digit '4', number = 4
number = 4, next chars: '2' -> 'a' -> 'b' -> 'c'
Why: Start building the number from digits
Step 4: Read digit '2', number = 4*10 + 2 = 42
number = 42, next chars: 'a' -> 'b' -> 'c'
Why: Add next digit to the number by shifting previous digits left
Step 5: Encounter non-digit 'a', stop parsing
final number = 42, apply sign -> -42
Why: Stop when non-digit found, number is complete
Result:
final number: -42
Annotated Code
DSA Python
class Solution:
    def myAtoi(self, s: str) -> int:
        i = 0
        n = len(s)
        # Skip leading spaces
        while i < n and s[i] == ' ':
            i += 1
        # Check if string is empty after spaces
        if i == n:
            return 0
        # Check sign
        sign = 1
        if s[i] == '-':
            sign = -1
            i += 1
        elif s[i] == '+':
            i += 1
        # Convert digits to number
        num = 0
        while i < n and s[i].isdigit():
            num = num * 10 + (ord(s[i]) - ord('0'))
            i += 1
        return sign * num

# Driver code
sol = Solution()
print(sol.myAtoi("  -42abc"))
while i < n and s[i] == ' ':
skip all leading spaces to find start of number
if i == n: return 0
handle empty string or only spaces by returning zero
if s[i] == '-': sign = -1 i += 1 elif s[i] == '+': i += 1
detect and record sign, move index past sign
while i < n and s[i].isdigit(): num = num * 10 + (ord(s[i]) - ord('0')) i += 1
build number by reading each digit and shifting previous digits
return sign * num
apply sign to the number and return
OutputSuccess
-42
Complexity Analysis
Time: O(n) because we scan the string once from left to right
Space: O(1) because we use only a few variables regardless of input size
vs Alternative: This is optimal compared to parsing with regex or converting whole string at once which may be slower or use more memory
Edge Cases
empty string or string with only spaces
returns 0 because no digits found
DSA Python
if i == n:
    return 0
string with only sign and no digits, e.g. '+' or '-'
returns 0 because no digits after sign
DSA Python
while i < n and s[i].isdigit():
string starting with non-digit non-sign character
returns 0 because no valid number starts
DSA Python
while i < n and s[i].isdigit():
When to Use This Pattern
When you see a problem asking to convert a string to a number with rules about spaces, signs, and stopping at non-digits, use the String to Integer atoi pattern to parse carefully step by step.
Common Mistakes
Mistake: Not skipping leading spaces before parsing sign and digits
Fix: Add a loop to skip spaces before checking sign or digits
Mistake: Not handling sign correctly or ignoring it
Fix: Check for '+' or '-' sign and record it before parsing digits
Mistake: Continuing to parse after encountering a non-digit character
Fix: Stop parsing digits as soon as a non-digit character is found
Summary
Converts a string into an integer by reading characters one by one, handling spaces, sign, and digits.
Use when you need to safely parse a number from a string that may have extra characters or spaces.
The key insight is to carefully skip spaces, detect sign, then build the number digit by digit until a non-digit stops parsing.