UNIT-II
Rubric: 10m Code + 5m Viva +
5m Record
MEDIUM
15 Marks
Session: 59:59
Bubblewrap Sandbox Active
Problem Statement
Given a string containing only brackets: '(', ')', '{', '}', '[', and ']', determine if the input string is valid.
An input string is valid if:
1. Open brackets are closed by the same type of brackets.
2. Open brackets are closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
Input Format
A single line containing the bracket string S.
Output Format
Print "YES" if the bracket sequence is balanced and valid; otherwise, print "NO".
Constraints
1 <= length(S) <= 10^5
S consists solely of the characters '()[]{}'.
Status
Lang
Score
Time
Submitted
No prior submissions for this problem.
Ready
Click Run Code to evaluate against sample test
cases, or Submit Solution for full evaluation.
No compiler or execution errors recorded.
#include <stdio.h>
#include <string.h>
int main() {
char s[100005];
if (scanf("%s", s) != 1) return 0;
char stack[100005];
int top = -1;
for (int i = 0; s[i] != '\0'; i++) {
char c = s[i];
if (c == '(' || c == '{' || c == '[') {
stack[++top] = c;
} else {
if (top == -1) { printf("NO\n"); return 0; }
char o = stack[top--];
if ((c == ')' && o != '(') ||
(c == '}' && o != '{') ||
(c == ']' && o != '[')) {
printf("NO\n"); return 0;
}
}
}
if (top == -1) printf("YES\n");
else printf("NO\n");
return 0;
}
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
string s;
if (!(cin >> s)) return 0;
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') st.push(c);
else {
if (st.empty()) { cout << "NO\n"; return 0; }
char top = st.top(); st.pop();
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) {
cout << "NO\n"; return 0;
}
}
}
cout << (st.empty() ? "YES" : "NO") << endl;
return 0;
}
import java.util.Scanner;
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if (!sc.hasNext()) return;
String s = sc.next();
Deque<Character> st = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') st.push(c);
else {
if (st.isEmpty()) { System.out.println("NO"); return; }
char top = st.pop();
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
System.out.println("NO"); return;
}
}
}
System.out.println(st.isEmpty() ? "YES" : "NO");
}
}
import sys
def main():
s = sys.stdin.read().strip()
if not s:
return
st = []
pairs = {')': '(', '}': '{', ']': '['}
for c in s:
if c in "({[":
st.append(c)
elif c in pairs:
if not st or st[-1] != pairs[c]:
print("NO")
return
st.pop()
print("YES" if not st else "NO")
if __name__ == "__main__":
main()