PPractick

DSA interview question

String to Integer (atoi)

Medium · Algorithms · Topics: string, math

The problem

A configuration loader reads user-typed numbers such as " -42", "4193 with words" or "99999999999" and must turn them into 32-bit integers the way C's atoi does. Skip leading spaces, read an optional sign, read digits until the first non-digit, and clamp anything outside the 32-bit range to INT_MIN or INT_MAX. The parsing is easy; the part interviewers watch is detecting overflow before it happens, without relying on a 64-bit type.

Example: " -42" → -42; "-91283472332" → -2147483648.

Function signature

int myAtoi(const string& s);  // spaces, optional sign, digits; clamped to the int range

Test cases

Input sOutputExplanation
"42"42
" -42"-42Leading spaces and a sign
"4193 with words"4193Stops at the first non-digit
"words and 987"0No digits before a letter
"-91283472332"-2147483648Clamped to INT_MIN
"2147483648"2147483647Clamped to INT_MAX
"+-12"0Only one sign is allowed
" 0000000000012345678"12345678Leading zeros are fine
""0Empty input

(Confirm: only the space character counts as whitespace; the sign must directly precede the digits; out-of-range values clamp.)

How interviewers phrase it

Clarifying questions to ask

  1. Which characters count as whitespace?
  2. What happens on overflow: clamp, or return 0?
  3. Is "+" or "-" alone valid? (It gives 0.)
  4. Can I use a 64-bit integer internally?

Follow-ups to expect

  1. "How do you detect overflow without 64-bit arithmetic?"
  2. "Does clamping to INT_MAX handle negatives correctly?"
  3. "Why stop at the first non-digit?"
  4. "What about a 64-bit accumulator?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in