The best data structure to check whether an arithmetic expression has balanced…
2004
The best data structure to check whether an arithmetic expression has balanced parentheses is a
- A.
queue
- B.
stack
- C.
tree
- D.
list
Attempted by 1249 students.
Show answer & explanation
Correct answer: B
Key idea: use a stack to match opening and closing brackets (LIFO behavior).
Initialize an empty stack.
Scan the expression left to right. For each character:
If it is an opening bracket ( '(', '{', '[' ), push it onto the stack.
If it is a closing bracket (')', '}', ']'), then:
If the stack is empty, the expression is unbalanced (no matching opening).
Otherwise pop the top element and check it is the corresponding opening bracket type. If it does not match, the expression is unbalanced.
After processing all characters, if the stack is empty the parentheses are balanced; if not, they are unbalanced (there are unmatched opening brackets).
Example walkthrough: for the expression "([{}])" push '(', then '[', then '{'; on encountering '}', pop '{' and it matches; on ']' pop '[' and it matches; on ')' pop '(' and it matches, stack ends empty => balanced.
Complexity:
Time: O(n), where n is the length of the expression (each character is processed once).
Space: O(n) worst-case (all characters are opening brackets and are pushed onto the stack).
A video solution is available for this question — log in and enroll to watch it.