📖 6 min read
Last updated on

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:

  1. Skip leading whitespace.
  2. Read an optional + or - sign.
  3. Read digits until a non-digit character or end of string.
  4. Clamp the result to the 32-bit signed integer range: [-2^31, 2^31 - 1].
  5. Return 0 if no valid conversion was possible.

(LeetCode #8)

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.

SkillWhat Interviewers Observe
Edge-case inventoryDo you enumerate all edge cases before coding?
Overflow clampingDo you clamp to [-2^31, 2^31 - 1] correctly?
Sign handlingDo you default to positive if no sign is present?
Non-digit terminationDo you stop at the first non-digit after digits begin?
Whitespace stripping only at the startDo you strip leading spaces only, not trailing or mid-string?

Step 1: Clarifying Questions

  1. What characters count as whitespace? Only spaces (' '). Tabs, newlines, and other whitespace are not part of the spec. Confirming this avoids over-engineering.

  2. 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.

  3. 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.

  4. Can the input be empty? Yes. Return 0.


Step 2: Edge Cases to Enumerate Upfront

State these to the interviewer before writing code:

  1. Leading whitespace — skip spaces only, stop at the first non-space.
  2. Optional sign (+ or -) — default to positive if absent.
  3. No valid digits — e.g., "abc" returns 0.
  4. Non-digit after digits"123abc" returns 123 (stop at 'a').
  5. Overflow"99999999999" returns 2^31 - 1.
  6. Underflow"-99999999999" returns -2^31.
  7. Empty string returns 0.
  8. 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

  1. Strip leading whitespace: advance index while s[i] == ' '.
  2. Check for sign: if s[i] == '-', set sign = -1; if s[i] == '+', set sign = 1. Advance index.
  3. Read digits: while s[i].isdigit(), accumulate result = result * 10 + int(s[i]). Advance index.
  4. Apply sign: result *= sign.
  5. Clamp: max(-2^31, min(2^31 - 1, result)).
  6. 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 i advances through each phase (whitespace, sign, digits) exactly once.
  • Bounds checking on every access. Each while loop checks i < n before accessing s[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

TimeSpace
myAtoiO(n)O(1)

Single pass through the string. No additional data structures.


Common Interview Mistakes

  1. 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.

  2. 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.

  3. Handling + sign. Many candidates skip the + sign case. The problem specifies both + and - as valid. A + sign followed by digits is valid input.

  4. Not bounds-checking i in every while loop. Each while loop must check i < n before accessing s[i]. Missing this causes an IndexError on empty strings or strings with only whitespace.

  5. Forgetting the default result is 0. If no digits are read, return 0. Initializing result = 0 handles this naturally, but candidates sometimes return None or 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.


  • 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.


Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →