Search code examples
algorithmstackestimationshunting-yard

How can I estimate the stack space needed to turn an infix expression into a postfix expression


There is the famous shunting-yard algorithm that can be used to turn an infix expression (such as 1 + 2 * 3) into a postfix expression (such as 1 2 2 * +). The shunting-yard algorithm needs a stack to store elements that are about to be moved.

Is it possible to pre-estimate the length of the stack needed to perform a translation of a specific input into its postfix form in linear time and constant memory?


Solution

  • Sure. The shunting-yard algorithm only pushes operators (including parentheses) onto the stack, so a first-order approximation is the number of operators in the expression. With a little more intelligence, you could scan the expression and look for associativity and grouping. But by the time you were done, you would probably have written a stack-based algorithm for determining the best estimate of the stack size required for the expression, and would have doubled your execution cost.