Taro Logo

String to Integer (atoi)

#1 Most AskedMedium
Topics:
Strings

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

The algorithm for myAtoi(string s) is as follows:

  1. Whitespace: Ignore any leading whitespace (" ").
  2. Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present.
  3. Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
  4. Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.

Return the integer as the final result.

Example 1:

Input: s = "42"

Output: 42

Explanation:

The underlined characters are what is read in and the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
         ^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "42" ("42" is read in)
           ^

Example 2:

Input: s = " -042"

Output: -42

Explanation:

Step 1: "   -042" (leading whitespace is read and ignored)
            ^
Step 2: "   -042" ('-' is read, so the result should be negative)
             ^
Step 3: "   -042" ("042" is read in, leading zeros ignored in the result)
               ^

Example 3:

Input: s = "1337c0d3"

Output: 1337

Explanation:

Step 1: "1337c0d3" (no characters read because there is no leading whitespace)
         ^
Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit)
             ^

Example 4:

Input: s = "0-1"

Output: 0

Explanation:

Step 1: "0-1" (no characters read because there is no leading whitespace)
         ^
Step 2: "0-1" (no characters read because there is neither a '-' nor '+')
         ^
Step 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit)
          ^

Example 5:

Input: s = "words and 987"

Output: 0

Explanation:

Reading stops at the first non-digit character 'w'.

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. How should we handle strings that contain no valid numerical digits or are completely empty / consist only of whitespace?
  2. What exact return value should we provide if the parsed number overflows or underflows the 32-bit signed integer range?
  3. Can the input string contain leading characters other than whitespace, signs (+/-), and digits, and should they be treated as invalid inputs that terminate parsing immediately?
  4. How should we handle multiple or invalid consecutive sign characters, such as '--12' or '+-5'?
  5. Are there any localization requirements, or can we safely assume the input will only use standard ASCII characters for digits?

Brute Force Solution

Approach

Imagine you have a messy handwritten note containing a mix of letters, spaces, and numbers, and your task is to carefully extract the numerical value hidden inside. The brute force strategy involves examining every single character from the very beginning to understand the full context before attempting to form the final number.

Here's how the algorithm would work step-by-step:

  1. Begin looking at the very first character of the message.
  2. Skip over any empty spaces at the very start because they do not affect the numerical value.
  3. Check if the next character is a plus or a minus sign to determine whether the final number should be positive or negative.
  4. Look at all the remaining characters one by one, keeping track of every single digit you encounter in the exact order they appear.
  5. Stop collecting digits the moment you hit a letter, a punctuation mark, or the end of the entire message.
  6. Combine all the collected digits together into a single numerical value.
  7. Adjust the final value to be negative if you spotted a minus sign earlier.
  8. Check if the resulting number is too large or too small to fit within standard numerical limits, and adjust it to the maximum or minimum possible limit if it overflows.

Code Implementation

class Solution:
    def myAtoi(self, input_string: str) -> int:
        character_index = 0
        total_characters = len(input_string)
        
        # We must skip leading whitespace to find the actual start of the numerical value sequence
        while character_index < total_characters and input_string[character_index] == ' ':
            character_index += 1
            
        if character_index >= total_characters:
            return 0
            
        sign_multiplier = 1
        first_character = input_string[character_index]
        if first_character == '-':
            sign_multiplier = -1
            character_index += 1
        elif first_character == '+':
            character_index += 1
            
        accumulated_number = 0
        # We stop collecting as soon as we encounter any non-digit character to parse correctly
        while character_index < total_characters and input_string[character_index].isdigit():
            current_digit = int(input_string[character_index])
            accumulated_number = accumulated_number * 10 + current_digit
            character_index += 1
            
        final_result = accumulated_number * sign_multiplier
        integer_minimum = -2147483648
        integer_maximum = 2147483647
        
        # We clamp the value because standard 32-bit signed integers cannot exceed these specific bounds
        if final_result < integer_minimum:
            return integer_minimum
            
        if final_result > integer_maximum:
            return integer_maximum
            
        return final_result

Big(O) Analysis

Time Complexity
O(n) – To convert the string to an integer, we iterate through the input string of length n character by character. First, we scan past the leading whitespace, and then we process each subsequent numeric digit sequentially until a non-digit character is encountered or the end of the string is reached. In the worst case, we touch every character in the string exactly once, resulting in approximately 1 * n operations. Simplifying this constant-factor linear scan yields a total time complexity of O(n).
Space Complexity
O(1) – The algorithm only uses a few primitive variables, such as an index pointer to traverse the string, a sign multiplier, and a running total for the numeric value. These variables require a constant amount of extra memory regardless of the input string length N. Since no additional data structures, auxiliary arrays, or recursive call stacks are utilized that scale with N, the space complexity remains strictly constant.

Optimal Solution

Approach

The optimal strategy is like reading a text message from left to right, carefully stripping away meaningless spaces, figuring out if the number is positive or negative, and then building the numerical value digit by digit. As we build the number, we constantly check to make sure it does not grow too large, safely stopping it at the maximum or minimum allowed limits if it overflows.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the very beginning of the text and skip past any empty space characters until you find the first meaningful character.
  2. Check if that first meaningful character is a plus or a minus sign to determine whether the final number should be positive or negative, and remember this choice.
  3. If you do not see a plus or a minus, assume the number is positive and start looking at the characters that follow.
  4. Look at the remaining characters one by one, making sure each one is a valid numerical digit.
  5. As soon as you encounter a character that is not a digit, or if you reach the end of the text, stop looking further.
  6. While building the number digit by digit, constantly check whether the growing value is about to exceed the maximum or minimum allowed limits.
  7. If the growing value is about to go over the upper limit, immediately cap it at the highest possible value and stop.
  8. If the growing value is about to drop below the lower limit, immediately cap it at the lowest possible value and stop.
  9. Once you run out of digits or hit a stopping point, apply the positive or negative sign you remembered at the beginning and deliver the final number.

Code Implementation

class Solution:
    def myAtoi(self, input_string: str) -> int:
        string_index = 0
        string_length = len(input_string)
        
        # Leading whitespace must be skipped to find the start of the integer value.
        while string_index < string_length and input_string[string_index] == ' ':
            string_index += 1
            
        if string_index >= string_length:
            return 0
            
        sign_multiplier = 1
        first_character = input_string[string_index]
        
        # Sign detection establishes whether the resulting integer is positive or negative.
        if first_character == '-':
            sign_multiplier = -1
            string_index += 1
        elif first_character == '+':
            string_index += 1
            
        accumulated_value = 0
        maximum_integer_limit = 2**31 - 1
        minimum_integer_limit = -2**31
        
        # Conversion stops immediately upon encountering any non-digit character.
        while string_index < string_length and input_string[string_index].isdigit():
            current_digit = int(input_string[string_index])
            
            # Overflow detection prevents exceeding 32-bit signed integer boundaries.
            if accumulated_value > (maximum_integer_limit - current_digit) // 10:
                if sign_multiplier == 1:
                    return maximum_integer_limit
                else:
                    return minimum_integer_limit
                    
            accumulated_value = accumulated_value * 10 + current_digit
            string_index += 1
            
        return accumulated_value * sign_multiplier

Big(O) Analysis

Time Complexity
O(n) – To convert the string to an integer, we iterate through the input string of length n from left to right at most once. We first skip leading spaces and evaluate the sign in constant time, then process each subsequent digit character sequentially. Since we visit each character of the string at most once, the total operations scale linearly as roughly 1 * n. This directly simplifies to a Big O time complexity of O(n).
Space Complexity
O(1) – The algorithm processes the input string character by character from left to right using only a constant number of primitive variables to track the sign, the accumulated numerical value, and the current index. No auxiliary data structures, temporary lists, or recursive calls are utilized during this process. Because these few variables consume a fixed amount of extra memory regardless of the input string length N, the auxiliary space complexity remains constant.

Edge Cases

Empty or whitespace-only strings
How to Handle:
The algorithm iterates past all whitespace characters and terminates early, returning zero.
Strings with explicit positive or negative signs
How to Handle:
A sign multiplier variable captures the first '+' or '-' character to correctly negate the final result.
Inputs with non-digit characters immediately following the sign or digits
How to Handle:
Parsing stops at the first non-digit character encountered, returning the accumulated value up to that point.
Integer overflow exceeding 32-bit signed integer limits
How to Handle:
The running total is checked against integer boundary thresholds before multiplication and addition to clamp it correctly.
Leading zeros before the actual number
How to Handle:
Leading zeros are naturally processed as zero additions without affecting the mathematical magnitude of the result.
Strings containing only signs without any digits
How to Handle:
The algorithm detects the lack of valid numeric digits following the sign and safely returns zero.
Extremely long strings of valid digits
How to Handle:
Overflow checking occurs dynamically during iteration, ensuring efficient processing without performance degradation.
Invalid characters appearing before any whitespace or numbers
How to Handle:
The parser immediately halts and returns zero if the first non-whitespace character is not a sign or digit.
0/3 completed