Evaluate an Integer Expression String with +, -, * and Nested Parentheses
Company: Aiprise
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Overview: Evaluate a valid arithmetic expression string containing non-negative integers, the operators +, - and *, and nested parentheses, and return its exact integer value. Tests tokenizing, operator precedence, left-to-right associativity of subtraction and correct handling of nested parentheses without division.
Constraints
- 1 <= len(expression) <= 10^4
- expression contains only the digits 0 to 9, +, -, *, (, ) and spaces, and is valid under the rules above.
- Each number literal has at most 9 digits. Leading zeros may appear and do not change the value (007 is 7).
- Parentheses are nested at most 100 levels deep.
- The value of every subexpression, and of the whole expression, has absolute value at most 10^15. This exceeds the 32-bit signed range, so use 64-bit integers in languages with fixed-width types; every value stays within ±2^53.
Examples
Input: ('7',)
Expected Output: 7
Explanation: Minimum valid input: a single one-character literal.
Input: ('( ( 007 ) )',)
Expected Output: 7
Explanation: A literal with leading zeros inside redundant nested parentheses, with spaces between every token.
Hints
- Start without parentheses: `*` binds tighter than `+` and `-`, and operators of equal precedence apply from left to right. Work out how to evaluate a flat expression such as `10 - 2 * 3 - 4` in a single pass first.
- To the operators around it, a parenthesized group behaves exactly like a single number. Think about what you must remember about the outer expression while you evaluate a group, given that groups can nest up to 100 levels deep.
- Numbers can span several digits and may have leading zeros, and values can reach 10^15 in magnitude, so read each number whole and use 64-bit integers.