GATE / CS ARCHIVE

GATE CSE 2004 / QUESTION 5

Balanced parentheses

Data Structures · Stacks & Queues · Full GATE CSE 2004 paper

GATE 2004, Q5 1 mark · MCQ
Report issue

Stacks & Queues

Question 5, GATE 2004: Which listed data structure is best for checking whether parentheses in an arithmetic expression are balanced?
Options:
(A) Queue
(B) Stack
(C) Tree
(D) List
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. A stack matches each closing delimiter with the most recently unmatched opening delimiter. Reject an unmatched/mismatched close and accept only if the stack is empty at the end.

2. Thus B. With only one kind of parenthesis a counter is sufficient, but stack is the appropriate listed general delimiter-matching structure.

3. Teaching check: On an opening parenthesis, push it; on a closing one, require and pop its matching opener. The last-in-first-out rule handles nesting such as (()()). A FIFO queue does not retain the most recently opened delimiter at its removal end.

Original paper, page 1