PPractick

DSA interview question

String to Integer (atoi), Implemented Recursively

Medium · Algorithms · Topics: recursion, string

The problem

A configuration loader reads numbers typed by users, such as " -042", "1337px" and "99999999999", and must turn them into 32-bit integers the way C's atoi does: skip leading spaces, read one optional sign, read digits until the first non-digit, and clamp anything outside the 32-bit range. The interviewer wants it written recursively: each call handles one character and passes the value built so far to the next call, so the "loop" becomes the call chain.

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

Function signature

int myAtoi(const string& s);

Test cases

InputOutputExplanation
"42"42
" -042"-42Spaces, a sign and leading zeros
"1337c0d3"1337Stops at the first non-digit
"words and 987"0No digits before the first letter
"-91283472332"-2147483648Clamped to INT_MIN
"+-12"0Only one sign is allowed

(Confirm: only the space character counts as whitespace; no digits means 0; results are clamped to [−2³¹, 2³¹ − 1].)

How interviewers phrase it

Clarifying questions to ask

  1. Which characters count as whitespace? (Only ' ' in LeetCode's version.)
  2. What happens on overflow? (Clamp to INT_MIN or INT_MAX.)
  3. What if there are no digits? (Return 0.)

Follow-ups to expect

  1. "What does each recursive call do?"
  2. "How do you detect overflow without overflowing?"
  3. "Why keep the sign separately?"
  4. "What's the recursion depth?"
  5. "Iterative vs recursive?"

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