← Create New Paste

String to Integer (atoi) in Coding Interviews: Parsing Rules and Overflow Without Panic

3 views
"Implement atoi" looks like a warm-up, but interviewers like it because it tests something most candidates rush: reading a spec carefully and handling every boundary. Here is a calm way to approach it. 1. Restate the rules before coding Say the contract out loud: skip leading spaces; read an optional '+' or '-'; read digits until the first non-digit; ignore the rest; if no digits were read, return 0; clamp the result to the 32-bit signed range [-2^31, 2^31 - 1]. Ask whether leading zeros, an empty string, or a string like "+-12" need special treatment. Interviewers often leave one rule vague on purpose to see if you ask. 2. Use a single index and three phases Write the parser as a pointer i moving through the string: - Phase 1: while s[i] == ' ', i++. - Phase 2: if s[i] is '+' or '-', record the sign and i++ (only once). - Phase 3: while s[i] is a digit, accumulate. Keeping the phases separate makes the code easy to read and easy to test, and it avoids nested conditionals that hide bugs. 3. Detect overflow before it happens The classic mistake is computing result * 10 + digit and checking afterwards; in languages with fixed-width integers the overflow has already occurred. Instead, check first: if result > (MAX - digit) / 10, then clamp to MAX (or MIN if negative) and return. An alternative is to accumulate as a negative number, since the negative range is one larger, then flip the sign at the end. Either is fine; explain which one you chose and why. 4. Dry-run the nasty inputs Before saying "done", trace a short list: "42", " -42", "4193 with words", "words 4193", "-91283472332", "2147483648", "+", "", "00000123". Each one exercises a different branch. Narrating these out loud shows the interviewer you test like an engineer, not just a solver. 5. Complexity and follow-ups Time is O(n), space O(1). Common follow-ups: support 64-bit, parse floats or scientific notation, or return an error instead of clamping. Mention that real code would usually use the standard library, but that the exercise is about precise state handling. Practicing under pressure Problems like atoi are less about algorithms and more about composure: a nervous candidate skips the spec and loses points on edge cases. Practicing with a timer and talking through your reasoning helps. If you want support during the real thing, Linkjob AI (https://linkjob.ai) gives real-time help during live job interviews and technical interviews, so you can stay structured when the clock is running.
Created Nov 17, 2026 07:02 Expires Nov 17, 2027 07:02