Shunting Yard Algorithm - Problem

The Shunting Yard Algorithm is a method for converting mathematical expressions from infix notation (where operators are between operands, like 3 + 4 * 2) to postfix notation (where operators come after operands, like 3 4 2 * +).

Your task is to implement this algorithm to handle:

  • Basic operators: +, -, *, /
  • Parentheses: ( and ) for grouping
  • Operator precedence: * and / have higher precedence than + and -
  • Left associativity: operators of same precedence are evaluated left to right

Given an infix expression as a string, return the equivalent postfix expression.

Note: The input will contain single-digit numbers, operators, and parentheses separated by spaces.

Input & Output

Example 1 — Basic Precedence
$ Input: expression = "3 + 4 * 2"
Output: "3 4 2 * +"
💡 Note: Multiplication (*) has higher precedence than addition (+), so 4 * 2 is evaluated first. In postfix: 3 4 2 * + means 3 + (4 * 2) = 3 + 8 = 11
Example 2 — Parentheses Override
$ Input: expression = "( 3 + 4 ) * 2"
Output: "3 4 + 2 *"
💡 Note: Parentheses override precedence, so (3 + 4) is evaluated first. In postfix: 3 4 + 2 * means (3 + 4) * 2 = 7 * 2 = 14
Example 3 — Left Associativity
$ Input: expression = "8 - 3 + 1"
Output: "8 3 - 1 +"
💡 Note: Same precedence operators are left-associative, so 8 - 3 is evaluated first. In postfix: 8 3 - 1 + means (8 - 3) + 1 = 5 + 1 = 6

Constraints

  • 1 ≤ expression.length ≤ 1000
  • Expression contains only single-digit numbers (0-9), operators (+, -, *, /), parentheses, and spaces
  • Expression is guaranteed to be valid and well-formed
  • No division by zero will occur

Visualization

Tap to expand
INPUTALGORITHMRESULTInfix Expression3 + 4 * 23+4*2Numbers and operatorsin mathematical order1Stack for Operators* (precedence 2)+ (precedence 1)2Process by Precedence3Output in Postfix OrderPostfix Expression3 4 2 * +342*+Numbers first, thenoperators by precedenceReady for evaluation!Key Insight:The stack manages operator precedence automatically - higher precedence operatorsare output before lower precedence ones, creating correct postfix order.TutorialsPoint - Shunting Yard Algorithm | Stack-Based Approach
Asked in
Google 42 Microsoft 38 Amazon 35 Facebook 28 Apple 25
23.4K Views
Medium Frequency
~35 min Avg. Time
892 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