You are given a string denoting a valid Postfix expression containing ‘+’, ’-’, ’*’, ‘/’ and lowercase letters.
Convert the given Postfix expression into a Prefix expression.
Postfix notation is a method of writing mathematical expressions in which operators are placed after the operands. For example, "a b +" represents the addition of a and b.
Prefix notation is a method of writing mathematical expressions in which operators are placed before the operands. For example, "+ a b" represents the addition of a and b.
Expression contains lowercase English letters, ‘+’, ‘-’, ‘*’, and ‘/’.
Input: abc*+
Output: +a*bc
Explanation:
For the given postfix expression, infix expression is a+b*c. And it's corresponding prefix expression is +a*bc.
The first line of input contains a string ‘s' which denotes the Postfix expression.
Return a string which denotes the corresponding prefix expression.
You do not need to print anything, and it has already been taken care of. Just implement the given function.
ab+cd-*
*+ab-cd
*+ab-cd
For this testcase, the infix expression will be (a + b) * (c - d). Hence, our prefix expression will be *+ab-cd.
ab+c-
-+abc
-+abc
Try to solve this in O(n), where n is the length of expression.
1 <= |s| <= 10^5
Time Limit: 1 sec
Can stack help to solve this problem?
Here, to convert from postfix to prefix, we can simply use stack data structure. We will be following two conditions as follow:
This process should repeat till the end of prefix expression.
O(N) where ‘N’ is the length of the string.
Here, we are iterating over the entire Postfix expression which requires ‘N’ iterations. Hence, our time complexity is O(N).
O(N) where ‘N’ is the length of the string.
Here, we are iterating over the entire Postfix expression which requires ‘N’ iterations, we push each element to the stack. Hence, our space complexity is O(N).