wiz-icon
MyQuestionIcon
MyQuestionIcon
1
You visited us 1 times! Enjoying our articles? Unlock Full Access!
Question

The best data structure to check whether an arithmetic expression has balanced parenthesis is a

A
stack
Right on! Give the BNAT exam to get a 100% scholarship for BYJUS courses
B
list
No worries! We‘ve got your back. Try BYJU‘S free classes today!
C
queue
No worries! We‘ve got your back. Try BYJU‘S free classes today!
D
tree
No worries! We‘ve got your back. Try BYJU‘S free classes today!
Open in App
Solution

The correct option is A stack
The stack is a data structure in which each push (insert) or pop (delete) operation takes constant θ(1) time. The best data structure to check whether an arithmetic expression has a balanced parenthesis.

Step 1: Start with empty stack of currently open parenthesis
Step 2: Process each char of an expression string
Step 3: If it is open, push it on the stack
Step 4: If it is closed, check it against the top of stack element
Step 4.1: If stack empty or not a matching parenthesis then not balanced and return false
step 4.2: Otherwise it matches. pop the open parenthesis then go to step 2
Step 5: If stack is empty at the end, return true
Step 6: If not empty then some parenthesis is unmatched, return false

flag
Suggest Corrections
thumbs-up
0
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Data and Its Classifications
STATISTICS
Watch in App
Join BYJU'S Learning Program
CrossIcon