0

I got this as an interview question.

What is the maximum number of elements that can be on stack at a specific moment while doing a translation from infix form to reversed postfixed Polish form?

I know that the principle is that on the stack there cannot be elements with higher priority (usually * and /) under the ones with smaller priority (+ and -). I tried making an algorithm keeping track of a global and local maximum number, but I didn`t found out a certain rule.

For example if i have infix: 2 - 3 * 4 * 5 / 1 + 10
Stack 1: - * * / => maxLocal = 4 maxGlobal = 4

Stack 2: (After eliminating /, * and * because + has lower priority) - +
=> maxLocal = 2 maxGlobal = 4

Can you please help me?

Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697
Soreena
  • 19
  • 3

1 Answers1

0

I think there is no limit. For example, take the following infix expression:
(1 + (1 + (1 + (1 + (1 + (1 + (1 + …
It is very deep, every time you push yet another element to the stack. Of course there is usually some limit to the number of parentheses you parser accepts, but such limit is purely practical (to prevent stack overflow), not theoretical.

heap underrun
  • 1,846
  • 1
  • 18
  • 22
  • Thanks for your answer, but I did not mean memory limitation, but a sort of rule to determine at any moment of time the maximum number of elements that can be on the stack. – Soreena Jun 18 '12 at 10:07
  • Sorry, I don't quite get it. Convert this infix expression: `(1+(1+(1+(1+(1+(1+(1+1)))))))` into postfix. Then what exactly would get pushed into the stack and how many elements would occur in the stack at maximum? Anyway, the final result of the conversion should be: `1 1 1 1 1 1 1 1 + + + + + + +` (this is the postfix expression). What algorithm are you using to perform the conversion? – heap underrun Jun 18 '12 at 12:37
  • I am using Dijkstra Shunting Algorithm that uses a stack to temporary store the expression`s operators. So on this stack only operators can be pushed from left to right and you cannot have an operator with lower priority above one with higher priority. (i.e you cannot have - above *, then * has to be popped). In the example I gave above I was referring only to the state of stack, not to the final result. – Soreena Jun 19 '12 at 00:13
  • I showed the result just to make sure we both got it the same. In the `(1+(1+(1+(1+(1+(1+(1+1)))))))` case, the stack gradually grows to contain 14 operators: `( + ( + ( + ( + ( + ( + ( + `, and only then it starts to shrink. So in this particular case the maximum is 14. But if the infix contained yet another `(1+` summand in nested parenthesis, the maximum would be 16, and so on. Try out the step-by-step shunting-yard algorithm demo applet at http://www.chris-j.co.uk/parsing.php (enter infix expression, press _Tokenize_, then _Convert_) and look into the stack column. So there is no limit. – heap underrun Jun 19 '12 at 11:50