DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Kotlin Code Style: Best Practices for Former Java Developers
  • Is Codex the End of Boilerplate Code?
  • Design Guards: The Missing Layer in Your Code Quality Strategy
  • Open Source: A Pathway To Personal and Professional Growth

Trending

  • Why AI Agents Need a Shared Enterprise Ontology
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • The SDLC After AI
  • Adding Graph Retrieval to a RAG Pipeline With Python

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

Code Corner: Balancing Brackets

By 
Sam Atkinson
·
Dec. 04, 14 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
9.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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!

Bracket (tournament) code style

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

Opinions expressed by DZone contributors are their own.

Related

  • Kotlin Code Style: Best Practices for Former Java Developers
  • Is Codex the End of Boilerplate Code?
  • Design Guards: The Missing Layer in Your Code Quality Strategy
  • Open Source: A Pathway To Personal and Professional Growth

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook