Solve several coding interview problems
GoogleSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to perform string-based arithmetic and handle edge cases in digit-by-digit computation.
Problem: String-Based Addition of Large Numbers
Given two non-negative integers represented as strings num1 and num2, return the sum of the two numbers as a string. You cannot convert the input strings directly to integers (e.g., using int() in Python or parseInt in JS), as the numbers might exceed the maximum capacity of standard integer types.
Constraints
num1.lengthandnum2.lengthare between 1 and 10,000.num1andnum2consist of digits '0'-'9'.num1andnum2do not contain any leading zeros except for the number "0" itself.
Examples
Example 1:
Input: num1 = "11", num2 = "123"
Output: "134"
Example 2:
Input: num1 = "456", num2 = "77"
Output: "533"
Example 3:
Input: num1 = "0", num2 = "0"
Output: "0"
Implementation
def addStrings(num1: str, num2: str) -> str:
# Write your code here
Hints
Hint 1
Start from the last character of each string, representing the least significant digit, and use pointers to move backwards.
Hint 2
Maintain a variable to keep track of the carry as you add corresponding digits from each string.
Hint 3
If one string is longer than the other, continue adding the remaining digits and the carry until all digits are processed.
Follow-up questions
- How would you modify your approach if the numbers were allowed to be negative?
- How would you perform subtraction for two large numbers represented as strings?
- What is the time and space complexity of your solution, and can you optimize the space if the strings are extremely large?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.