LeetCode 8: String to Integer (atoi) | Java | Optimal Solution

Problem: String to Integer (atoi) (LeetCode 8) Given a string, convert it into a 32-bit signed integer following specific parsing rules. Approach We simulate the conversion process manually. The algorithm: Ignore leading whitespaces Detect optional sign Read digits one by one Stop when a non-digit character is encountered Handle overflow according to 32-bit integer limits Steps: Skip leading spaces. Determine sign. Read consecutive digits. Check overflow before updating result. Return final signed integer. Time Complexity O(n) — Each character is processed at most once. Space Complexity O(1) Pattern String Parsing Key Insight Instead of using built-in conversion functions, parse the string manually while respecting all constraints. Optimality The string must be read at least once, making O(n) the optimal time complexity. Common Pitfall Forgetting to handle overflow. Not stopping at the first non-digit character. Mishandling sign characters. Takeaway Whenever a problem requires converting structured text into a value, think about parsing it character by character.