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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • Open Source: A Pathway To Personal and Professional Growth
  • Enhancing Software Quality with Checkstyle and PMD: A Practical Guide
  • Linting Excellence: How Black, isort, and Ruff Elevate Python Code Quality
  • Mastering GitHub Copilot: Top 25 Metrics Redefining Developer Productivity

Trending

  • How to Install and Set Up Jenkins With Docker Compose
  • Memory Leak Due to Uncleared ThreadLocal Variables
  • Java Enterprise Matters: Why It All Comes Back to Jakarta EE
  • Cognitive Architecture: How LLMs Are Changing the Way We Build Software

Code Corner: Balancing Brackets

By 
Sam Atkinson user avatar
Sam Atkinson
·
Dec. 04, 14 · Interview
Likes (1)
Comment
Save
Tweet
Share
8.7K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Open Source: A Pathway To Personal and Professional Growth
  • Enhancing Software Quality with Checkstyle and PMD: A Practical Guide
  • Linting Excellence: How Black, isort, and Ruff Elevate Python Code Quality
  • Mastering GitHub Copilot: Top 25 Metrics Redefining Developer Productivity

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: