Recursive Descent Parser - Problem

Build a recursive descent parser for arithmetic expressions that correctly handles operator precedence and parentheses.

Your parser should parse expressions with:

  • Numbers: Non-negative integers (0-9 digits)
  • Operators: + (addition), - (subtraction), * (multiplication), / (integer division)
  • Parentheses: ( and ) for grouping

The parser should follow standard mathematical precedence:

  1. Parentheses (highest priority)
  2. Multiplication and Division (left-to-right)
  3. Addition and Subtraction (left-to-right, lowest priority)

Return the evaluated result of the parsed expression as an integer.

Input & Output

Example 1 — Basic Precedence
$ Input: expression = "2+3*4"
Output: 14
💡 Note: Multiplication has higher precedence: 3*4 = 12, then 2+12 = 14
Example 2 — Parentheses Override
$ Input: expression = "(2+3)*4"
Output: 20
💡 Note: Parentheses first: (2+3) = 5, then 5*4 = 20
Example 3 — Division and Subtraction
$ Input: expression = "10-2*3/2"
Output: 7
💡 Note: Left-to-right for same precedence: 2*3 = 6, 6/2 = 3, then 10-3 = 7

Constraints

  • 1 ≤ expression.length ≤ 1000
  • expression contains only digits, +, -, *, /, (, ), and spaces
  • All intermediate results fit in 32-bit integer range
  • No division by zero

Visualization

Tap to expand
INPUTALGORITHM STEPSFINAL RESULTExpression"2+3*4"Numbers: 2, 3, 4Operators: +, *Precedence: * before +1parseExpression()Handle + and - (lowest precedence)2parseTerm()Handle * and / (higher precedence)3parseFactor()Handle numbers and parentheses4Recursive Evaluation3*4=12, then 2+12=14Parsed Result14Correct precedence:3*4 = 12 firstthen 2+12 = 14Key Insight:Recursive descent parsing mirrors mathematical precedence naturally - each grammarrule becomes a function, and higher precedence operations call lower precedence ones.This creates a clean separation where precedence is handled by the call hierarchy.TutorialsPoint - Recursive Descent Parser | Compiler Design
Asked in
Google 45 Microsoft 35 Facebook 30 Amazon 25
24.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen