I am getting segementation fault on submitting balanced parenthesis...HELP

problem link ---- Balanced Brackets | HackerRank

my code ---- I am getting segmentation fault inspite of getting correct answer on unlocked test cases… Please help me solve my mistake

{
    if((a=='('&&b==')') || (a=='{'&&b=='}') || (a=='['&&b==']'))
        return true;
        
    return false;
}
// Complete the isBalanced function below.
string isBalanced(string s) 
{   
    string y ="YES";
    string n = "NO";
    stack<int> sss;
    for(int i=0;i<s.length();i++)
    {
        if(s[i]== '(' || s[i]== '{'  || s[i]== '[' )
            sss.push(s[i]);
            
        else
       {
        if(s.empty())
           return n;
        else if(matching(sss.top(),s[i])==false)
            return n;
        else
            sss.pop();
       }
    }
    
if(sss.empty())
        return y;
    
    return n;
}

Here you go.

#include <bits/stdc++.h>

using namespace std;

// Complete the isBalanced function below.
bool matching(char ch1, char ch2) {
    if(ch1=='(' && ch2 == ')')
        return true;
    else if(ch1 == '{' && ch2 == '}')
        return true;
    else if(ch1 == '[' && ch2 == ']')
        return true;
    return false;
}
string isBalanced(string s) {
    string yes = "YES";
    string no = "NO";
    stack<char> st;
    for(int i=0;i<s.length();i++) {
        if(s[i] == '(' || s[i] == '{' || s[i] == '[') {
            st.push(s[i]);
        }
        else if(!st.empty() && matching(st.top(), s[i])) {
            st.pop();
        }
        else {
            return no;
        }
    }
    return (st.empty()?yes:no);
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    int t;
    cin >> t;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    for (int t_itr = 0; t_itr < t; t_itr++) {
        string s;
        getline(cin, s);

        string result = isBalanced(s);

        fout << result << "\n";
    }

    fout.close();

    return 0;
}

Isn’t it supposed to be

stack <char> sss;

instead of

stack <int> sss;

?

but that shouldn’t give correct answer for unlocked test cases isn’t it ?

I think your mistake is that you’re checking if the string “s” is empty, instead of checking whether the stack “sss” is empty in the for loop! :grin:

//your code:
if(s.empty())
    return n;

//correct code:
if(sss.empty())
    return n;
1 Like

yes , that was my mistake…thanks for solving that

1 Like

@suman_18733097 integer stack also works fine, as ascii code for all characters are integers (and they are unique).

Mention not! :blush:

1 Like