Solve expression evaluator and string decoder
Company: Instacart
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability in parsing, expression evaluation, and nested string decoding, including handling malformed input, character encoding nuances, and large-file streaming considerations.
Part 1: Arithmetic Expression Evaluator
Constraints
- 0 <= len(expressions) <= 10^4
- 0 <= len(expressions[i]) <= 10^5
- The total number of characters across all expressions is at most 2 * 10^5
- Valid integer results and intermediate values must fit in signed 64-bit range: [-2^63, 2^63 - 1]
- Allowed non-whitespace characters are digits, '+', '-', '*', '/', '(', and ')'
Examples
Input: (['1 + 2 * 3', '(8 + 4) / 3'],)
Expected Output: ['7', '4']
Explanation: Multiplication is evaluated before addition. Parentheses override precedence. Division truncates toward zero.
Input: (['14 - 3 * 2 + 8 / 3', '18 / (3 * (2 + 1))'],)
Expected Output: ['10', '2']
Explanation: The first expression is 14 - 6 + 2 = 10. The second is 18 / 9 = 2.
Hints
- Use either recursive descent parsing with grammar levels for expression, term, and factor, or use two stacks/shunting-yard to enforce precedence.
- Validate as you parse: after every arithmetic operation, check for divide-by-zero and signed 64-bit overflow.
Part 2: Nested k[encoded_string] String Decoder
Constraints
- 0 <= len(s) <= 10^5
- Repeat counts contain ASCII digits '0' through '9'
- A repeat count must be immediately followed by '['
- Literal characters may be any non-digit, non-bracket Unicode characters
- The decoded output length is limited to 10^5 characters
Examples
Input: ('3[a2[c]]',)
Expected Output: 'accaccacc'
Explanation: The inner pattern 2[c] becomes cc, so a2[c] becomes acc, repeated 3 times.
Input: ('10[a]',)
Expected Output: 'aaaaaaaaaa'
Explanation: Multi-digit repeat counts are supported.
Hints
- Use a stack. When you see k[, push the current decoded prefix and k, then start a new current segment.
- When you see ], pop the previous prefix and count, repeat the current segment, and append it to the previous prefix.