Site icon DocMCQs.Com

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

a) Queue
b) Stack
c) Tree
d) Array

How it works:

  1. 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.
  2. 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.

Exit mobile version