#8

String to Integer (atoi)

Medium
StringHash MapArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Single Pass)
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution still follows the same logic but is implemented in a single pass through the string. We carefully manage the integer conversion and handle overflow without needing to check conditions multiple times.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an index, result, and sign.
  2. 2Step 2: Skip leading whitespace.
  3. 3Step 3: Determine the sign of the number.
  4. 4Step 4: Convert characters to digits while checking for overflow in a single loop.
  5. 5Step 5: Return the final result after applying the sign.
solution.py29 lines
1# Full working Python code with comments
2
3def myAtoi(s: str) -> int:
4    index = 0
5    result = 0
6    sign = 1
7    INT_MAX = 2**31 - 1
8    INT_MIN = -2**31
9
10    # Step 2: Skip leading whitespace
11    while index < len(s) and s[index] == ' ':
12        index += 1
13
14    # Step 3: Check for sign
15    if index < len(s) and (s[index] == '-' or s[index] == '+'):
16        sign = -1 if s[index] == '-' else 1
17        index += 1
18
19    # Step 4: Read digits and check for overflow
20    while index < len(s) and s[index].isdigit():
21        digit = int(s[index])
22        # Check for overflow
23        if result > (INT_MAX - digit) // 10:
24            return INT_MAX if sign == 1 else INT_MIN
25        result = result * 10 + digit
26        index += 1
27
28    return result * sign
29

Complexity note: The time complexity remains O(n) as we still traverse the string once. The space complexity is O(1) since we only use a few variables for computation.

  • 1The key observation is that we can process the string in a single pass, which reduces unnecessary checks and improves efficiency.
  • 2Understanding how to handle overflow is crucial, as it helps avoid errors when converting large numbers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.