How can we evaluate infix expressions in Data Structures and Algorithms (DSA)?
Loading
How can we evaluate infix expressions in Data Structures and Algorithms (DSA)?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sandhiya PriyaPosted Jan 1, 2026, 7:16 AM
What is an Infix Expression?
An infix expression is the standard way we write math: operators are placed between operands.
Example:
A + B * CThe challenge: You can’t just evaluate left to right because multiplication/division have higher precedence than addition/subtraction.
How to Evaluate Infix Expressions
There are two main approaches:
1. Convert Infix ? Postfix (or Prefix) and Evaluate
Use the Shunting Yard Algorithm (by Dijkstra) to convert infix to postfix.
Then evaluate the postfix expression using a stack.
Steps:
Scan the infix expression left to right.
Use a stack to store operators and parentheses.
Apply precedence and associativity rules to reorder operators.
Generate a postfix expression.
Evaluate postfix using another stack (push operands, pop two when operator appears, apply operator, push result).
Example:
2. Direct Evaluation Using Two Stacks
Maintain two stacks:
Operand stack (numbers)
Operator stack (+, -, *, /, etc.)
Algorithm:
Scan the infix expression left to right.
Push operands onto the operand stack.
Push operators onto the operator stack, but handle precedence:
If the new operator has lower/equal precedence than the top of the stack, pop and evaluate first.
Handle parentheses by pushing
(and popping until you find it.At the end, apply remaining operators.
Example:
Comparison of Approaches
In Practice
Postfix conversion + evaluation is the most common in DSA courses and competitive programming because it’s easier to implement and debug.
Direct two-stack evaluation is closer to how compilers/interpreters work internally.
Jayraj ChhayaPosted Oct 8, 2024, 6:02 AM
To evaluate infix expressions, we generally follow a two-step process: conversion to postfix notation (also known as Reverse Polish Notation) and then evaluation of the postfix expression.
Conversion to Postfix: This can be achieved using the Shunting Yard algorithm developed by Edsger Dijkstra. The algorithm utilizes a stack to hold operators and ensures that the output maintains the correct order of operations (precedence and associativity).