0

I am implementing balanced parenthesis problem on hacker rank. link When i run my program on hackerrank ide, it shows following ⚠warning .

Solution.cpp: In function ‘std::__cxx11::string isBalanced(std::__cxx11::string)’:
Solution.cpp:51:17: warning: this ‘if’ clause does not guard... [-Wmisleading-indentation]
                 if('{'!=s[i])
                 ^~
Solution.cpp:54:21: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the ‘if’
                     bracket.pop();
                     ^~~~~~~
Solution.cpp:25:16: error: control reaches end of non-void function [-Werror=return-type]
     stack<char>bracket;
                ^~~~~~~
cc1plus: some warnings being treated as errors

When i run my program in local computer, then my program crashes after reading a integer (test case).
For ease of code i added comment to it.
The problem is showing in isBalanced() function.
My Code:

#include <bits/stdc++.h>

using namespace std;

// return true if the passed character belongs to ar[], false otherwise
bool find(char ch,char ar[]){
    for(int i=0;i<3;i++)
        if(ar[i]==ch)
            return true;

    return false;
}


string isBalanced(string s) {
    int size=s.length();
    stack<char>bracket;
    char open[3]={'{','[','('};

    // if size of string is odd then expression is not balanced
    if(size%2!=0)
        return "NO";

    for(int i=0;i<size;i++){
    // if current bracket is opening bracket
    // then push it into bracket stack
    if(find(s[i],open)){
        bracket.push(s[i]);
    }
    // if current bracket is closing bracket
    // then match top element of bracket stack with current bracket
    // if both are matched then pop an element from bracket stack
    // if both are not matched return "NO"
    else{
        // if there is an element to match and current stack is empty then expression is not balanced
        if(bracket.empty())
        return "NO";

        else
        switch (bracket.top()) {
         case '{': 

                if('{'!=s[i])
                 return "NO";

                 bracket.pop();
             break;

        case '(':
        if('('!=s[i])
            return "NO";

        bracket.pop();
        break;

        case '[':
        if('['!=s[i])
            return "NO";

        bracket.pop();
        break;
        }

        bracket.pop();
    }
    return "YES";
}

}

int main()
{
    int t;
    cin >> t;
    for (int t_itr = 0; t_itr < t; t_itr++) {
        string s;
        getline(cin, s);
        string result = isBalanced(s);
        cout << result << "\n";
    }
    return 0;
}

  • Your function `isBalanced` does not return a value if `size <= 0`, that means it will invoke undefined behavior if `s` is the empty string. This is your problem. Make sure your function always returns a value and look at [this question](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) to fix how you read input. – nick Apr 25 '20 at 05:34
  • Crashes are a blessing. If the program crashes, run the program in whatever debugger comes with your development environment. When the program crashes, the debugger will halt and let you examine the crash site to gather clues. – user4581301 Apr 25 '20 at 05:46

1 Answers1

0

Two things:

  1. Do not mix getline and operator >>. Either do this:
int main()
{
    int t;
    cin >> t;
    cin.ignore();
    for (int t_itr = 0; t_itr < t; t_itr++) {
        string s;
        getline(cin, s);
        string result = isBalanced(s);
        cout << result << "\n";
    }
    return 0;
}

or do this:

int main()
{
    int t;
    cin >> t;
    for (int t_itr = 0; t_itr < t; t_itr++) {
        string s;
        cin >> s;
        string result = isBalanced(s);
        cout << result << "\n";
    }
    return 0;
}

whichever suits your case.

  1. Your logic is flawed. Here's the corrected implementation of isBalanced():
string isBalanced(string s) {
    int size=s.length();
    stack<char>bracket;
    char open[3]={'{','[','('};

    if(size%2!=0)
        return "NO";

    for(int i=0;i<size;i++){
        cout << i << endl;
        if(find(s[i],open)){
            bracket.push(s[i]);
        }
        else{
            if(bracket.empty())
                return "NO";
            else
            {
                switch (bracket.top()) {
                    case '{': 
                        if('}'!=s[i])
                            return "NO";
                        break;

                    case '(':
                        if(')'!=s[i])
                            return "NO";
                        break;

                    case '[':
                        if(']'!=s[i])
                            return "NO";
                    break;
                }
                bracket.pop();
            }
        }
    }
    return bracket.empty() ? "YES" : "NO";
}

An advice: Please always have proper indentation.

theWiseBro
  • 1,260
  • 6
  • 8