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
Constraints
- ●
0 <= s.length <= 200 - ●
s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'
Examples
s = "42"42s = " -042"-42s = "1337c0d3"1337s = "words and 987"0Asked At
3 companies| Company | Difficulty | |
|---|---|---|
| Databricks | Medium | View all Databricks questions → |
| Netflix | Medium | View all Netflix questions → |
| Bloomberg | Medium | View all Bloomberg questions → |
How to Think About It
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].
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.
The sign can only appear once. If you encounter a sign character after already reading digits, stop parsing.
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
What Trips People Up in Real Interviews
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.
Solution Code
O(n) timedef 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 * resultFrequently 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`.