Atoi Problem

String to Integer (atoi) 

Problem Statement

Implement the myAtoi(string s) function that converts a string into a 32-bit signed integer (int) using the following rules:

Parsing Rules

  1. Whitespace: Skip all leading whitespace characters.

  2. Sign: Check for an optional '+' or '-' sign.

  3. Digits: Convert digits until a non-digit is found.

  4. Clamp: If the number exceeds 32-bit range:

    [-2^31, 2^31 - 1] = [-2147483648, 2147483647]

    return the clamped value.

  5. Return: The resulting integer.

Example 

Input: s = " -042" Output: -42

Multiple Approaches

Approach 1: Brute Force with Built-in Functions (Not Allowed in Interviews)

Idea: Use built-in parsing and catching exceptions.

public int myAtoi(String s) { s = s.trim(); try { return Integer.parseInt(s.split("[^0-9+-]")[0]); } catch (Exception e) { return 0; } }

Approach 2: Manual Parsing with Overflow Detection (Optimal)

Idea: Process character-by-character. Track whitespace, sign, digits, and overflow manually.

class Solution { public int myAtoi(String s) { int i = 0, n = s.length(); // 1. Skip leading whitespaces while (i < n && s.charAt(i) == ' ') i++; // 2. Check for sign int sign = 1; if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) { sign = (s.charAt(i) == '-') ? -1 : 1; i++; } // 3. Parse digits long result = 0; while (i < n && Character.isDigit(s.charAt(i))) { result = result * 10 + (s.charAt(i++) - '0'); if (sign * result <= Integer.MIN_VALUE) return Integer.MIN_VALUE; if (sign * result >= Integer.MAX_VALUE) return Integer.MAX_VALUE; } return (int)(sign * result); } }

⚠️ Common Mistakes

  • Not skipping leading spaces

  • Forgetting to stop at the first non-digit after digits

  • Overflow not handled

  • No digits after sign → should return 0

📊 Time and Space Complexity Analysis

Step        Time Complexity        Space Complexity
Trim/Loop        O(n)            O(1)
Parsing Digits        O(n)            O(1)
FSM        O(n)            O(1)

🌍 Real-World Applications

  • Parsing numerical config values in user input

  • Interpreting CLI arguments

  • Reading serialized text data

  • Converting CSV fields into usable formats


I hope you found this article insightful! Keep exploring, keep learning, and don’t forget to check back daily for more exciting problem breakdowns. If you know someone who would benefit from this, share it with them and help them grow too! That’s it for today—see you in the next post!

                                                                                                                                         Signing off!! 

                                                                                                Master DSA One Problem at a Time :)

Comments

Popular posts from this blog

Divisible Drama — Who’s In, Who’s Out?

Trailing Zeros in Factorial – How Many and Why?

Minimum equal sum