{ Balanced Brackets }

Solving the Programming Challenge

Balanced Brackets

Problem

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ].

Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and ().

A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ].

By this logic, we say a sequence of brackets is balanced if the following conditions are met:

It contains no unmatched brackets. The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets. Given strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO.

Read more on the challenge page…


My Solution

I’m providing the solution for Python and JS, please leave on the comments if you found a better way.

def isBalanced(s):
    openers = ['(', '{', '[']
    closers = {
        ')': '(', 
        '}': '{', 
        ']': '['
    }
    bracket_stack = []
    for c in s:
        if c in openers:
            bracket_stack.append(c)
        elif c in closers:
            if len(bracket_stack) == 0:
                return 'NO'

            if bracket_stack.pop() != closers[c]:
                return 'NO'

    if len(bracket_stack) > 0:
        return 'NO'

    return 'YES'
function isBalanced(s) {
    const openers = ['(', '{', '['];
    const closers = {
        ')': '(', 
        '}': '{', 
        ']': '['
    };
    const bracket_stack = [];

    for (let i=0; i<s.length; i++) {
        const c = s.charAt(i);
        if (openers.includes(c)) {
            bracket_stack.push(c);
        } else if (closers[c]) {
            if (bracket_stack.length == 0) {
                return 'NO';
            }

            if (bracket_stack.pop() !== closers[c]) {
                return 'NO';
            }
        }
    }

    if (bracket_stack.length > 0) {
        return 'NO';
    }

    return 'YES';
}

Join the Free Newsletter

A free, weekly e-mail with the best new articles, courses, and special bonuses.

We won't send you spam. Unsubscribe at any time.