{"id":"6b093dddbd4755deb67ee055","slug":"balanced-brackets","title":"Balanced brackets","summary":"Check whether the round, square and curly brackets in a code fragment are properly nested. The textbook use of a stack.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"easy","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["stack","strings","parsing"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** true when (), [] and {} in `code` are balanced; other characters are ignored. */\nfunction isBalanced(code: string): boolean {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"test('empty string and no brackets', () => {\n  expect(isBalanced('')).toBe(true);\n  expect(isBalanced('abc')).toBe(true);\n});\n\ntest('simple and nested pairs', () => {\n  expect(isBalanced('()')).toBe(true);\n  expect(isBalanced('[]{}()')).toBe(true);\n  expect(isBalanced('([{}])')).toBe(true);\n});\n\ntest('wrong kind or interleaving', () => {\n  expect(isBalanced('(]')).toBe(false);\n  expect(isBalanced('([)]')).toBe(false);\n  expect(isBalanced('{[}]')).toBe(false);\n});\n\ntest('closing without opening', () => {\n  expect(isBalanced(')')).toBe(false);\n  expect(isBalanced('())(')).toBe(false);\n});\n\ntest('something left open', () => {\n  expect(isBalanced('((')).toBe(false);\n  expect(isBalanced('{[()]')).toBe(false);\n});\n\ntest('other characters are ignored', () => {\n  expect(isBalanced('function f(a) { return [a, b]; }')).toBe(true);\n  expect(isBalanced('if (x > 0 { y(); }')).toBe(false);\n});\n\ntest('performance: 100 000 levels deep', () => {\n  const n = 100000;\n  const ok = '('.repeat(n) + '[]' + ')'.repeat(n);\n  expect(isBalanced(ok)).toBe(true);\n  expect(isBalanced(ok + '}')).toBe(false);\n  expect(isBalanced('{'.repeat(n) + ']')).toBe(false);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/** true when (), [] and {} in `code` are balanced; other characters are ignored. */\nfunction isBalanced(code) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"test('empty string and no brackets', () => {\n  expect(isBalanced('')).toBe(true);\n  expect(isBalanced('abc')).toBe(true);\n});\n\ntest('simple and nested pairs', () => {\n  expect(isBalanced('()')).toBe(true);\n  expect(isBalanced('[]{}()')).toBe(true);\n  expect(isBalanced('([{}])')).toBe(true);\n});\n\ntest('wrong kind or interleaving', () => {\n  expect(isBalanced('(]')).toBe(false);\n  expect(isBalanced('([)]')).toBe(false);\n  expect(isBalanced('{[}]')).toBe(false);\n});\n\ntest('closing without opening', () => {\n  expect(isBalanced(')')).toBe(false);\n  expect(isBalanced('())(')).toBe(false);\n});\n\ntest('something left open', () => {\n  expect(isBalanced('((')).toBe(false);\n  expect(isBalanced('{[()]')).toBe(false);\n});\n\ntest('other characters are ignored', () => {\n  expect(isBalanced('function f(a) { return [a, b]; }')).toBe(true);\n  expect(isBalanced('if (x > 0 { y(); }')).toBe(false);\n});\n\ntest('performance: 100 000 levels deep', () => {\n  const n = 100000;\n  const ok = '('.repeat(n) + '[]' + ')'.repeat(n);\n  expect(isBalanced(ok)).toBe(true);\n  expect(isBalanced(ok + '}')).toBe(false);\n  expect(isBalanced('{'.repeat(n) + ']')).toBe(false);\n});\n"},{"lang":"python","runner":"browser","starter":"def is_balanced(code: str) -> bool:\n    \"\"\"True when (), [] and {} in `code` are balanced; other characters are ignored.\"\"\"\n    raise NotImplementedError\n","testCount":7,"tests":"def check(code, expected):\n    got = is_balanced(code)\n    assert got is expected, f\"is_balanced({code[:40]!r}): expected {expected}, got {got}\"\n\n\ndef test_empty_and_no_brackets():\n    check(\"\", True)\n    check(\"abc\", True)\n\n\ndef test_simple_and_nested_pairs():\n    check(\"()\", True)\n    check(\"[]{}()\", True)\n    check(\"([{}])\", True)\n\n\ndef test_wrong_kind_or_interleaving():\n    check(\"(]\", False)\n    check(\"([)]\", False)\n    check(\"{[}]\", False)\n\n\ndef test_closing_without_opening():\n    check(\")\", False)\n    check(\"())(\", False)\n\n\ndef test_something_left_open():\n    check(\"((\", False)\n    check(\"{[()]\", False)\n\n\ndef test_other_characters_are_ignored():\n    check(\"function f(a) { return [a, b]; }\", True)\n    check(\"if (x > 0 { y(); }\", False)\n\n\ndef test_performance_100k_levels():\n    n = 100_000\n    ok = \"(\" * n + \"[]\" + \")\" * n\n    check(ok, True)\n    check(ok + \"}\", False)\n    check(\"{\" * n + \"]\", False)\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\n\npublic static class Solution\n{\n    /// <summary>true when (), [] and {} in <paramref name=\"code\"/> are balanced; other characters are ignored.</summary>\n    public static bool IsBalanced(string code)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":7},{"lang":"java","runner":"judge0","starter":"class Solution {\n    /** true when (), [] and {} in code are balanced; other characters are ignored. */\n    static boolean isBalanced(String code) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":7},{"lang":"go","runner":"judge0","starter":"package main\n\n// IsBalanced reports whether (), [] and {} in code are balanced; other characters are ignored.\nfunc IsBalanced(code string) bool {\n\tpanic(\"not implemented\")\n}\n","testCount":7}],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.293Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A code editor highlights an error when brackets go out of sync. We need a function that tells whether the brackets "},{"type":"text","text":"()","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"[]","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"{}","marks":[{"type":"code"}]},{"type":"text","text":" in "},{"type":"text","text":"code","marks":[{"type":"code"}]},{"type":"text","text":" are "},{"type":"text","text":"balanced","marks":[{"type":"bold"}]},{"type":"text","text":": every opening bracket has a closing one of the same kind and pairs do not interleave ("},{"type":"text","text":"([)]","marks":[{"type":"code"}]},{"type":"text","text":" is wrong). All other characters are ignored."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"Return "},{"type":"text","text":"true","marks":[{"type":"code"}]},{"type":"text","text":" when the brackets are correct, otherwise "},{"type":"text","text":"false","marks":[{"type":"code"}]},{"type":"text","text":". An empty string (or one without brackets) is correct."}]},{"type":"paragraph","content":[{"type":"text","text":"Signatures: "},{"type":"text","text":"isBalanced(code)","marks":[{"type":"code"}]},{"type":"text","text":" (JS/TS), "},{"type":"text","text":"is_balanced(code)","marks":[{"type":"code"}]},{"type":"text","text":" (Python), "},{"type":"text","text":"Solution.IsBalanced","marks":[{"type":"code"}]},{"type":"text","text":" (C#), "},{"type":"text","text":"Solution.isBalanced","marks":[{"type":"code"}]},{"type":"text","text":" (Java), "},{"type":"text","text":"IsBalanced","marks":[{"type":"code"}]},{"type":"text","text":" (Go)."}]},{"type":"heading","attrs":{"level":2,"id":"examples"},"content":[{"type":"text","text":"Examples"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"code","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Result"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"([{}])\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"true","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"function f(a) { return [a]; }\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"true","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"([)]\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"false","marks":[{"type":"code"}]},{"type":"text","text":" – pairs interleave"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"())(\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"false","marks":[{"type":"code"}]},{"type":"text","text":" – closing without opening"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"((\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"false","marks":[{"type":"code"}]},{"type":"text","text":" – something is left open"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"0 ≤ code.length ≤ 200,000","marks":[{"type":"code"}]},{"type":"text","text":", ASCII characters."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Nesting can be 100,000 levels deep – recursion is not a good idea."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"O(n)","marks":[{"type":"bold"}]},{"type":"text","text":" time, "},{"type":"text","text":"O(n)","marks":[{"type":"bold"}]},{"type":"text","text":" memory in the worst case (only opening brackets)."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/valid-parentheses/","title":"LeetCode 20 – Valid Parentheses","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:53.296Z","updatedAt":"2026-11-27T08:22:53.296Z"}