Ad
Sponsored by Sir Tauqeer
CLICK HERE TO JOIN SIR TAUQUEER WHATSAPP GROUP
FOR PREPARATION CLASSES AND JOBS UPDATES
Join Now

The data structure required to check whether an expression contains a balanced parenthesis is?

A. Queue
B. Stack
C. Tree
D. Array
Correct Answer: B. Stack

LIFO (Last In, First Out) property, This is crucial for matching opening and closing parentheses. The last opening parenthesis encountered should be the first one to be closed.

Efficient push and pop operations: A stack allows for quick insertion (push) and removal (pop) of elements, which is essential for processing the expression character by character.

How it works?

Iterate through the expression

If you encounter an opening parenthesis (like ( or { or , push it onto the stack.

If you encounter a closing parenthesis, pop the top element from the stack.

Compare the popped element with the current closing parenthesis. If they don't match, the expression is unbalanced.

Check for empty stack at the end

If the stack is empty at the end of the expression, the parentheses are balanced.

If the stack is not empty, there are extra opening parentheses, and the expression is unbalanced.

By utilizing the stack's LIFO property, we can effectively keep track of the opening parentheses and ensure they are closed in the correct order.

Leave a Comment

Join Our WhatsApp Channel ×
Scroll to Top