const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Problem Walkthrough

String to Integer (atoi) LeetCode: Edge-Case Walkthrough

String to Integer (#8) isn't algorithmically hard — it's an edge-case marathon that tests whether you can handle whitespace, signs, overflow, and invalid characters without missing a single rule.

7 min read|

The algorithm is simple — the edge cases are the real problem

Master String to Integer (#8) and learn the defensive programming pattern interviewers love to test

String to Integer (atoi) — The Edge-Case Gauntlet

LeetCode 8, String to Integer (atoi), is one of those problems that looks trivially easy until you start coding it. The core algorithm is straightforward — read characters and build a number. But the problem buries you in edge cases: leading whitespace, optional signs, non-digit characters, integer overflow, and combinations of all of the above.

This is the "easy to code, hard to get right" pattern that interviewers love. The string to integer atoi leetcode problem is not testing whether you can write a loop. It is testing whether you can translate a precise specification into bulletproof code without missing any of the ten-plus edge cases hiding in the problem description.

The key to solving it cleanly is sequential rule processing. Handle each rule in order — whitespace, sign, digits, clamp — and the edge cases resolve themselves. Try to handle everything at once, and you will drown in conditional logic.

Understanding the String to Integer Problem

The problem asks you to implement atoi, the classic C library function that converts a string to a 32-bit signed integer. You are given a string s and must parse it according to a specific set of rules, returning the resulting integer.

The rules are deceptively detailed. First, discard any leading whitespace characters. Then, check for an optional plus or minus sign. Next, read in digits until a non-digit character is encountered or the end of the string is reached. Finally, clamp the result to the 32-bit signed integer range: [-2^31, 2^31 - 1], which is [-2147483648, 2147483647].

If no digits are read at all, the function must return 0. This includes cases where the string is empty, contains only whitespace, or has a sign character followed immediately by a non-digit character.

ℹ️

Interview Favorite

String to Integer (#8) is a favorite at Microsoft and Amazon — it's not about algorithm skill, it's about whether you can handle 10+ edge cases without missing any.

Step-by-Step Rules for Implementing atoi

The entire solution follows five sequential rules. Process them strictly in order and you will handle every edge case the problem throws at you. Trying to be clever or combining steps is how bugs creep in.

Rule 1: Skip leading whitespace. Advance your index past any space characters at the beginning of the string. Do not skip tabs, newlines, or other whitespace variants — the problem only mentions spaces.

Rule 2: Check for a sign. If the current character is a plus or minus sign, record the sign and advance the index by one. If neither sign is present, default to positive. There can be at most one sign character.

Rule 3: Read digits. Continue reading characters as long as they are digits (0-9). For each digit, multiply your running result by 10 and add the digit value. Stop at the first non-digit character or the end of the string.

Rule 4: Clamp to 32-bit range. If the result exceeds 2147483647, return 2147483647. If it is less than -2147483648, return -2147483648. This overflow check must happen during digit processing, not after.

Rule 5: Return 0 if no digits were read. This covers empty strings, whitespace-only strings, and strings where the first non-whitespace, non-sign character is not a digit.

Implementation — Sequential Checks in O(n)

The implementation follows the five rules directly. Initialize an index at 0, a sign variable defaulting to 1, and a result variable at 0. Walk through the string one character at a time, applying each rule in sequence.

For the whitespace step, use a while loop that increments the index as long as the character at that position is a space. For the sign step, check if the character at the current index is a plus or minus, update the sign variable, and advance the index.

For digit reading, use another while loop. At each iteration, extract the digit value by subtracting the character code of "0" from the current character. Before adding the digit to the result, check for overflow: if the result is greater than Math.floor(2147483647 / 10), or if the result equals Math.floor(2147483647 / 10) and the digit is greater than 7, clamp and return immediately.

The time complexity is O(n) where n is the length of the string, since each character is visited at most once. The space complexity is O(1) — you only need the index, sign, and result variables. This is optimal for the string to int conversion problem.

💡

Pro Tip

Process rules strictly in order: whitespace, sign, digits, clamp. Don't try to handle everything simultaneously — sequential processing makes edge cases manageable.

Visual Walkthrough — Five Key Examples

Tracing through examples is the best way to verify your implementation handles every path. Here are five cases that cover the most important scenarios for the string to integer atoi leetcode problem.

Example 1: "42". No whitespace, no sign. Read digits 4 and 2. Result: 42. The simplest happy path.

Example 2: " -42". Skip three spaces. Read minus sign, set sign to -1. Read digits 4 and 2. Apply sign: -42. This tests whitespace and negative sign handling together.

Example 3: "4193 with words". No whitespace, no sign. Read digits 4, 1, 9, 3. Hit space — stop reading. Result: 4193. The trailing non-digit characters are simply ignored.

Example 4: "words and 987". No leading whitespace. First character "w" is not a sign or digit. No digits were read, so return 0. The digits later in the string are irrelevant because a non-digit was encountered first.

Example 5: "-91283472332". Skip whitespace (none). Read minus sign. Read digits and accumulate: the value exceeds 2147483648 during processing. Clamp to -2147483648 (INT_MIN). Overflow detection catches this before the multiplication overflows your number type.

  • "42" -> 42: simple digit parsing
  • " -42" -> -42: whitespace + negative sign
  • "4193 with words" -> 4193: stop at non-digit
  • "words and 987" -> 0: no leading digits found
  • "-91283472332" -> -2147483648: negative overflow clamped to INT_MIN

Edge Cases That Trip Up Interviewees

Beyond the five examples above, several edge cases catch people off guard. Handling these correctly is what separates a passing solution from one that fails on hidden test cases.

Empty string: return 0 immediately. Only whitespace like " ": after skipping whitespace, the index is at the end of the string. No digits are read, return 0.

Only a sign character: "+". After skipping whitespace and reading the sign, the next character does not exist. No digits are read, return 0. This same logic applies to "+" followed by a non-digit, like "+abc".

Positive overflow: "2147483648" should return 2147483647 (INT_MAX). The digit 8 in the ones place exceeds 7 when the accumulated value is already 214748364 (which equals INT_MAX / 10). Your overflow check catches this during the last digit.

Leading zeros: "0000000000012345678" should return 12345678. Leading zeros are valid digits and get processed normally — multiplying 0 by 10 and adding 0 has no effect. The result builds naturally once non-zero digits appear.

  • Empty string or only whitespace: return 0
  • Sign with no digits ("+" or "-"): return 0
  • Positive overflow: clamp to 2147483647
  • Negative overflow: clamp to -2147483648
  • Leading zeros: processed normally, no special handling needed
  • Mixed content after digits: ignored once a non-digit stops parsing
⚠️

Overflow Trap

Overflow detection must happen BEFORE multiplying by 10 — check if result > INT_MAX/10 or (result == INT_MAX/10 and digit > 7) before adding the next digit.

What String to Integer Teaches You

String to Integer (atoi) is the poster child for defensive programming problems. The algorithm itself — a single pass through a string — could not be simpler. The challenge is entirely in translating a precise specification into code that handles every corner case without becoming a tangled mess of if-else branches.

The lesson that transfers to other problems is this: when a problem has many rules, process them sequentially rather than trying to handle them all at once. State-machine-style thinking — where each step has a clear entry condition and exit condition — keeps your code clean and your edge cases contained.

This same approach applies to problems like Roman to Integer (#13), where you process characters left to right with specific rules, and to parsing problems in general. The pattern of "read, validate, transform, clamp" appears throughout string manipulation problems on LeetCode.

Review the string to integer problem with YeetCode flashcards to reinforce the sequential rule processing pattern. When you see a similar edge-case-heavy problem in an interview, you will recognize the structure immediately and avoid the common trap of trying to be too clever.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now