Balanced Brackets

Sort by

recency

|

240 Discussions

|

  • + 0 comments

    My answer with Typescript.

    Idea is remove couple of bracket when it can, then check remaining [s], if it empty mean it fully valid brackets

    function isBalanced(s: string): string {
        let s_memo = ''
    
        while (s_memo != s && s.length > 0) {
            s_memo = s
            s = s.replace(/(\[\]|\{\}|\(\))/g, '')
        }
    
        return s.length > 0 ? 'NO' : 'YES'
    }
    
  • + 0 comments

    JavaScript Solution:-

    function isBalanced(s) {
        let stack = [];
        let matchingBrackets = {
            '(': ')',
            '{': '}',
            '[': ']'
        };
        
        for (let char of s) {
            if (matchingBrackets[char]) {
                stack.push(char);
            } else {
                let top = stack.pop();
                if (matchingBrackets[top] !== char) {
                    return 'NO';
                }
            }
        }
        return stack.length === 0 ? 'YES' : 'NO';
    }
    
  • + 1 comment

    My Python code works for most of the test cases, but is unable to finish within the time limits for some of the test cases. Can anyone help me optimize my code? It starts off by making sure that there is an even number of brackets. Next, if a pair of brackets are next to each other, they get removed. This is continued until there is nothing left, meaning that those brackets are balanced, or until nothing happens, meaning that those brackets are not balanced.

        s = list(s)
        old = []
        front = ["(", "[", "{"]
        back = [")", "]", "}"]
        if len(s) % 2 == 1:
            return "NO"
        while len(s) != 0:
            old = copy.deepcopy(s)
            for a in range(len(s) - 1):
                if s[a] in front and s[a + 1] in back:
                    if front.index(s[a]) == back.index(s[a + 1]):
                        s.pop(a)
                        s.pop(a)
                        break
            if old == s:
                return "NO"
        return "YES"
    
  • + 1 comment

    My Java solution:

    public static String isBalanced(String s) {
            
            Stack<Character> stack = new Stack<>();
            HashMap<Character, Character> map = new HashMap<>();
            map.put(')', '(');
            map.put(']', '[');
            map.put('}', '{');
            
            // \ ({}) \     \ )({}) \
            for (char c : s.toCharArray()) {
                if (map.containsKey(c)) {
                    if (!stack.isEmpty() && stack.peek() == map.get(c)) {
                        stack.pop();
                    } else {
                        return "NO";
                    }
                } else {
                    stack.push(c);
                }
            }
            
            return (stack.isEmpty()) ? "YES" : "NO";
        }
    
  • + 0 comments

    This is my python solution. It's consise and self explanatory if you understand the application of a stack.

    def isBalanced(s):
        stack = []
        open_to_close = {"{": "}", "[": "]", "(": ")"}
        for bracket in s:
            # Open bracket case
            closing_bracket = open_to_close.get(bracket)
            if closing_bracket:
                stack.append(closing_bracket)
            # Close bracket case
            elif not stack or bracket != stack.pop():
                return "NO"
        
        # If we have looped through the entire string and the stack is empty, all opening brackets were closed
        return "NO" if stack else "YES"