Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Could the input parameter be Null?
Could the input string represent negative numbers?
Could the input string represent numbers larger/smaller than a computer can represent with a standard integer data type?
Could the input string represent have characters other than numbers?
HAPPY CASE
Input: "123"
Output: 123
Input: "-6714"
Output: -6714
EDGE CASE
Input: "what is a 1000"
Output: 0
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
Sort
Two pointer solutions (left and right pointer variables)
Storing the elements of the array in a HashMap or a Set
Traversing the array with a sliding window
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate from left to right and multiply the integer by 10 each time to shift the number.
1) Clean up string
2) Create boolean variable for negatives
3) Create an integer variable
4) Iterate the input string from left to right as long as digit is seen
a) Multiply the integer variable by 10 and add the current indexed integer in the string
5) Handles negative case
6) Handle index out of bound case
7) Return Built Int
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Solution:
def myAtoi(self, s: str) -> int:
# Clean up string
s = s.strip()
if not s:
return 0
# Create boolean variable for negatives
isNeg = False
if s[0] == "-":
isNeg = True
s = s[1:]
elif s[0] == "+":
s = s[1:]
# Create an integer variable
buildInt = 0
i = 0
# Iterate the input string from left to right as long as digit is seen
while i < len(s) and s[i].isdigit():
# Multiply the integer variable by 10 and add the current indexed integer in the string
buildInt = buildInt * 10 + int(s[i])
i += 1
# Handles negative case
buildInt = -1 * buildInt if isNeg else buildInt
# Handle index out of bound case
buildInt = -2**31 if buildInt < -2**31 else buildInt
buildInt = 2 ** 31 - 1 if buildInt > 2 ** 31 - 1 else buildInt
# Return Built Int
return buildInt
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N represents the number of character in the string.