Scrivio Interview library
Stacks and queuesStacks, queues and heapsReported 15 times · 15 min read · updated 15 November 2026

Check whether a string of brackets is balanced.

1What it means for brackets to be balanced, told as doors in a house

Imagine walking into a large old house. You open the front door, then the door of the study, and inside the study you open a cupboard. When you leave, there is only one sensible order: the cupboard first, then the study door, and the front door last. You cannot close the study door while the cupboard inside it is still open. The door you must close next is always the one you opened most recently.

Brackets behave in the same way. An opening bracket, one of (, [ or {, is a door being opened. A closing bracket, one of ), ] or }, is a door being closed, and it must close a door of its own kind, so ) closes (, ] closes [, and } closes {. A string of brackets is called balanced when every door that was opened gets closed, by a closer of the same kind, in the right order. We are given such a string and must answer true if it is balanced and false if it is not.

Let us keep one example for the whole article, the string {[()()]}. Read it as a walk through the house. We open a curly door, then a square door inside it, then a round door, and we close the round door at once. We open a second round door and close it too. Then we close the square door and, last of all, the curly one. Every door was closed, each by its own kind, and always the innermost open door first, so the answer is true.

A string can go wrong in only three ways. In ([)] we try to close round while the square door inside it is still open, so the pairs cross. In ()) the last ) closes a door that was never opened. In (() one door is never closed. The problem looks as if it needs clever parsing, but it is smaller than it looks. If we can catch these three mistakes, we are done.

PictureThe example string and its answer

Eight brackets: a curly pair outside, a square pair inside it, and two round pairs innermost.

  1. {0[1(2)3(4)5]6}7
    length
    8
    answer
    true

    1The string {[()()]} is balanced, so the answer is true. Every opener is closed by its own kind, and the innermost one is always closed first.

What to assume

Can the string hold other characters, like the letters in a line of code?
We assume it can, and we skip them, so a(b[c]d)e is balanced.
Is the empty string balanced?
Yes. And the string may be long, so we would like to read it only once.

A careful candidate asks a few questions first. Can the string hold other characters, like the letters in a line of code? We assume it can, and we skip them, so a(b[c]d)e is balanced. Is the empty string balanced? Yes, because no door was opened, so none is left open. And the string may be long, so we would like to read it only once.

2How to recognise that a stack is the right tool

A beginner reading this question often reaches for counting: add one for each opener, subtract one for each closer, and check that we end at zero without ever going below it. For round brackets alone that works. But on ([)] the count goes 1, 2, 1, 0 and never goes negative, so counting says balanced, while the true answer is false. Counting remembers how many doors are open, but not which kinds, and the kind is exactly what went wrong.

So let us read the question again and take its clues one at a time. The first clue is the phrase same type. A closer is not just any closer; it must match one particular opener. That tells us we must remember the kind of every opener that is still waiting, not merely how many of them there are.

The second clue is the word order, or nesting, which means that pairs sit inside each other and never cross. As in the house, a closer may only close the opener opened most recently that is still open. In {[( the next closer has to be ). So of all the openers we remember, we only ever need the newest.

Those two clues point to the stacks and queues pattern, and to one structure in it, the stack. A stack is a pile, like a pile of plates in a kitchen. You may put a plate on top, which is called a push, and you may take the top plate off, which is called a pop. You never pull a plate out of the middle. So the last plate put on is the first one taken off, which people shorten to last in, first out. Our doors follow exactly this rule, since the last door opened is the first one closed.

The rule to carry to new problems is short. Whenever the most recent unfinished thing must be finished first, keep the unfinished things on a stack. The same rule checks HTML tags, tracks nested function calls and drives an editor's undo button.

Two neighbours look similar but do not fit. A queue is a line at a counter, where the first to arrive is served first, so it would check each closer against the oldest open door, the front door, which is the wrong one. And a counter cannot tell ([)] from ([]), although with only round brackets it would be the better answer, which is worth saying in an interview.

3The honest first attempt, a brute force that rubs out matched pairs

Before reaching for a stack, it is worth trying the brute force, the plain idea most people find on their own, because it is correct and it shows us what the stack will save. Every balanced string has an innermost pair, such as (), written side by side with nothing between. If we rub it out, what is left is still balanced. So we keep rubbing out side-by-side pairs, (), [] and {}, and see whether the string disappears. If we get stuck with characters left over, it was not balanced.

Let us do it by hand. Rubbing out both () pairs in {[()()]} leaves {[]}, rubbing out [] leaves {}, and rubbing out {} leaves nothing, so the answer is true. On ([)] there is no side-by-side pair at all, so we are stuck at once and the answer is false. Java's String.replace removes every copy of a short piece of text, so a loop of replace calls does the rubbing out for us.

Now let us count the cost, and here a different string tells the truth. Our example happens to vanish in a single pass of the loop, because its pairs are shallow. A deeply nested string such as (((()))) behaves very differently. Only its innermost pair is ever side by side, so each pass removes just one pair, as the picture shows.

Step throughDeleting pairs from (((()))) one pass at a time

Only the innermost pair is ever side by side, so each pass removes one pair and rereads everything else.

  1. (0(1(2(3)4)5)6)7
    pass
    0
    length
    8
    read so far
    0

    1Before the first pass the string has eight brackets. Only the middle two, at indexes 3 and 4, sit side by side as ().

  2. (0(1(2)3)4)5
    pass
    1
    length
    6
    read so far
    8

    2Pass 1 reads all eight characters and removes the one () it finds. The new innermost pair is now side by side.

  3. (0(1)2)3
    pass
    2
    length
    4
    read so far
    14

    3Pass 2 reads the six characters that are left, removes one more pair, and leaves four.

  4. (0)1
    pass
    3
    length
    2
    read so far
    18

    4Pass 3 reads four characters and leaves a single pair. The outer brackets have been read three times already.

  5. 0
    pass
    5
    length
    0
    read so far
    20

    5Pass 4 removes the last pair, and pass 5 finds nothing to change, so the loop stops with an empty string: balanced, after five passes.

Java
// Brute force: keep deleting side-by-side matching pairs until nothing changes.
static boolean isBalanced(String s) {
String previous;
do {
previous = s;
s = s.replace("()", "").replace("[]", "").replace("{}", "");
} while (!s.equals(previous));
return s.isEmpty();
}

Each pass of the loop remembers the string in previous, removes every (), then every [], then every {}, and goes round again until a pass changes nothing. The answer is whether the string became empty. This version only works for strings of pure brackets, because a letter between two brackets would stop them from ever becoming side by side.

Let us count the reading on (((()))). The five passes read 8, 6, 4, 2 and 0 characters, twenty in all, for a string of only eight, and each replace call rereads the string, so the true count is about three times that. For n brackets nested like this there are about n / 2 passes reading n, n - 2, n - 4 and so on, roughly n times n divided by four. We write that as O(n squared), read as order n squared: doubling the length makes the work about four times larger. Each pass also builds new strings, so the extra memory, called the space, is O(n).

So where is the waste? Look at the outer brackets in the picture. Each pass reads them again, although nothing about them has changed. All the news in a pass is at the innermost pair. So the question worth asking is this. As we read from left to right the first time, could we remember the openers still waiting, so that we never read them again?

4From rereading to remembering, one rule at a time

Let us return to the house. Each time we open a door, we write its kind on a card and put the card on top of a pile. Each time we close a door, the card on top tells us which closer is allowed. That pile of cards is our stack, and it holds exactly the openers that are still waiting, with the newest on top.

So the rule for an opener is simple. When we read (, [ or {, we push it, because it has just become the innermost open door. Why push it without checking anything? Because an opener can never be wrong at the moment it appears; whether it is fine depends only on what comes later.

The rule for a closer has two checks, in a fixed order. First we ask whether the stack is empty. If it is, this closer has no door to close, as in the last ) of ()), and we can answer false at once. Only when the stack is not empty do we pop the top opener and compare it with the closer. If it is the matching kind, this pair is finished and we read on. If it is not, as when ) pops [ in ([)], the pairs cross, and we answer false.

Why must the empty check come first? Let us skip it and see. On the string ) the first character is a closer, and the code would pop an empty ArrayDeque, which throws a NoSuchElementException, so the program would crash instead of answering false. This is the mistake beginners make most often here, and it is tempting because the examples we usually test start with an opener.

There is one more check, and it is the easiest one to forget. When the whole string has been read, every closer has been checked, but some openers may still be waiting on the pile, as in ((). Those are doors left open. So the final answer is not simply true; it is whether the stack is empty. Characters that are not brackets are skipped entirely, because they open and close nothing.

Why is this always right? The stack always holds the unmatched openers in the order they were opened, newest on top. A string is balanced exactly when each closer meets the newest unmatched opener of its own kind and nothing is left at the end, and those are precisely the checks we make.

The three ways a string can fail, and the check that catches each
StringWhat happensCheck that firesResult
([)]pop [ when ) arrivespopped opener does not matchfalse
())second ) finds the stack emptystack empty at a closerfalse
(()one ( is still waiting at the endfinal isEmpty is falsefalse
{[()()]}every closer pops its partnernonetrue

5Watching the stack grow and shrink on {[()()]}

The picture plays the stack method on {[()()]}. The string itself never changes. The pointer i marks the character we are reading, and the panel shows the character, what we did with it, and the stack, written from bottom to top so that the top is the bracket on the right.

Watch the stack grow and shrink like the pile of cards. Openers that are still waiting are marked as compared, because they are on the pile, and each finished pair turns to done the moment its closer pops its opener.

Step throughChecking {[()()]} with a stack, one character at a time

The panel shows the stack written from bottom to top, so the top is the rightmost bracket. Matched pairs are marked as done.

  1. {0[1(2)3(4)5]6}7
    char
    -
    action
    start
    stack
    empty
    result
    -

    1Before we read anything the stack is empty, because no door has been opened yet.

  2. {0[1(2)3(4)5]6}7i
    char
    {
    action
    push {
    stack
    {
    result
    -

    2The first character is {, an opener, so we push it. The stack holds one waiting opener.

  3. {0[1(2)3(4)5]6}7i
    char
    [
    action
    push [
    stack
    { [
    result
    -

    3[ is another opener, so it goes on top of the {. The newest open door is now the square one.

  4. {0[1(2)3(4)5]6}7i
    char
    (
    action
    push (
    stack
    { [ (
    result
    -

    4( is pushed as well. Three doors are open, and the round one, on top, must be closed first.

  5. {0[1(2)3(4)5]6}7i
    char
    )
    action
    pop (, match
    stack
    { [
    result
    -

    5The closer ) arrives. We pop the top, which is (, and it matches, so this pair is finished.

  6. {0[1(2)3(4)5]6}7i
    char
    (
    action
    push (
    stack
    { [ (
    result
    -

    6The next ( is pushed. The stack is back to three waiting openers, with the new round one on top.

  7. {0[1(2)3(4)5]6}7i
    char
    )
    action
    pop (, match
    stack
    { [
    result
    -

    7The closer ) pops the round opener we just pushed. It matches, so the second round pair is finished.

  8. {0[1(2)3(4)5]6}7i
    char
    ]
    action
    pop [, match
    stack
    {
    result
    -

    8The closer ] pops the top, which is now [. It matches, so the square pair around both round pairs is finished.

  9. {0[1(2)3(4)5]6}7i
    char
    }
    action
    pop {, match
    stack
    empty
    result
    -

    9The closer } pops the last opener, {. It matches, and the stack is empty again.

  10. {0[1(2)3(4)5]6}7
    char
    -
    action
    end
    stack
    empty
    result
    true

    10The scan is over and the stack is empty, so no door was left open. isBalanced returns true.

Let us read a few frames back. After the third character the stack holds { [ (, three open doors, with the round one on top. That is why the closer at index 3 is allowed. It pops (, the newest opener, and the pair at indexes 2 and 3 is done.

At index 4 the stack grows again, simply following the doors as they open. At index 6 the closer ] pops [, which has been waiting underneath both round pairs, and at index 7 the closer } pops {, the very first card on the pile.

In the last frame the stack is empty, so no door was left open, and the answer is true. Without the final }, the stack would still hold { at the end, and the answer would be false.

6The complete Java program

Here is the full program. We use ArrayDeque as the stack, the class the Java documentation recommends for this job. main checks our example, the crossed string, an opener left over, an extra closer, the empty string, and a string with letters in it.

Java
import java.util.*;
public class BalancedBrackets {
// True if every bracket is closed by the matching type in the right order.
static boolean isBalanced(String s) {
Deque<Character> stack = new ArrayDeque<>(); // open brackets still waiting
for (char c : s.toCharArray()) {
switch (c) {
case '(', '[', '{' -> stack.push(c);
case ')', ']', '}' -> {
if (stack.isEmpty()) return false; // a closer with nothing to close
char open = stack.pop(); // the most recent open bracket
if (open != matching(c)) return false; // wrong type, e.g. ( closed by ]
}
default -> { } // ignore any other character
}
}
return stack.isEmpty(); // leftovers were never closed
}
static char matching(char close) {
return switch (close) {
case ')' -> '(';
case ']' -> '[';
default -> '{';
};
}
public static void main(String[] args) {
System.out.println(isBalanced("{[()()]}")); // true
System.out.println(isBalanced("([)]")); // false
System.out.println(isBalanced("(()")); // false
System.out.println(isBalanced("())")); // false
System.out.println(isBalanced("")); // true
System.out.println(isBalanced("a(b[c]d)e")); // true
}
}

Let us read isBalanced in the order it runs. First we create an empty stack, our pile of cards, as a Deque<Character>. Then the for loop visits each character once, from left to right.

Inside the loop a switch looks at the character. The arrow form of switch lets us group the three openers on one line and the three closers on another. For an opener the only work is stack.push(c), putting the card on the pile.

For a closer we first test stack.isEmpty() and return false if nothing is waiting, which protects the pop on the next line. Then stack.pop() takes the newest opener off the pile, and we compare it with matching(c), the opener that this closer needs. If they differ, we return false straight away, without reading the rest of the string, because nothing later can repair a crossed pair.

Every other character falls into the default branch, which does nothing. After the loop, return stack.isEmpty() gives true only if every opener found its partner.

The helper matching turns a closer into its opener. We only call it with a closer, so its default branch can safely stand for }. Running main prints true, false, false, false, true and true.

7How much it costs, and the strings at the edges

Let us count on the example first. The string {[()()]} has eight characters, and the loop looked at each one once. Four of them were pushed and four were popped, so each character caused at most one push or one pop, and each of those is a single quick step. For n characters that is about n steps, so the time is O(n). We cannot do better, because a character we never read might be the one that breaks the balance.

For space, look at the tallest the stack became, three openers on our example. In the worst case, a string such as (((((( pushes every character, so the stack holds n openers and the extra space is O(n). The pile of cards is the price of never reading anything twice.

Comparing the ways to check brackets
ApproachTimeExtra spaceSeveral bracket types?
Single counterO(n)O(1)no, only one type
Delete side-by-side pairs until stableO(n^2)O(n)yes
Stack of open bracketsO(n)O(n)yes

The edge cases are handled by the checks we already have, with no extra code. The empty string never enters the loop body, the stack stays empty, and we return true. A closer at the very start finds the stack empty and returns false, instead of crashing. Openers left over at the end are caught by the final isEmpty. A crossed string stops at the first mismatch, and letters fall into the default branch.

8Follow-up questions

Why not use java.util.Stack instead of ArrayDeque?

Stack is an old class that extends Vector, so every method is synchronized, paying a small cost for thread safety even when only one thread uses it. It also offers list methods such as get, which let code reach into the middle of the pile and break the stack's rule. ArrayDeque has the same push, pop and peek methods, is faster, and is what the Java documentation recommends.

How would you find the length of the longest balanced run of round brackets in a string?

We keep a stack of indexes instead of characters, and we start it with -1, a marker that stands just before the first character. For each (, we push its index. For each ), we pop. If the stack is now empty, this ) had no partner, so we push its own index as the new marker. Otherwise the index on top is the last place where the balance broke, and the current index minus that top is the length of a balanced run ending here, which we compare with the best so far. On (()) the stack ends with -1 under nothing else, and the run at index 3 has length 3 - (-1) = 4. It is O(n) time and O(n) space.

9Conclusion

We checked whether a string of brackets is balanced by reading it once with a stack of the openers still waiting. Each opener is pushed, each closer must find a waiting opener of its own kind on top, and the stack must be empty at the end. That catches all three failures, crossed pairs, extra closers and openers left open, in O(n) time and O(n) space. The clue to remember is nesting: whenever the most recently opened thing must be closed first, reach for a stack.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the rules first. There are three bracket types, other characters are ignored, and the empty string counts as balanced. A single counter is not enough, because it forgets which kind of bracket is open.

Then, if they want more

A first attempt is to keep deleting side-by-side pairs until the string stops changing, but a deeply nested string loses only one pair per pass, so that is O(n squared).

The key observation is that a closer must always close the most recently opened bracket that is still open, which is last in, first out, so I will use a stack. I scan the string once with an ArrayDeque. For an opener I push it.

For a closer, if the stack is empty I return false, because there is nothing to close; otherwise I pop the top and return false if it is not the matching opener. At the end I return whether the stack is empty, because leftover openers were never closed.

Each character is pushed or popped at most once, so the time is O(n), and the stack can hold up to n openers, so the space is O(n). I would test the empty string, a closer at the start, a crossed string and an unclosed opener at the end.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 15 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Check whether a string of brackets is balanced.": https://scrivio-interview-library.netlify.app/data-structures/solutions/check-whether-a-string-of-brackets-is-balanced-3798ec/

More stacks and queues questions