String to Integer (atoi) — Coding Interview Walkthrough
You’re in a coding interview. The interviewer says: “Implement the atoi function.” You think, that’s just parsing a string into an integer, right? Then the edge cases start: leading whitespace, an optional sign, non-digit characters that terminate parsing, and 32-bit integer overflow. String to Integer is LeetCode #8, and it’s almost entirely an exercise in disciplined edge-case handling.
This walkthrough shows how a strong candidate enumerates all edge cases before writing a single line of code, then implements a clean single-pass solution that handles every one.
The Problem
Implement myAtoi(s: str) -> int which converts a string to a 32-bit signed integer. The rules:
- Skip leading whitespace.
- Read an optional
+or-sign. - Read digits until a non-digit character or end of string.
- Clamp the result to the 32-bit signed integer range:
[-2^31, 2^31 - 1]. - Return 0 if no valid conversion was possible.
Example 1
Input
s = "42"
Output
42
Example 2
Input
s = " -42"
Output
-42
Example 3
Input
s = "4193 with words"
Output
4193
Example 4
Input
s = "words and 987"
Output
0
Already comfortable with the solution? Practice it in a mock interview →
What Interviewers Are Actually Testing
String to Integer isn’t algorithmically difficult. The challenge is demonstrating that you can systematically identify and handle every edge case without missing any. Interviewers use this problem to see whether you think before you code.
| Skill | What Interviewers Observe |
|---|---|
| Edge-case inventory | Do you enumerate all edge cases before coding? |
| Overflow clamping | Do you clamp to [-2^31, 2^31 - 1] correctly? |
| Sign handling | Do you default to positive if no sign is present? |
| Non-digit termination | Do you stop at the first non-digit after digits begin? |
| Whitespace stripping only at the start | Do you strip leading spaces only, not trailing or mid-string? |
Step 1: Clarifying Questions
-
What characters count as whitespace? Only spaces (
' '). Tabs, newlines, and other whitespace are not part of the spec. Confirming this avoids over-engineering. -
What happens with
"+-12"? Only one sign character is allowed. After reading+, the next character-is not a digit, so digit parsing never starts and the result is 0. -
Is Python’s arbitrary precision a concern? Yes, in the sense that Python won’t overflow naturally. You must explicitly clamp to the 32-bit range. In C++ or Java, you’d need to check before each digit accumulation.
-
Can the input be empty? Yes. Return 0.
Step 2: Edge Cases to Enumerate Upfront
State these to the interviewer before writing code:
- Leading whitespace — skip spaces only, stop at the first non-space.
- Optional sign (
+or-) — default to positive if absent. - No valid digits — e.g.,
"abc"returns 0. - Non-digit after digits —
"123abc"returns 123 (stop at'a'). - Overflow —
"99999999999"returns2^31 - 1. - Underflow —
"-99999999999"returns-2^31. - Empty string returns 0.
- Only whitespace returns 0.
Step 3: A First (Non-Optimal) Idea
You could use Python’s built-in int() with exception handling: strip whitespace, read sign, extract consecutive digits, convert. But interviewers want to see you implement the parsing manually. The manual approach is already O(n) and O(1) space, so there’s no brute-force-to-optimal progression here. The “optimization” is in completeness of edge-case handling.
Step 4: Algorithm
- Strip leading whitespace: advance index while
s[i] == ' '. - Check for sign: if
s[i] == '-', setsign = -1; ifs[i] == '+', setsign = 1. Advance index. - Read digits: while
s[i].isdigit(), accumulateresult = result * 10 + int(s[i]). Advance index. - Apply sign:
result *= sign. - Clamp:
max(-2^31, min(2^31 - 1, result)). - Return result.
Python Implementation
def myAtoi(s: str) -> int:
INT_MIN = -(2**31)
INT_MAX = 2**31 - 1
i = 0
n = len(s)
# Step 1: Skip leading whitespace
while i < n and s[i] == ' ':
i += 1
# Step 2: Read optional sign
sign = 1
if i < n and s[i] in ('+', '-'):
sign = -1 if s[i] == '-' else 1
i += 1
# Step 3: Read digits
result = 0
while i < n and s[i].isdigit():
digit = int(s[i])
result = result * 10 + digit
i += 1
# Step 4: Apply sign and clamp
result *= sign
return max(INT_MIN, min(INT_MAX, result))
Why this is interview-friendly:
- Single pass, no extra data structures. The index
iadvances through each phase (whitespace, sign, digits) exactly once. - Bounds checking on every access. Each
whileloop checksi < nbefore accessings[i], preventing index-out-of-bounds errors. - Clamping is one line.
max(INT_MIN, min(INT_MAX, result))is clean and correct. No branching needed.
Time & Space Complexity
| Time | Space | |
|---|---|---|
| myAtoi | O(n) | O(1) |
Single pass through the string. No additional data structures.
Common Interview Mistakes
-
Stripping all whitespace with
s.strip(). Only leading whitespace is skipped.strip()also removes trailing whitespace, which isn’t part of the spec. More importantly, it hides the manual parsing the interviewer wants to see. -
Not clamping overflow. In Python, integers have arbitrary precision, so overflow doesn’t happen naturally. You must explicitly clamp to
[-2^31, 2^31 - 1]. Missing this is a silent correctness bug. -
Handling
+sign. Many candidates skip the+sign case. The problem specifies both+and-as valid. A+sign followed by digits is valid input. -
Not bounds-checking
iin every while loop. Eachwhileloop must checki < nbefore accessings[i]. Missing this causes anIndexErroron empty strings or strings with only whitespace. -
Forgetting the default result is 0. If no digits are read, return 0. Initializing
result = 0handles this naturally, but candidates sometimes returnNoneor raise an exception instead.
What a Strong Candidate Sounds Like
“Before writing code, let me enumerate the edge cases: leading whitespace, optional sign, non-digit termination, empty string, overflow and underflow. I’ll handle them in order: strip leading spaces, read sign, read digits until a non-digit, apply sign, clamp to 32-bit range. Single pass, O(n) time, O(1) space.”
The key signal: stating all edge cases before coding. This tells the interviewer you won’t discover them one at a time through failed test cases.
Example Interview Dialogue
Interviewer: What does Python’s arbitrary precision mean for this problem?
Candidate: Python integers don’t overflow natively, so result can grow to any size. I need to explicitly clamp the result at the end with max(-2^31, min(2^31 - 1, result)). In a language like Java or C++, integer overflow would happen automatically and incorrectly, so you’d want to check for it before each digit accumulation, something like if result > (INT_MAX - digit) / 10, return INT_MAX.
Interviewer: What’s the output for "+-12"?
Candidate: After reading +, i advances. The next character is -, which is not a digit, so the digit loop doesn’t run. Result is 0.
Interviewer: What about " " (only spaces)?
Candidate: The whitespace loop advances i to n. The sign check sees i >= n and skips. The digit loop also skips. Result is 0. The bounds checking on i < n handles this cleanly.
Related Problems
- Valid Number (LeetCode #65). More complex string parsing that validates whether a string represents a valid number, including exponents and decimals.
- Reverse Integer (LeetCode #7). Integer manipulation with 32-bit overflow handling, the same clamping pattern.
- Integer to Roman (LeetCode #12). Reverse direction: integer to string representation.
Practice This in a Mock Interview
atoi is a problem where the implementation is simple but the edge-case inventory is what separates a complete answer from a partial one. Candidates who jump straight to coding inevitably miss one or two cases and discover them through failed tests, burning time and confidence. State all eight edge cases upfront, then write code that handles them in order.
Start a mock interview for String to Integer (atoi) on Intervu.
Related Problems to Practice
- Valid Palindrome — Character-by-character string parsing.
- Add Binary — Digit-by-digit string processing with carry.
- Longest Palindromic Substring — String traversal with boundary conditions.
Further reading:
- How to Prepare for a Coding Interview in 2026, the complete roadmap and study plans
- Why LeetCode alone isn’t enough, and what to practice instead
- Practice any LeetCode problem as a live mock interview
- The Grind 75 Pathway, a structured study plan with AI practice links
- Browse all walkthroughs on GitHub, condensed solutions with code