Skip to main content

8. String to Integer (atoi)

mediumAsked at Goldman Sachs

Implement atoi: parse a string into a signed 32-bit integer, handling whitespace, sign, digits, and overflow clamping. Goldman Sachs uses atoi specifically because it grades how you handle edge cases — the spec has 5 rules and missing any of them is an instant downgrade.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Source citations

Public interview reports confirming this problem appears in Goldman Sachs loops.

  • Glassdoor (2026-Q1)Goldman Sachs SWE phone-screen reports specifically call out atoi as a 'spec-reading' question with 5 mandatory rules.
  • LeetCode Discuss (2025-11)atoi sits in the top-20 of LeetCode's Goldman Sachs company tag.

Problem

Implement the myAtoi(string s) function which converts a string to a 32-bit signed integer. The algorithm: (1) ignore leading whitespace; (2) check for '+' or '-' sign, default '+'; (3) read in digits until non-digit or end of string, treat result as integer; (4) clamp to [-2^31, 2^31 - 1]; (5) return the integer.

Constraints

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

Examples

Example 1

Input
s = "42"
Output
42

Example 2

Input
s = "   -42"
Output
-42

Explanation: Whitespace then sign then digits.

Example 3

Input
s = "4193 with words"
Output
4193

Explanation: Stop at the first non-digit.

Example 4

Input
s = "-91283472332"
Output
-2147483648

Explanation: Out of range; clamp to INT_MIN.

Approaches

1. Step-by-step state machine (optimal)

Four phases: skip whitespace → read sign → accumulate digits with overflow check → return. No regex needed.

Time
O(n)
Space
O(1)
function myAtoi(s) {
  const INT_MAX = 2 ** 31 - 1;
  const INT_MIN = -(2 ** 31);
  let i = 0;
  while (i < s.length && s[i] === ' ') i++;
  let sign = 1;
  if (s[i] === '+' || s[i] === '-') {
    sign = s[i] === '-' ? -1 : 1;
    i++;
  }
  let result = 0;
  while (i < s.length && s[i] >= '0' && s[i] <= '9') {
    const digit = s.charCodeAt(i) - 48;
    if (result > Math.floor(INT_MAX / 10) || (result === Math.floor(INT_MAX / 10) && digit > 7)) {
      return sign === 1 ? INT_MAX : INT_MIN;
    }
    result = result * 10 + digit;
    i++;
  }
  return sign * result;
}

Tradeoff: Linear with constant extra memory. The state-machine structure makes each rule auditable against the spec, which is exactly what Goldman is grading.

2. Regex parse

Use /^\s*([+-]?\d+)/ to capture the leading numeric chunk, then convert and clamp.

Time
O(n)
Space
O(n)
function myAtoiRegex(s) {
  const m = s.match(/^\s*([+-]?\d+)/);
  if (!m) return 0;
  const n = parseInt(m[1], 10);
  const INT_MAX = 2 ** 31 - 1;
  const INT_MIN = -(2 ** 31);
  if (n > INT_MAX) return INT_MAX;
  if (n < INT_MIN) return INT_MIN;
  return n;
}

Tradeoff: Concise but Goldman often disallows built-in parsers because that's the whole point. Mention it as the production answer ('just use parseInt'), but show the state machine for the interview answer.

Goldman Sachs-specific tips

Goldman Sachs interviewers will rapid-fire edge cases at you: '+', '-', '+-2', ' +0 123', '.1'. Have all five clearly itemized at the top of the whiteboard before coding. If you fail to handle one, they'll just feed you the failing input and watch you debug — your fix-loop discipline is part of the grade. Don't use parseInt without permission.

Common mistakes

  • Forgetting to clamp to INT_MAX / INT_MIN — returning -2147483649 or 2147483648 fails the spec.
  • Treating '+-2' as -2 — the spec says only ONE sign character is allowed; everything after a sign+sign sequence is invalid.
  • Stopping at the first non-digit but mishandling 'words and 987' — leading non-whitespace, non-sign, non-digit means return 0.
  • Allowing decimals: '3.14' must return 3, not 3.14.

Follow-up questions

An interviewer at Goldman Sachs may pivot to one of these next:

  • What if leading zeros were allowed and you needed to preserve them in a string view? (Parse separately from the numeric value.)
  • Extend to floating-point atof — adds an optional . then more digits.
  • What if you needed to support arbitrary-precision integers? (BigInt accumulator, no overflow clamp.)

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

FAQ

Why does Goldman ban parseInt or similar built-ins?

Because the question is about your ability to read a spec and translate it into code with edge-case discipline — not about your knowledge of JavaScript's standard library. The same evaluation applies in their Java/C++ rounds.

Is the overflow-check formula always result > INT_MAX / 10?

Almost. You also need the tie-breaker: if result equals INT_MAX / 10 (which is 214748364), the next digit must be <= 7 for + or <= 8 for -. Most candidates miss the equality case and silently overflow on inputs like '2147483648'.

Free learning resources

Curated free links for this problem.

Practice these live with InterviewChamp.AI

Drill String to Integer (atoi) and other Goldman Sachs interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →