Sort by

recency

|

1616 Discussions

|

  • + 0 comments

    It can be optimized with regex, but here is a solution that can help solving many balancing issues. the idea is to strip all the valid brackets, till we are left with no valid ones. Solution is in Typescript:

    function isBalanced(s: string): string {
        // Write your code here
        let replacedCount = Infinity;
        while (replacedCount > 0) {
            const start = s.length
            s = s.replace('()', '').replace('{}', '').replace('[]', '');
            const end = s.length;
            replacedCount = start - end;
        }
      
      return s.length === 0 ? 'YES' : 'NO';
    }
    
  • + 0 comments

    In C language, not using a stack but mimicking it:

    char* isBalanced(char* s) {
        char* s2 = malloc(strlen(s) * sizeof(char));
        memset(s2, strlen(s), sizeof(char)); // Not mandatory. To keep memory clean
        
        char* p1 = s;
        char* p2 = s2;
        
        bool isBalanced = true;
        
        while (isBalanced && *p1)
        {
            switch (*p1)
            {
                case '{':
                case '(':
                case '[':
                    *(p2++) = *p1;
                    break;
                case '}':
                    if (p2 > s2 && *(p2 - 1) == '{')
                        *(--p2) = '\0';
                    else
                        isBalanced = false;
                    break;
                case ')':
                    if (p2 > s2 && *(p2 - 1) == '(')
                        *(--p2) = '\0';
                    else
                        isBalanced = false;
                    break;
                case ']':
                    if (p2 > s2 && *(p2 - 1) == '[')
                        *(--p2) = '\0';
                    else
                        isBalanced = false;
                    break;
            }
            
            p1++;
        }
        
        if (*p1 == '\0' && p2 > s2)
            isBalanced = false;
        
        free(s2);
        
        char * response = malloc(4 * sizeof(char));
        if (isBalanced)
            strcpy(response, "YES");
        else
            strcpy(response, "NO");
        return response;
    }
    
  • + 3 comments

    Something must be wrong with the compiler, or something is happening behind the scenes. I have some code that is failing 3 cases, but when I unlock the test case and run the input as a custom case it passes just fine.

    (I have a correct solution already, but my friend wanted me to try out this other solution)

     const stack = [];
        let i = 0;
        while (i <= s.length) {
            switch (s[i]) {
                case "(": 
                case "[": 
                case "{": 
                    stack.push(s[i]); 
                    break;
                case ")": 
                    if (stack.pop() !== "(") return "NO"; 
                    break;
                case ']': 
                    if (stack.pop() !== "[") return "NO"; 
                    break;
                case '}': 
                    if (stack.pop() !== "{") return "NO";
                    break;
            }
    												
    												
            i++
        }
    												return "YES"
    
  • + 0 comments

    My C code 😁😎

    char* isBalanced(char* s) {
        if(strlen(s)%2 != 0){
            return "NO";
        }
    
        //parenthese = 0,crochet = 0,bracket = 0;
        int par_g = 0,par_d = 0,cro_g = 0,cro_d = 0,brac_g = 0,brac_d = 0;
    
        for(int i = 0;i<strlen(s);i++){
            if(s[i] == '('){
                par_g++;
            }
            if(s[i] == ')')
            {
                par_d++;
            }
            if(s[i] == '['){
                cro_g++;
            }
            if(s[i] == ']'){
                cro_d++;
            }
            if(s[i] == '{'){
                brac_g++;
            }
            if(s[i] == '}'){
                brac_d++;
            }
            
    
        }
    
        if(((par_d + par_g)%2 != 0) || ((cro_d + cro_g)%2 != 0) || ((brac_g + brac_d)%2 != 0)){
            return "NO";
        }
        if((par_d != par_g) || (cro_d != cro_g) || (brac_d != brac_g)){
            return "NO";
        }
         char stack[10000];
        int top = -1;
    
        for (int i = 0; i < strlen(s); i++) {
            char c = s[i];
            if (c == '(' || c == '{' || c == '[') {
                stack[++top] = c;
            } else {
                if (top == -1)return "NO";
                char topChar = stack[top--];
                if ((c == ')' && topChar != '(') ||
                    (c == '}' && topChar != '{') ||
                    (c == ']' && topChar != '[')) {
                    return "NO";
                }
            }
        }
        return "YES";
    }
    
  • + 1 comment

    My Python submission gives RuntimeError or WrongAnswer in most of the test cases. Anyone knows why?

    def isBalanced(s):
        # Write your code here
        assert len(s) >= 1 and len(s) <= 1e3
        # print(1e3 == 1000)
        
        pairs = {
            "{": "}",
            "(": ")",
            "[": "]"
        }
        brackets = ('{', '}', '(', ')', '[', ']')
        o_brackets = ('{', '(', '[')
        # c_brackets = ('}', ')', ']')
        
        while len(s):
            # print(len(s))
            for c_idx, c in enumerate(s):
                assert c in brackets
                if c in o_brackets:
                    o_c = c
                else:
                    if pairs[o_c] == c:
                        s = s[:c_idx-1]+s[c_idx+1:]
                        break
                    else:
                        return "NO"
        # print(len(s))
        return "YES"