Introduction
The String to Integer (atoi) problem asks us to convert a string containing a number into an integer.
While converting, we need to correctly handle:
- Leading spaces
- Positive or negative signs
- Digits
- Non-digit characters
- Integer overflow
For example:
" -42"
should produce:
-42
Problem Statement
Given a string, convert it into a 32-bit signed integer.
Follow these rules:
- Ignore leading spaces.
- Check for an optional + or - sign.
- Read consecutive digits.
- Stop when a non-digit character is encountered.
- If the value exceeds the 32-bit signed integer range, clamp it to the nearest limit.
Example
Input:" -42"
Output:
-42
Another example:
Input:"4193 with words"
Output:
4193
Constraints
- The input can contain letters, digits, spaces, and symbols.
- The result must fit within the 32-bit signed integer range.
- Minimum value: -2147483648
- Maximum value: 2147483647
Approach 1: Brute Force
Explanation
A straightforward approach is to:
- Remove leading spaces.
- Extract the optional sign.
- Collect all consecutive digits.
- Convert the collected digits into an integer.
- Check whether the value is within the valid integer range.
This approach uses a temporary string to store the digits.
Steps
- Skip leading spaces.
- Check for + or -.
- Traverse the remaining characters.
- Stop when a non-digit character is found.
- Store the digits.
- Convert the digits into an integer.
- Handle overflow.
Dry Run
Input:" -42abc"
Skip spaces:
" -42abc"
↑
Sign:
-
Read digits:
4
2
Stop at:
a
Digits:
42
Apply sign:
-42
Output:
-42
Brute Force Code
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n) because the digits are stored separately.
Approach 2: Optimized Solution
Explanation
We can avoid storing the digits separately.
Instead, build the number directly while traversing the string.
For every digit:
number = number × 10 + digit
Before adding a new digit, check whether doing so would cause overflow.
This allows us to process the string in a single pass.
Steps
- Skip leading spaces.
- Determine the sign.
- Initialize the number to 0.
- Read each digit.
- Check for overflow.
- Add the digit to the number.
- Stop at the first non-digit.
- Apply the sign.
Dry Run
Input:" -42abc"
Skip spaces.
Sign:
-
Start:
number = 0
Read 4:
number = 0 × 10 + 4
number = 4
Read 2:
number = 4 × 10 + 2
number = 42
Next character:
a
Stop.
Apply sign:
42 × -1 = -42
Output:
-42
Optimized Code
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Edge Cases
- "42" → 42
- " -42" → -42
- "+42" → 42
- "4193 with words" → 4193
- "words 42" → 0
- "000123" → 123
- Very large positive number → 2147483647
- Very large negative number → -2147483648
- Empty string → 0
Why This Problem is Important
This problem teaches how to carefully process strings while handling:
- Whitespace
- Signs
- Digits
- Invalid characters
- Integer overflow
It is a common interview problem because it tests edge-case handling and implementation accuracy.
Real-World Applications
String-to-number conversion is commonly used in:
- Processing user input
- Reading configuration values
- Parsing command-line arguments
- Processing CSV and text data
- Converting form input into numeric values
Common Mistakes
- Not skipping leading spaces.
- Accepting multiple signs.
- Continuing after encountering a non-digit.
- Forgetting to handle negative numbers.
- Ignoring integer overflow.
- Using a data type that cannot safely hold intermediate values.
Interview Tips
- Explain the parsing rules before writing code.
- Handle spaces first.
- Process the sign before digits.
- Stop immediately at the first non-digit.
- Always discuss 32-bit integer overflow.
- Avoid relying entirely on a built-in conversion function if the interviewer asks for implementation.
Related Questions
- String to Integer Conversion
- Valid Number
- Reverse Integer
- Add Strings
- Multiply Strings
- Compare Version Numbers
Final Takeaway
The String to Integer (atoi) problem requires careful parsing of a string.
The optimized solution processes the input in one pass, builds the number digit by digit, and handles signs and overflow efficiently.
Time Complexity: O(n)
Space Complexity: O(1)