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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code