Solve String Addition and Expression Evaluation
Company: Bytedance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates string manipulation and parsing skills for numeric computation, covering addition of integers represented as character arrays and correct evaluation of arithmetic expressions with operator precedence.
Part 1: Add Two Numbers from Character Arrays
Constraints
- 1 <= len(digits1), len(digits2) <= 100000
- Each element of digits1 and digits2 is a character from '0' to '9'
- The input numbers have no leading zeros unless the number itself is zero
- You must not convert the entire input into a built-in integer type
Examples
Input: (['1', '2', '3'], ['9', '9'])
Expected Output: "222"
Explanation: 123 + 99 = 222.
Input: (['9', '9', '9'], ['1'])
Expected Output: "1000"
Explanation: A carry propagates through all digits.
Input: (['0'], ['0'])
Expected Output: "0"
Explanation: Edge case: both numbers are zero.
Input: (['5'], ['5'])
Expected Output: "10"
Explanation: Single-digit addition that creates a new leading digit.
Hints
- Start from the last digit of each array and move left, just like grade-school addition.
- Keep track of a carry value after adding each pair of digits.
Part 2: Evaluate a Basic Arithmetic Expression
Constraints
- 1 <= len(expression) <= 100000
- The expression contains only digits, spaces, and the operators '+', '-', '*', '/'
- The expression is guaranteed to be valid and contains no parentheses
- Division by zero will not occur
- Integer division must truncate toward zero
Examples
Input: "3+2*2"
Expected Output: 7
Explanation: Multiplication happens first: 2 * 2 = 4, then 3 + 4 = 7.
Input: " 14-3/2 "
Expected Output: 13
Explanation: 3 / 2 truncates toward zero to become 1, so 14 - 1 = 13.
Input: "42"
Expected Output: 42
Explanation: Edge case: the expression is just a single number.
Input: " 3+5 / 2 "
Expected Output: 5
Explanation: 5 / 2 truncates toward zero to 2, so 3 + 2 = 5.
Input: "0-3/2"
Expected Output: -1
Explanation: 3 / 2 becomes 1, so 0 - 1 = -1.
Hints
- You do not need a full parser. Process the string left to right while remembering the previous operator.
- A stack is a simple way to handle precedence: push numbers for + and -, but immediately combine for * and /.