Intermediate Level

Implement the checkBalancedScoreBrackets method that checks whether scored bracket text remains balanced.

The input contains a string text made of brackets such as (), [], and {}. Your task is to check whether the brackets are balanced.

A bracket string is balanced when every opening bracket has a matching closing bracket of the same type, and the closing brackets appear in the correct order.

For example, ([]{}) is balanced, but ([)] is not balanced because the closing brackets do not match the most recent opening brackets.

Example 1

Input
text (string) = ([]{})
Returns (boolean) true

Example 2

Input
text (string) = ([)]
Returns (boolean) false

Example 3

Input
text (string) =
Returns (boolean) true

Use a stack to remember opening brackets that have not been closed yet.

When an opening bracket is found, push it onto the stack. When a closing bracket is found, the top of the stack must contain the matching opening bracket. If it does not match, the string is not balanced.

After all characters are processed, the stack must be empty. If anything remains in the stack, some opening brackets were never closed.

Pseudocode:

function checkBalancedScoreBrackets(text):
    create empty stack
    for each character ch in text:
        if ch is opening bracket:
            push ch into stack
        else if ch is closing bracket:
            if stack is empty:
                return false
            top = pop from stack
            if top does not match ch:
                return false
    return stack is empty
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.