Infix to Postfix Conversion Using Stack in DSA C# - Time & Space Complexity
We want to understand how the time needed 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.
public string InfixToPostfix(string infix) {
Stack<char> stack = new Stack<char>();
StringBuilder postfix = new StringBuilder();
foreach (char ch in infix) {
if (char.IsLetterOrDigit(ch)) {
postfix.Append(ch);
} else if (ch == '(') {
stack.Push(ch);
} else if (ch == ')') {
while (stack.Count > 0 && stack.Peek() != '(') {
postfix.Append(stack.Pop());
}
stack.Pop();
} else {
while (stack.Count > 0 && Precedence(ch) <= Precedence(stack.Peek())) {
postfix.Append(stack.Pop());
}
stack.Push(ch);
}
}
while (stack.Count > 0) {
postfix.Append(stack.Pop());
}
return postfix.ToString();
}
This code converts an infix expression (like "a+b*c") into postfix notation (like "abc*+") using a stack to manage operators.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One main loop that goes through each character of the input expression once.
- How many times: Exactly once per character, so n times if the expression length is n.
- Inside this loop, some stack operations (push/pop) happen, but each character is pushed and popped at most once.
As the input expression gets longer, the number of steps grows roughly in direct proportion to its length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 main steps plus some stack operations |
| 100 | About 100 main steps plus stack operations |
| 1000 | About 1000 main steps plus stack operations |
Pattern observation: The total work grows linearly with the input size.
Time Complexity: O(n)
This means the time to convert grows in a straight line with the size of the input expression.
[X] Wrong: "Because there are nested loops inside, the time must be quadratic O(n²)."
[OK] Correct: The inner loops only pop from the stack, and each character is pushed and popped once, so total operations stay proportional to n, not n squared.
Understanding this linear time complexity helps you explain why stack-based expression parsing is efficient and practical in real coding problems.
"What if the input expression included multi-digit numbers or spaces? 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: Differentiate stack usage from other tasks
The postfix expression is built separately, and the stack is not used to store operands or reverse the expression.Final Answer:
To temporarily hold operators and manage their precedence -> Option AQuick Check:
Stack holds operators = A [OK]
- Thinking stack stores operands
- Confusing stack with output storage
- Assuming stack reverses expression
operatorStack?Solution
Step 1: Recall stack method to add elements
In C#, the method to add an element to a stack isPush().Step 2: Verify other methods are invalid for Stack
Add(),Insert(), andAppend()are not valid methods for the Stack class.Final Answer:
operatorStack.Push('+'); -> Option AQuick Check:
Stack push method = Push() [OK]
- Using Add() instead of Push()
- Confusing List methods with Stack methods
- Trying to use Append() on Stack
A + B * C using standard operator precedence?Solution
Step 1: Apply operator precedence rules
Multiplication (*) has higher precedence than addition (+), so B * C is evaluated first.Step 2: Convert to postfix respecting precedence
Postfix places operands first, then operator: B C * then A +, resulting in ABC*+.Final Answer:
ABC*+ -> Option CQuick Check:
Multiplication before addition = ABC*+ [OK]
- Ignoring operator precedence
- Placing operators before operands
- Confusing postfix order
Stack<char> stack = new Stack<char>();
string infix = "A+B*C";
string postfix = "";
foreach (char ch in infix)
{
if (char.IsLetter(ch))
postfix += ch;
else
stack.Push(ch);
}
while (stack.Count > 0)
postfix += stack.Pop();
Console.WriteLine(postfix);Solution
Step 1: Analyze operator handling in code
The code pushes operators directly onto the stack without checking precedence or popping higher precedence operators first.Step 2: Understand impact on postfix output
This causes incorrect postfix order because operator precedence is ignored.Final Answer:
Operators are pushed without checking precedence -> Option BQuick Check:
Missing precedence check = B [OK]
- Ignoring operator precedence rules
- Assuming stack auto-sorts operators
- Not popping operators when needed
(A+B)*(C-D)/E to postfix using stack-based conversion. What is the correct postfix expression?Solution
Step 1: Handle parentheses and operator precedence
Parentheses force A+B and C-D to be evaluated first, then multiply results, then divide by E.Step 2: Convert stepwise to postfix
A+B becomes AB+, C-D becomes CD-, then multiply: AB+CD-*, then divide by E: AB+CD-*E/.Final Answer:
AB+CD-*E/ -> Option DQuick Check:
Parentheses first, then multiply, then divide = AB+CD-*E/ [OK]
- Ignoring parentheses order
- Mixing operator precedence
- Placing division before multiplication
Ready to prove it?
Pass the test and this pattern moves unknown
