Facebook | Phone Screen | Balance Parentheses

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2019-09-11Added By Anonymous
Source: Link

Company: Meta (Facebook)
Role: e3, e4
Interview Stage: Phone Screen
Location: unknown
Year: unknown

Original Post Content:

Balance Parentheses

My solution

I have an idea to do it in O(N) time, code as below, but I am not sure if I miss some corner case , kindly comment if any corner case this way might not work.

string rmparan(string &s) {
    int nl = 0; // # of '('
    int nr = 0; // # of ')'
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == '(') {
            nl++;
        } else {
            if (nl > 0) {
                nl--;
            } else {
                nr++;
            }
        }
    }
    string ans;
    vector<bool> take(s.size(), true);
    // for ')' , if we get nr > 0 , like case '())'' or ')' , both are okay to remove from left
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == ')' && nr > 0) {
            take[i] = false;
            nr--;
        }
    }
    // for '(' , if nl > 0 , that means right side doesn't have any ')' to pair with it , so remove
    // from right
    for (int i = s.size()-1; i >= 0; i--) {
        if (s[i] == '(' && nl > 0) {
            take[i] = false;
            nl--;
        }
    }
    for (int i = 0; i < s.size(); i++) {
        if (take[i]) {
            ans.push_back(s[i]);
        }
    }
    return ans;
}

Comments