Balanced Brackets
Level: Beginner 15–30 minConcepts: Algorithms
Solutions: C# | TypeScript | Python
Take an input string with X opening brackets [ and Y closing brackets ], in a random order.
Determine if the generated string of brackets is balanced, that is it consists of pairs of opening/closing brackets in the correct order with no matched opening and closing pairs.
The kata has been structured to be simple, yet loosely guided. You will need to make decisions just like you were writing code for production.
The examples are not meant to guide your implementation, they are there merely to guide you.
Do not worry about input other than brackets and empty string.
Examples
(empty) ""
[] OK
[][] OK
[[]] OK
[[[][]]] OK
][ FAIL
][][ FAIL
[][]][ FAIL
Hint
Start off returning string.empty as the default condition. This will allow you properly work the red-green-refactor cycle.
Reference Walkthrough
Reference implementations in C#, TypeScript, and Python live at tddbuddy-reference-katas/balanced-brackets. This is an F1 kata — 12 scenarios for a single pure function isBalanced(input), shared across all three languages, built around a single-pass depth counter.
- C# (.NET 8, xUnit, FluentAssertions 6.12.0) — walkthrough
- TypeScript (Node 20, Vitest 1.6, TS 5 strict) — walkthrough
- Python (3.11, pytest) — walkthrough
This kata ships in Agent Full-Bake mode at high gear: the algorithm is small enough to land as one commit per language, with a brief walkthrough noting there are no builders because the input and output are the domain. A string goes in, a boolean comes out — no aggregates to construct, no value types to introduce, no collaborators to inject. The canonical “stack-based bracket validation” framing still applies; the references note that because this kata uses only one bracket type, an int depth counter carries the same information as a stack of [ characters, and prefer the counter for that reason.
Solutions
You can find all language solutions here Balanced Brackets Solutions
Or you can select a specific language below.
Related reading
- Katas Are Rehearsal, Not Performance
You don't practice TDD on production code. You practice on katas and bring the muscle memory to production. The gap between knowing TDD and doing TDD is reps. - Test Deletion Is a Privileged Operation
The cheapest way for an agent to make a failing test pass is to delete it. That is logical for the agent and catastrophic for the codebase. Tests are append-only by default. Deletion needs a human author, a separate commit, and a separate review. - Refactor Was Always Where Compounding Lived
Red and green were the visible two thirds of TDD. Refactor was the optional polish. Codebases that compound did the refactor pass; codebases that accrete did not. Agents skip refactor by default because it has no green-bar reward, and a year of skipped refactors is how a codebase loses its shape.