Be the first user to complete this post

  • 0
Add to List
Medium

410. Evaluation of Prefix Expressions (Polish Notation) | Set 1

Prefix notation is a notation for writing arithmetic expressions in which the operands appear after their operators. There are no precedence rules to learn.

Let's assume the below

  • Operands are real numbers in real digits. (Later we will Enhance the solution for any number)
  • Permitted operators: +,-, *, /, ^(exponentiation)
  • Blanks are NOT permitted in expression.
  • Parenthesis are permitted

Example:

Postfix: +54
Output: 9
Explanation: Infix expression of the above prefix is:  5+ 4 which resolves to 9

Postfix: -/*2*5+3652
Output: 16
Explanation: Infix expression of above prefix is:  2 * (5 *(3+6))/5-2 which resolves to 16

Approach: Use Stack

Algorithm:

Reverse the given expression and Iterate through it, one character at a time

  1. If the character is an operand, push it to the operand stack.
  2. If the character is an operator, 
    1. pop the operand from the stack, say it's s1.
    2. pop another operand from the stack, say it's s2.
    3. perform (s1 operator s2) and push it to stack.
  3. Once the expression iteration is completed, The stack will have the final result. pop from the stack and return the result.

Please see the walkthrough of an example below for more understanding.

Output:

Prefix Expression: -/*2*5+3652
Evaluation: 16.0