Back to track
#12 Easy Foundations

Balanced Parentheses

Open the editor

Problem

Check if brackets are balanced.

Constraints

1 <= |s| <= 200000
Characters: ()[]{}

Hints

  1. 1

    Use stack

  2. 2

    Match pairs

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  string s; cin >> s;
  vector<char> st;
  for (char c : s) {
    if (c == '(' || c == '[' || c == '{') st.push_back(c);
    else {
      if (st.empty()) { cout << "NO\n"; return 0; }
      char t = st.back(); st.pop_back();
      if ((c == ')' && t != '(') || (c == ']' && t != '[') || (c == '}' && t != '{')) {
        cout << "NO\n"; return 0;
      }
    }
  }
  cout << (st.empty() ? "YES" : "NO") << '\n';
  return 0;
}

© 2026 ChitChat