Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Code Corner: Balancing Brackets

DZone's Guide to

Code Corner: Balancing Brackets

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

java interview balancing brackets


Given a sentence or formula containing square brackets, curly braces and brackets, write an algorithm to determine if it is balanced.

This question has been around for a long time but often candidates can struggle with it due to having limited data structures experience.  There’s a number of possible ways of coming up with a solution, but here’s the best I’m aware of.

At its purest form this is a matching exercise. We obviously need to loop through the characters in the sentence.  For efficiency we want to only iterate through it once, which rules out the option of taking each character and then trying to find it’s partner from the opposite end (which will result in multiple iterations).  But how do we keep track of what we have seen, and in what order?

In day to day work, people generally spend most of their time with Lists and Maps.  There’s a ton of other collections in the Java universe but people don’t get experience with them which is why this can be so tricky.   The data structure we’re looking for here is a Stack.  Stacks are LIFO, Last In First Out.  That means whichever element I most recently added will be removed first.  This is perfect for this exercise, as it means as I go through I can pop opening brackets onto the Stack, and if I find a closing brace I then can compare it to whatever is on top of the stack. If it matches then we’re happy, else we know we’re unbalanced.

//pseudocode
loop through characters of string 
   If(this character is an opening brace)
      push onto stack
   if(this character is a closing brace)
      pop from stack. If it isn't the matching brace, return false

If you had figured out this far then well done.  You know how to use Stacks and how to apply it to this problem which is the main test as part of this question.  There are a couple of hazards to avoid when implementing though.

Firstly, although Java does have a Stack collection you shouldn’t use it. Even Oracle’s own documentation says to avoid it in favour of Dequeue.  A Dequeue is a double ended queue and has functionality to support LIFO and FIFO (First in First Out) functionality.

Secondly, it’s really easy to write ugly code for this.  Most the implementations you’ll find on line have a ton of if statements; there’s a particularly horrible implantation from Princeton you can see the source for here.  Big if statements are a terrible practice; they’re very difficult to read and understand.  Your code combined with your tests should be your documentation; if you feel the need to write comments then 95% of the time you need to break your code down and make it simpler. Hopefully you can apply your knowledge to come up with something a bit more obvious!

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class StackFormulaBalanceTest {

    private StackFormulaBalance stackFormulaBalance;

    @Test
    public void emptyStringIsBalanced() throws Exception {
        stackFormulaBalance = new StackFormulaBalance();
        assertThat(stackFormulaBalance.balance(""), is(true));
    }

    @Test
    public void lotsOfNestedBracketsButBalancedReturnsTrue() throws Exception {
        stackFormulaBalance = new StackFormulaBalance();
        assertThat(stackFormulaBalance.balance("([Hell{} T(h(e[r]e))]boom)"), is(true));
    }
    @Test
    public void correctNumberOfClosingBracketsButInWrongOrderReturnsFalse() throws Exception {
        stackFormulaBalance = new StackFormulaBalance();
        assertThat(stackFormulaBalance.balance("(a[b{c)d]e}"), is(false));
    }
    @Test
    public void onlyHasClosedBracesReturnsFalse() throws Exception {
        stackFormulaBalance = new StackFormulaBalance();
        assertThat(stackFormulaBalance.balance("}])"), is(false));
    }
    @Test
    public void correctBalancingButWithMoreOpeningBracketsReturnsFalse() throws Exception {
    stackFormulaBalance = new StackFormulaBalance();
    assertThat(stackFormulaBalance.balance("({}"), is(false));
    }
}


import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

public class StackFormulaBalance {
    Map<Character, Character> brackets = new HashMap<Character, Character>() {{
        put('{', '}');
        put('(', ')');
        put('[', ']');
    }};

    public boolean balance(String toBalance) {
        Deque<Character> bracketsStack = new ArrayDeque<Character>();
        for (int i = 0; i < toBalance.length(); i++) {
            char currentChar = toBalance.charAt(i);
            if (characterIsOpenBracket(currentChar)) {
                bracketsStack.push(currentChar);
            } else if (characterIsAClosingBracket(currentChar) &&
                    closingBracketMatchesLastOpeningBracket(bracketsStack, currentChar)) {
                return false;
            }
        }
        return bracketsStack.isEmpty;
    }

    private boolean closingBracketMatchesLastOpeningBracket(Deque<Character> bracketsStack, char currentChar) {
        return bracketsStack.size() == 0 || !brackets.get(bracketsStack.pop()).equals(currentChar);
    }

    private boolean characterIsAClosingBracket(char currentChar) {
        return brackets.values().contains(currentChar);
    }

    private boolean characterIsOpenBracket(char currentChar) {
        return brackets.containsKey(currentChar);
    }
}

The private methods could be inlined if you’re that way inclined, but by pulling them out and naming them well we can make our algorithm clear. It reads very similarly to the pseudocode.

What do you think? Do you have a better implementation or other suggestions? Let me know!

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Published at DZone with permission of Sam Atkinson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}