Prepin
Log in

Examine the string to determine if the parentheses are properly balanced.

Approach / Explanation

Your objective in this task is to determine if the parentheses in a string are balanced. For parentheses to be balanced, each opening parenthesis must be matched by a closing parenthesis in the reverse order of their opening. For instance, "(()())" and "()(())" are balanced, whereas ")())(()" and "(()" are not. To tackle this problem, you can utilize a Stack data structure. Examine the string from left to right. Each time you find an opening parenthesis, "push" it onto the stack. Upon encountering a closing parenthesis, check the stack: a. If the stack is empty, the parentheses are imbalanced. b. If the stack is not empty, "pop" a parenthesis off the stack. After you have scanned the entire string, the stack should be empty if the parentheses are balanced.

Suggested Answer

For instance, consider the string s = "(()())". The following steps illustrate the process: Examine the string: 1. '(' is an opening parenthesis, so it is added to the stack ['(']. 2. Another '(', which is also added to the stack ['(', '(']. 3. ')' is a closing parenthesis; remove the last opening parenthesis from the stack ['(']. 4. '(' is added to the stack ['(', '(']. 5. ')' removes the last opening parenthesis from the stack ['(']. 6. ')' removes the last opening parenthesis from the stack [], leaving it empty. Since the stack is empty after processing the entire string, this indicates that the parentheses in the string are balanced.

Alternative Answer

As another example, consider the string s = "(()". The following steps illustrate the process: Examine the string: 1. '(' is added to the stack ['(']. 2. '(' is added to the stack ['(', '(']. 3. ')' removes the most recent opening parenthesis from the stack ['(']. Since the stack is not empty at the end, the parentheses in this string are unbalanced.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Meta (Facebook)

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.