Skip to content

Instantly share code, notes, and snippets.

@onedayitwillmake
Created July 22, 2016 01:37
Show Gist options
  • Save onedayitwillmake/7ea3f2cbf46cbffd8ae4c946072d6221 to your computer and use it in GitHub Desktop.
Save onedayitwillmake/7ea3f2cbf46cbffd8ae4c946072d6221 to your computer and use it in GitHub Desktop.
parenthesis

Question

Write a function to detect if correct order of parentheses in a string. Let's assume the string will only ever contain parentheses.

(()) = good
(())) = bad
(()(())) = good
)() = bad

Answer

The below is the most basic answer:

var isParensOrderValid = function(str) {
	return true/false
};

I often see a look of terror when a candidate is faced with this question as it seems pretty tough but really it's fairly easy. It's good to see them work through it and with a little nudging and help I often find candidates get the answer in the end (or at least get close).

This question is great because it can have many optimizations. If a candidate can solve it then great, but if they can solve it with a bunch of optimizations then we know they're more senior. 👍

A lot of the time candidates will not add the check inside the loop for when counter is negative - in fact they often start with two counters and just check they match at the end. Look out for that.

Some optimizations for more Senior candidates

We know that in order for the string to be good it must have an even number of chars. If the candidate doesn't get that on their own ask them this:

What if we had 1 million good chars with one rogue bad one at the end. E.g. '()'*1000000 then a random ')'

Another optimization would be to check that the last character is a closing parentheses.

Finally, you could make sure the number of opening and closing matches with something like this:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment