Leetcode #8: String to Integer (atoi)
In this guide, we solve Leetcode #8 String to Integer (atoi) in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: Whitespace: Ignore any leading whitespace (" ").
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: String
Intuition
We need to scan characters while tracking positions or counts.
A simple state machine keeps the logic precise.
Approach
Iterate through the string once and update the state for each character.
Use a map or array if you need fast lookups.
Steps:
- Iterate through characters.
- Maintain necessary state.
- Build or validate the output.
Example
The underlined characters are what is read in and the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^
Python Solution
class Solution:
def myAtoi(self, s: str) -> int:
if not s:
return 0
n = len(s)
if n == 0:
return 0
i = 0
while s[i] == ' ':
i += 1
if i == n:
return 0
sign = -1 if s[i] == '-' else 1
if s[i] in ['-', '+']:
i += 1
res, flag = 0, (2**31 - 1) // 10
while i < n:
if not s[i].isdigit():
break
c = int(s[i])
if res > flag or (res == flag and c > 7):
return 2**31 - 1 if sign > 0 else -(2**31)
res = res * 10 + c
i += 1
return sign * res
Complexity
The time complexity is , where is the length of the string. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.