DSA interview question
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.
int myAtoi(const string& s); // spaces, optional sign, digits; clamped to the int range
Input s | Output | Explanation |
|---|---|---|
"42" | 42 | |
" -42" | -42 | Leading spaces and a sign |
"4193 with words" | 4193 | Stops at the first non-digit |
"words and 987" | 0 | No digits before a letter |
"-91283472332" | -2147483648 | Clamped to INT_MIN |
"2147483648" | 2147483647 | Clamped to INT_MAX |
"+-12" | 0 | Only one sign is allowed |
" 0000000000012345678" | 12345678 | Leading zeros are fine |
"" | 0 | Empty input |
(Confirm: only the space character counts as whitespace; the sign must directly precede the digits; out-of-range values clamp.)
"+" or "-" alone valid? (It gives 0.)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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in