Coding Question – Javascript Bracket Validator

Please follow & like us :)

three sum algorithm

Here is the Question: Check for Balanced Brackets in an expression.

Here are the clarifications:

  • ‘(‘, ‘{‘, ‘[‘ are called “openers.”
  • ‘)’, ‘}’, ‘]’ are called “closers.”

You have given string containing Brackets. Write a function that returns true if an input string’s openers and closers are properly nested. Return false otherwise.

Here are the sample Input Data:

Examples:

  1. “{ ( ) }” should return True
  2. “{ ( [ ] ) }” should return True
  3. “{ [ ( ] ) }” should return False

Now to solve this problem, we have to track the order of bracket opener and closer. At any point if we don’t have matching closer for bracket opener we should just return false.

The best way to implement that logic we can use stack. Stack data structure operates on LIFO concept. That means whatever we add last will out first.

So we have stack where we push bracket openers and when we have closer we will pop out last opener if it matches the current closer we keep continue on given string, otherwise we will return false.

Let’s add that logic into actual working code.

const bracketValidation = (input) => {
   const openers = ["{", "[", "("];
   const closers = ["}", "]", ")"];
   const match = {
     "}": "{",
     "]": "[",
     ")": "("
   };
   let lastOpener = [];
   for (let i = 0; i < input.length; i++) {
     if (openers.includes(input[i])) {
       lastOpener.push(input[i]);
     }
     if (closers.includes(input[i])) {
       const last = lastOpener.pop();
       if (last !== match[input[i]]) {
         return false;
       }
     }
   }
   return lastOpener.length == 0;
 }

   

Now we also need to provide test cases for the function we have written. With test cases we can verify all the edge cases.

Test Cases:

const testCode = (codeoutput, correctoutput) => {
  console.log("actual", codeoutput, "expected", correctoutput);
}

testCode(bracketValidation(""), true);
testCode(bracketValidation("{{{}}}"), true);
testCode(bracketValidation("{{{}}}]"), false);
testCode(bracketValidation("{"), false);
testCode(bracketValidation("}"), false);
testCode(bracketValidation("{ [ ] ( { [ ] } ) }"), true);
testCode(bracketValidation("{ [ ] ( { [ ] } ( ) ) }"), true);
testCode(bracketValidation("{ [ () ] ( ) }"), true);
testCode(bracketValidation("{ [ ( ] ) ( ) }"), false);
testCode(bracketValidation("{ [ ] ( ) }"), true);
testCode(bracketValidation("{ [ ( ] ) }"), false);
testCode(bracketValidation("{ [ }"), false);

Test it out here on Code Playground