Infix to Postfix Conversion Using Stack in DSA C++ - Time & Space Complexity
We want to know 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.
string infixToPostfix(string infix) {
stack<char> s;
string postfix = "";
for (char c : infix) {
if (isalnum(c))
postfix += c;
else if (c == '(')
s.push(c);
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop();
} else {
while (!s.empty() && precedence(s.top()) >= precedence(c)) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
This code converts an infix expression (like "a+b*c") into postfix form (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 for each character in the input (n times).
- Inside the loop, there can be smaller loops popping from the stack, but each operator is pushed and popped only once overall.
As the input expression length (n) grows, the code processes each character once, plus some extra steps for operators pushed and popped from the stack.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 main steps plus some stack operations (around 15 total) |
| 100 | About 100 main steps plus stack operations (around 150 total) |
| 1000 | About 1000 main steps plus stack operations (around 1500 total) |
Pattern observation: The total steps grow roughly in a straight line with input size, meaning doubling input roughly doubles work.
Time Complexity: O(n)
This means the time to convert grows linearly with the length of the input expression.
[X] Wrong: "Because there is a nested loop popping from the stack, the time complexity is O(n²)."
[OK] Correct: Each operator is pushed and popped only once, so the inner popping loops do not multiply the total steps beyond linear growth.
Understanding this linear time complexity helps you explain how efficient stack-based expression parsing is, a skill useful in many coding problems.
"What if the input expression included multi-digit numbers or variables with multiple characters? 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 the stack
Operands are directly added to the output, while operators are pushed to the stack to manage order and precedence.Final Answer:
To temporarily hold operators and manage their precedence -> Option BQuick Check:
Stack holds operators = D [OK]
- Thinking stack stores operands
- Believing stack reverses the entire expression
- Confusing stack role with counting operators
st in C++?Solution
Step 1: Recall C++ stack push syntax
In C++, the standard stack uses the member functionpush()to add elements.Step 2: Match correct syntax
The correct syntax isst.push(operator);wherestis the stack object.Final Answer:
st.push(operator); -> Option AQuick Check:
Stack push method = st.push() [OK]
- Using non-member functions like push(st, element)
- Using incorrect method names like add()
- Incorrect dot notation like push.operator()
A + B * C?Solution
Step 1: Apply operator precedence rules
Multiplication (*) has higher precedence than addition (+), so B * C is evaluated first.Step 2: Convert to postfix
Postfix places operands first, then operator: B C * then A +, resulting in ABC*+.Final Answer:
ABC*+ -> Option CQuick Check:
Postfix of A + B * C = ABC*+ [OK]
- Ignoring operator precedence
- Placing operators before operands
- Confusing postfix with infix order
std::stack<char> st;
std::string infix = "A+B*C";
std::string postfix = "";
for (char ch : infix) {
if (isalnum(ch))
postfix += ch;
else {
while (!st.empty() && st.top() >= ch) {
postfix += st.top();
st.pop();
}
st.push(ch);
}
}
while (!st.empty()) {
postfix += st.top();
st.pop();
}Solution
Step 1: Analyze operator precedence check
The code compares operators using >= directly on characters, which does not correctly reflect operator precedence.Step 2: Identify correct precedence handling
Operator precedence should be checked using a function that assigns precedence values, not character comparison.Final Answer:
Operator precedence comparison is incorrect -> Option AQuick Check:
Operator precedence needs function, not char compare [OK]
- Comparing operators as characters
- Ignoring precedence rules
- Not popping stack correctly
(A+B)*(C-D)/E to postfix using stack. 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 step-by-step to postfix
A B + (for A+B), C D - (for C-D), then multiply: AB+CD-*, finally divide by E: AB+CD-*E/.Final Answer:
AB+CD-*E/ -> Option DQuick Check:
Postfix of (A+B)*(C-D)/E = AB+CD-*E/ [OK]
- Ignoring parentheses order
- Mixing operator order
- Placing division before multiplication
Ready to prove it?
Pass the test and this pattern moves unknown
