MediumStringUpdated Sep 2026

8. String to Integer (atoi)

Asked at Databricks, Netflix, Bloomberg

Difficulty

Medium

Time

O(n)

Space

O(1)

Pattern

String

Companies

3

Problem

Write a function myAtoi(s) that turns a string into a 32-bit signed integer, following a fixed set of parsing rules.

Read the string from left to right in four steps. First, skip any leading spaces. Second, look at the next character: if it is '-' or '+', that sets the sign (negative or positive), and you move past it. If it is anything else, the sign stays positive. Third, read digits one by one and build the number as result = result * 10 + digit. Stop as soon as you hit a character that is not a digit, or reach the end of the string. Any leading zeros are simply part of the number, so "042" becomes 42.

If you never read a single digit, the answer is 0. This covers an empty string, a string of only spaces, and a string whose first non-space character is a letter or a dot.

The last rule is clamping. The result must fit in the 32-bit signed range [-2^31, 2^31 - 1], that is [-2147483648, 2147483647]. If the parsed value would be larger than the maximum, return 2147483647. If it would be smaller than the minimum, return -2147483648.

Four steps on one string

s -04201234Index 0 is skipped, index 1 sets the sign, indices 2-4are the digits.skip spacesread sign: -read digits: 042apply sign and clampEach step moves the reading position forward; a wrongcharacter stops the digit step.
For " -042" we skip the space, take the minus sign, read the digits 042, and end with -42.

Constraints

  • ●0 <= s.length <= 200
  • ●s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'

Examples

Example 1
Inputs = "42"
Output42
WhyNo leading spaces and no sign character, so the sign stays positive. Both characters are digits, giving 42.
Example 2
Inputs = " -042"
Output-42
WhyThe leading space is skipped, then '-' sets the sign to negative. The digits 0, 4, 2 build the value 42, and the leading zero changes nothing. Applying the sign gives -42.
Example 3
Inputs = "1337c0d3"
Output1337
WhyDigits 1, 3, 3, 7 are read. The next character 'c' is not a digit, so parsing stops there and the rest of the string is ignored.
Example 4
Inputs = "words and 987"
Output0
WhyThe first non-space character is 'w', which is not a sign and not a digit. No digits are ever read, so the result is 0.

Asked At

3 companies

How to Think About It

1

Step 1: skip leading whitespace. Step 2: handle optional +/- sign. Step 3: read digits until a non-digit or end of string. Step 4: handle overflow by clamping to [-2^31, 2^31 - 1].

2

Overflow detection: before multiplying by 10 and adding the digit, check if the result would exceed INT_MAX or fall below INT_MIN. If so, clamp.

3

The sign can only appear once. If you encounter a sign character after already reading digits, stop parsing.

4

Edge cases: empty string (return 0), no digits (return 0), INT_MAX/INT_MIN overflow (clamp), leading zeros ("00042" → 42).

Optimal Approach

Step 1: Skip leading whitespace.
Step 2: Check for +/- sign. Set multiplier accordingly.
Step 3: Read digits, building the result: result = result * 10 + digit.
Step 4: After each digit, check for overflow:
If result > INT_MAX, return INT_MAX (positive) or INT_MIN (negative).
Step 5: Apply sign and return.

Overflow check formula: if result > (INT_MAX - digit) / 10, overflow will occur on next step.

Time: O(n) — single pass through the string. Space: O(1).

Build the number digit by digit

s -04201234iStart: i points at the sign after skipping the space.s -04201234iRead 0, 4, 2: result goes 0 → 0 → 4 → 42.result = result * 10 + digitoverflow if result > (INT_MAX - digit) / 10answer = sign * result
Multiply the running result by 10 and add the next digit, checking overflow before each step.
ComplexityTime O(n)Space O(1)We scan the string once from left to right, and only a few integer variables are kept.

What Trips People Up in Real Interviews

1

Not handling leading whitespace. The atoi function skips all leading spaces before processing.

2

Allowing multiple sign characters. Only one +/- sign is allowed at the beginning. If a second sign appears, stop parsing.

3

Not detecting overflow. A 32-bit signed integer has range [-2^31, 2^31 - 1]. If the result exceeds this, clamp to the boundary.

4

Returning 0 for a string with no digits. If the string has no valid digits after optional sign, return 0.

5

Using built-in string-to-int conversion. The problem asks you to implement atoi yourself. Don't use parseInt or stoi.

Solution Code

O(n) time
def myAtoi(s):
    i = 0
    n = len(s)
    while i < n and s[i] == ' ':
        i += 1
    if i == n:
        return 0
    sign = 1
    if s[i] == '+' or s[i] == '-':
        sign = -1 if s[i] == '-' else 1
        i += 1
    result = 0
    while i < n and s[i].isdigit():
        digit = int(s[i])
        if result > (2**31 - 1 - digit) // 10:
            return 2**31 - 1 if sign == 1 else -2**31
        result = result * 10 + digit
        i += 1
    return sign * result

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the String to Integer (atoi) problem?

Implement the `atoi` function which converts a string to a 32-bit signed integer. It must handle leading whitespace, optional sign, non-numeric characters, and overflow. This problem tests careful step-by-step parsing.

How do you solve String to Integer (atoi)?

The optimal approach runs in O(n) time and O(1) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask String to Integer (atoi)?

String to Integer (atoi) is asked at Databricks, Netflix, Bloomberg. It is a medium difficulty problem.

What are common mistakes on String to Integer (atoi)?
  • Not handling leading whitespace. The `atoi` function skips all leading spaces before processing.
  • Allowing multiple sign characters. Only one +/- sign is allowed at the beginning. If a second sign appears, stop parsing.
  • Not detecting overflow. A 32-bit signed integer has range [-2^31, 2^31 - 1]. If the result exceeds this, clamp to the boundary.
  • Returning 0 for a string with no digits. If the string has no valid digits after optional sign, return 0.
  • Using built-in string-to-int conversion. The problem asks you to implement `atoi` yourself. Don't use `parseInt` or `stoi`.