Implement the isValidBracketPairString method that checks whether a bracket string has properly matched and ordered brackets.

The input contains a string brackets made of opening and closing parentheses. Your task is to check whether the parentheses are properly balanced.

A valid bracket pair string means every opening parenthesis ( has a matching closing parenthesis ), and a closing parenthesis must never appear before its matching opening parenthesis. For example, ()() and (()) are valid, but ())( is not.

Example 1

Input
brackets (string) = ()()
Returns (boolean) true

Example 2

Input
brackets (string) = (())
Returns (boolean) true

Example 3

Input
brackets (string) = ())(
Returns (boolean) false

Use a balance counter while scanning the string from left to right.

Increase the balance for every opening parenthesis and decrease it for every closing parenthesis. If the balance becomes negative at any point, a closing parenthesis appeared too early, so return false. At the end, the balance must be 0.

Pseudocode:

function isValidBracketPairString(brackets):
    balance = 0
    for each character ch in brackets:
        if ch == '(':
            balance++
        else if ch == ')':
            balance--
        if balance < 0:
            return false
    return balance == 0
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.