algoadvance

The problem “String to Integer (atoi)” as described on LeetCode is as follows:

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function).

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

  1. Read in and ignore any leading whitespace.
  2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  3. Read in the next characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
  4. Convert these digits into an integer (i.e., "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
  5. If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2^31 should be clamped to -2^31, and integers greater than 2^31 - 1 should be clamped to 2^31 - 1.
  6. Return the integer as the final result.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42

Example 3:

Input: "4193 with words"
Output: 4193

Clarifying Questions

  1. Should the function handle leading and trailing spaces in the string?
    • The function should only handle leading whitespaces according to the problem statement.
  2. How should the function treat invalid input characters?
    • Invalid characters after the numeric part should be ignored. The conversion stops at the first occurrence of an invalid character.
  3. Can the string be empty?
    • Yes, if the string is empty, the function should return 0.
  4. Should the function handle overflow cases?
    • Yes, it should constrain the result to the 32-bit signed integer range.

Strategy

  1. Strip leading whitespaces from the string.
  2. Determine if the number is negative or positive by checking the next character.
  3. Initialize an integer variable to accumulate the number.
  4. Iterate through the string while characters are numeric and convert them to an integer.
  5. Apply the sign to the integer.
  6. Clamp the result to the 32-bit signed integer range if necessary.
  7. Return the result.

Code

def myAtoi(s: str) -> int:
    # Constants for integer limits
    INT_MIN, INT_MAX = -2**31, 2**31 - 1
    
    # Step 1: Ignore leading whitespace
    s = s.lstrip()
    if not s:
        return 0
    
    # Step 2: Check for the sign
    sign = 1
    start_index = 0
    if s[start_index] in ['-', '+']:
        if s[start_index] == '-':
            sign = -1
        start_index += 1
    
    # Step 3 and 4: Read digits and convert to integer
    num = 0
    for i in range(start_index, len(s)):
        if not s[i].isdigit():
            break
        num = num * 10 + int(s[i])
    
    # Apply the sign
    num *= sign
    
    # Step 5: Clamp the integer to be within the 32-bit signed integer range
    if num < INT_MIN:
        return INT_MIN
    if num > INT_MAX:
        return INT_MAX
    
    return num

Time Complexity

The time complexity for this solution is O(n), where n is the length of the input string s. The operations of stripping whitespaces and converting digits are linear with respect to the input length.

Space Complexity

The space complexity is O(1), as only a constant amount of extra space is used, regardless of the input size.

This solution efficiently handles the problem’s requirements and edge cases, providing a correct implementation of the atoi function.

Try our interview co-pilot at AlgoAdvance.com