Infix to Postfix Conversion Using Stack in DSA Go - Time & Space Complexity
We want to understand how the time taken to convert an infix expression to postfix grows as the expression gets longer.
How does the number of steps change when the input expression size increases?
Analyze the time complexity of the following code snippet.
func infixToPostfix(expr string) string {
stack := []rune{}
result := ""
for _, ch := range expr {
if isOperand(ch) {
result += string(ch)
} else if ch == '(' {
stack = append(stack, ch)
} else if ch == ')' {
for len(stack) > 0 && stack[len(stack)-1] != '(' {
result += string(stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
stack = stack[:len(stack)-1] // pop '('
} else {
for len(stack) > 0 && precedence(stack[len(stack)-1]) > precedence(ch) {
result += string(stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
stack = append(stack, ch)
}
}
for len(stack) > 0 {
result += string(stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
return result
}
This code converts an infix expression (like "a+b*c") into postfix notation (like "abc*+") using a stack to manage operators.
- Primary operation: Single loop over each character in the input expression.
- How many times: Exactly once per character, so n times where n is expression length.
- Inside the loop, there are inner loops popping from the stack, but each operator is pushed and popped at most once.
As the expression length grows, the number of operations grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 main steps plus some stack pops |
| 100 | About 100 main steps plus stack operations |
| 1000 | About 1000 main steps plus stack operations |
Pattern observation: The total steps increase roughly in direct proportion to the input size.
Time Complexity: O(n)
This means the time to convert grows linearly with the length of the expression.
[X] Wrong: "Because of nested loops, the time complexity is quadratic O(n²)."
[OK] Correct: The inner loops pop operators only once per operator, so total work is proportional to n, not n squared.
Understanding this linear time complexity helps you explain how efficient stack-based parsing is, a skill useful in many coding problems.
"What if the input expression contains multi-digit numbers or variables with multiple letters? How would the time complexity change?"
Practice
Infix to Postfix Conversion?Solution
Step 1: Understand the role of stack in conversion
The stack is used to hold operators temporarily while processing the infix expression to respect operator precedence and associativity.Step 2: Identify what is stored in stack
Operands are directly added to the output, while operators are pushed to the stack to decide their order in postfix.Final Answer:
To temporarily hold operators and manage their precedence -> Option AQuick Check:
Stack holds operators for precedence [OK]
- Thinking stack stores operands
- Confusing stack role with output
- Ignoring operator precedence
Solution
Step 1: Identify correct stack type for operators
Operators are characters, so stack should be a slice of runes (characters) initialized empty.Step 2: Check initialization correctness
var stack []rune = []rune{} initializes an empty rune slice correctly. stack := make([]int, 0) uses int slice, not suitable. stack := []string{0} has syntax error (cannot use int 0 as string). var stack []int = nil is nil slice, which can cause runtime errors.Final Answer:
var stack []rune = []rune{} -> Option AQuick Check:
Empty rune slice for operator stack [OK]
- Using int slice for operators
- Initializing with wrong type
- Using nil slice without initialization
"a+b*c"?
infix := "a+b*c" // Assume correct infix to postfix conversion function called here postfix := InfixToPostfix(infix) fmt.Println(postfix)
Solution
Step 1: Analyze operator precedence in expression
Multiplication (*) has higher precedence than addition (+), so 'b*c' is evaluated before adding 'a'.Step 2: Convert infix to postfix step-by-step
Postfix is formed as 'a' 'b' 'c' '*' '+', which is "abc*+".Final Answer:
"abc*+" -> Option CQuick Check:
Multiplication before addition = "abc*+" [OK]
- Ignoring operator precedence
- Placing + before * in postfix
- Confusing operand order
func precedence(op rune) int {
if op == '+' || op == '-' {
return 1
} else if op == '*' || op == '/' {
return 2
}
return 0
}
// InfixToPostfix function uses precedence(op) to compare operators
// but outputs incorrect postfix for input "a+b^c"Solution
Step 1: Check if all operators are handled
The function handles '+', '-', '*', '/' but misses '^' (exponent) operator which is common in infix expressions.Step 2: Understand impact on output
If input contains '^', missing precedence causes wrong order in postfix output.Final Answer:
Precedence function does not handle '^' operator -> Option DQuick Check:
Missing '^' causes wrong postfix [OK]
- Ignoring missing operators
- Assuming 0 precedence is error
- Confusing precedence values
(a+b)*c?Solution
Step 1: Understand role of parentheses in infix
Parentheses change normal precedence by grouping expressions to evaluate first.Step 2: Modify stack operations for parentheses
Push '(' onto stack when encountered. When ')' is found, pop operators until '(' is popped, discarding both parentheses.Final Answer:
Push '(' onto stack and pop operators until '(' when ')' is found -> Option BQuick Check:
Parentheses control stack push/pop [OK]
- Ignoring parentheses in algorithm
- Treating parentheses as operands
- Not popping until '(' on ')'
Ready to prove it?
Pass the test and this pattern moves unknown
