EvalFrame Technical Mock Interviews & Coding Practice

String to Integer (atoi)

Medium · String · Algorithm problem · all problems

Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer. The algorithm for `myAtoi(string s)` is as follows: 1. Whitespace: Ignore any leading whitespace (`" "`). 2. Signedness: Determine the sign by checking if the next character is `'-'` or `'+'`, assuming positivity if neither present. 3. Conversion: Read the integer by ignoring leading zeros until a non-digit character is encountered or end of the string is reached. 4. Rounding: If the integer is out of the 32-bit signed integer range `[-2^31, 2^31 - 1]`, clamp it to the boundary. **Examples:** ```typescript myAtoi("42") // 42 myAtoi(" -042") // -42 myAtoi("1337c0d3") // 1337 myAtoi("0-1") // 0 myAtoi("words and 987") // 0 ```

Solve It in the BrowserPractice Explaining It Out Loud

Optimal Approach

  • Time complexity: O(n)
  • Space complexity: O(1)

Single scan of string s of length n.

Follow-Up Questions Interviewers Ask About String to Integer (atoi)

  • Why check digit > 7 against INT_MAX % 10?
    2147483647 ends in 7, so if the prefix equals 214748364, any digit greater than 7 will overflow.

Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.