One line containing only the bracket characters ( ) [ ] { } is given. Print "yes" if every opening bracket is matched by a closing bracket of the same kind in the correct order, otherwise print "no". Correct order means that each closing bracket must be the same kind as the most recently opened bracket that is still unclosed. For example "{[()]}" and "()[]" are yes, while "([)]", "((" and ")(" are no.
Input
The string has length from 1 to 10,000. It contains no characters other than ( ) [ ] { } and no spaces.
Output
yes or no
Example 1 · stdin
{[()()]}
stdout
yes
Example 2 · stdin
([)]
stdout
no
main.py
Error List00F8 ↓ · ⇧F8 ↑
Input (stdin)
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
In other languagesShow solutions by language · 8 languages
This is a stack problem: push opening brackets, and on a closing bracket pop the top and compare kinds. Three traps: counting each kind only misses "([)]"; not checking for an empty stack on a closing bracket makes ")" crash Python pop() with IndexError and is undefined behaviour for C++ std::stack::top(); not checking that the stack is empty at the end lets "(((" pass as yes. Stack tools: Python list with append/pop, JavaScript/TypeScript arrays with push/pop, Java ArrayDeque (recommended over the old Stack class), C# Stack<char>, C++ std::stack (two steps: look with top(), discard with pop()), and in C an array plus a top index. In Craykon use a list: stack.Add(c), the top is stack[stack.Count - 1], and pop with stack.RemoveAt(stack.Count - 1); a Craykon list holds at most 10,000 items, which is why the length limit is 10,000.
Pythonmain.py · 12 lines
def is_balanced(s): match = {")": "(", "]": "[", "}": "{"} stack = [] for c in s: if c in "([{": stack.append(c) elif not stack or stack.pop() != match[c]: return False return not stackprint("yes" if is_balanced(input().strip()) else "no")
JavaScriptmain.js · 13 lines
const s = require("fs").readFileSync(0, "utf8").trim();function isBalanced(s) { const match = { ")": "(", "]": "[", "}": "{" }; const stack = []; for (const c of s) { if ("([{".includes(c)) stack.push(c); else if (stack.length === 0 || stack.pop() !== match[c]) return false; } return stack.length === 0;}console.log(isBalanced(s) ? "yes" : "no");