You are given a string ‘s’ of size ’n’, representing the prefix form of a valid mathematical expression.
Your task is to find out its corresponding postfix expression.
The expected time and space complexity is O(n) and O(n), where ‘n’ is the size of the string ‘s’.
The only operators used in the expressions are ‘+’, ‘-’, ‘*’, ‘/’.
Input: ‘n’ = 5, ‘s’ = “/A+BC”
Output: ABC+/
Explanation: For ‘s’ = “/A+BC”, the correct postfix expression is “ABC+/”.
The first line is an integer ‘n’, denoting the string ‘s’ size.
The second line contains a string ‘s’, denoting the prefix expression.
Return a string representing the postfix form of the expression.
You don't need to print anything. Just implement the given function.
5
/A+BC
ABC+/
Input: ‘n’ = 5, ‘s’ = “/A+BC”
Output: ABC+/
Explanation: For ‘s’ = “/A+BC”, the correct postfix expression is “ABC+/”.
9
-/A+BC*DE
ABC+/DE*-
Input: ‘n’ = 9, ‘s’ = “-/A+BC*DE”
Output: ABC+/DE*-
Explanation: For ‘s’ = “-/A+BC*DE”, the correct postfix expression is “ABC+/DE*-”.
3 <= n < 10^4
The characters in ‘s’ are either one of {‘+’, ‘-’, ‘/’, ‘*’} or is one of the Uppercase Letters.
Time Limit: 1 sec
Can we use stack?
We can convert a prefix expression into a postfix expression using a stack. First, we will reverse the string and iterate through it. When we encounter an operand, we will push it into the stack. When meeting an operator ‘op’, we will pop two operands from the stack, ‘s1’ and ‘s2’. We will then push into the stack expression ‘s1’+’s2’+’op’, where + means concatenation. Ultimately, we will have our final expression as the only element in the stack.
The steps are as follows:
function preToPost(string s):
O(n), where ‘n’ is the length of string ‘s’.
We are iterating over all the elements of string ‘s’; we push or pop a string from the stack in each iteration. This operation may take an O(n) time due to the length of the string being pushed or popped.
Hence, the time complexity is O(n).
O(n), where ‘n’ is the length of string ‘s’.
We are storing a maximum of ‘n’ characters in the stack.
Hence, the space complexity is O(n).