3 years later…I figured out this problem

Balanced Parenthesis is a common engineering interview question.

Write a function that takes a string of text and returns true 
if the parentheses are balanced and false otherwise.

*

Example:

balancedParens('('); // false

balancedParens('()'); // true

balancedParens(')('); // false

balancedParens('(())'); // true

I first tried it (well, try is a stretch. More like look at it and gave up) back in 2015 when I started to seriously study Javascript. And today, August 13, 2018, I finally have a solution

*Disclaimer: this is a naive solution that does not consider Big-O notation.

var balancedParens = function(input){

  // input === string

  var arr=input.split('');

  var leftParen= [];

  var rightParen= [];

  for (vari=0; i<arr.length; i++) {

    // find all indexes of left paren

    if(arr[i] ==='('){

      // push to array

      leftParen.push(arr[i]);

    }

    // find all indices of right paren

    if(arr[i] ===')') {

      // push to array

      rightParen.push(arr[i]);

    }

  }

  // compare the length

  // if length matches

  if(leftParen.length===rightParen.length){
    // return true

    console.log('true');

  }

  else {

    // return false

    console.log('false');

  }

};

The logic behind this solution is to split the input and put that into an array we will traverse over. Next, find all the left parenthesis and push them to an array named leftParen and do the same with the right parenthesis and push them to an array named rightParen.

Next, compare the length of leftParen and rightParen. If the string is balanced, the length of the leftParen will be the same as the rightParen (because every left parenthesis should have a counterpart). If the lengths aren’t equal, then its not balanced.

If we wanted to have our solution balance ‘()’, ‘{}’, ‘[]’, we could add two more conditionals to search for the left and right of each bracket.

 

I’m just stoked that I finally got this solution three years later. Hey! No one said I was fast, but I am definitely determined.

2 thoughts on “3 years later…I figured out this problem

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s