The basic approach works by associating '(' with the number 1, ')' with the number -1, and replacing string concatenation with addition. The empty string is just 0. A balanced string of parenthesis is one where every prefix has a non-negative valuation and the whole string has a zero valuation.
This valuation function is a monoid homomorphism: the sum of the values of two strings is the same as the value of their concatenation. Membership in our language is a matter of checking the valuation of some set of related strings (here, all prefixes). Converting the problem into this valuation monoid ends up being super convenient.
This solution breaks down into three interwoven but logically separate pieces: identifying the related strings to check, computing their valuations, and validating the valuations. You can tweak any of these steps individually and get a different language.
import operator
def scan(f, initial, iterable):
accumulator = initial
for value in iterable:
accumulator = f(accumulator, value)
yield accumulator
def valuation(ch):
return {'(': 1, ')': -1}[ch]
def is_balanced_parentheses(s):
values = map(valuation, s)
for value in scan(operator.add, 0, values):
if value < 0:
return False
return (value == 0)Speaking of coming up with solutions from first principles, I had a candidate come up with the following:
Map the opening and closing parentheses to indices, in two arrays. Example: For the string `(())()`, the two arrays would be `[0, 1, 4]` for `(` and `[2, 3, 5]` for `)`.
If the arrays of indices are not the same length, it isn't balanced.
If they are the same length, go through the two arrays in pairs. The candidate didn't express it this way, but I thought "zip the arrays" in my mind, so I'll express it that way, we get `[[0, 2], [1, 3], [4, 5]]`.
The candidate then said, if in each of these pairs, the index for `)` is greater than the index for `(`, the parentheses are balanced. Which is mathematically equivalent to a stack or a counter (the optimized degenerate case) or the prefix valuation.
Of course it's not as efficient as other solutions, and I don't see it generalizing, but hey... It was inventive, in my mind.
Efficiency, on the other hand, is not the best.
What about the string `({)}`? That is not balanced, so how would any counting or pairwise comparison work?
I was looking at the basic approach as a walk in 1D. In the students representation, this means that each tuple is ordered, implying a move forward (you start with a "(" and eventually end at a ")". As a walk, this means that you return to the origin without ever becoming negative.
In my rush, I generalized too quickly for the case of the two brackets as just a similar random walk in 2D. This of course doesn't work in the example you mentioned. If () corresponds to the xx dimension and {} to the yy axis:
- With "({)}" you do return to the origin [[1, 0], [1,1], [0, 1], [0, 0]] but not in a valid path.
- You basically need one extra rule. At each step, you can move forward in any direction (open a new type of bracket), but you can only move back in the direction you just came from (close the previous one).
This of course is just a weird way of representing a stack, because you still need to keep track of the entire history anyway (which you could just store as the brackets themselves.
To paraphrase one of my idols, "More (dimensions) is different"...
The language 'Anon84 is thinking of is useful for thinking about concurrent systems, where each kind of bracket is associated with a particular agent. What's important is not that the brackets are mutually well-nested, but only that each kind of bracket is independently well-nested. This independence property means that "({)}" is a well-formed string, since ignoring everything but round parentheses gives "()", and ignoring everything but curly braces gives "{}".
The Dyck language family is different. The entanglement between types of brackets means that you can't do a simple tensor like we'd like to.
If we're allowed to use more memory than a simple stack, this is my favorite super-cheaty solution. It abuses ruby's builtin string manipulation to recursively delete inner matched pairs (all that is really needed is a "slide remaining string left 2 chars" function). Since this only needs to match two-char long inner pairs, it trivially extends to multiple matched bracket types.
BRACKET_RE = /\(\)/
#BRACKET_RE = /\(\)|\[\]|\{\}/
def balanced?(str)
case str
when '' then return true
when BRACKET_RE then balanced? str.split(BRACKET_RE).join('')
else return false
end
endBUT.
Most of the people in my "tribe" had some formal education in computer science.
Our experience when hiring people is that there are programmers with a lot of raw talent and potential who will need a full slot (about 45 minutes of actual problem-solving time) to come up with something like the the code you suggest.
There will be no time to discuss their solution, ask them how to handle multiple types of parentheses, &c.
What most of those "They seem really smart, but struggled to balance parentheses" candidates seem to have in common is coming to programming without the formal education, e.g. through a "hacker school."
Whereas, the folks coming to us directly out of a university with a traditional CS curriculum grasp the basic idea right away, and we usually get past the first question and on to a follow-up in the same 45 minutes.
We already know from their resumé that some of the folks are coming from Waterloo or wherever, so it adds no useful information to us for them to do a lot better than the people with less formal backgrounds. For this reason, we now only ask this question of people doing work terms from universities with a formal CS curriculum.
When people are coming to us via another path, we now give them another question entirely, and we will be retiring this one outright in the near future.
1. If you're willing to train programmers, then all you're really looking for is an IQ test to see if they're smart enough to learn how to program. So in that case, you don't really need to ask programming questions at all. But if you're not willing to train programmers, then it makes sense to filter out programmers who aren't familiar with basic problem solving techniques, regardless of background. If they don't know how to do the job, that problem doesn't simply go away because you identify the cause (that they don't have a formal CS background). If a candidate is coming out of a "hacker school", I'd be MORE likely to ask this sort of question because I want to figure out if their lack of formal education is going to be a problem.
2. Someone with a formal CS background obviously has an advantage with this sort of question because they've seen this problem before, or a problem like it. But there's a lot of value in seeing how a candidate approaches a problem they've never seen before.
3. I'll say again that the response I posted doesn't require any formal CS education, as proven by the fact that I came up with that algorithm in an interview for an internship, before I had any formal CS education beyond for loops and if statements.
How much of this is due to them starting coding before thinking about the problem?
I'd not be surprised at all if these people would, if given several strings of parenthesis on a whiteboard and simply asked if those specific strings were balanced, have no trouble answering. I'd also not be surprised if then asked to explain how they determined this, they could do so. Then, if asked to write a program to use the same method, they could probably readily do it.
A lot of problems that are not hard if you think about them and then start coding are a lot harder if you try to simultaneously work out how to solve it and code that.
A reasonable person could look at it, and go, okay, so a parenthesized string is made up of some sequence of
( <more balanced parens> )
possibly repeated, to get things like "()()()". i.e., do that check in a loop.That is, for whatever position you're at, check that the first character is "(". Check that at position+1 there is a balanced parentheses string. Check that at position+1+len(the balanced paren string) there is a ")".
Consume as many of those as you can in your loop; return the consumed data as the "balanced string". Now, this function has to return the string (since our use of it above needs the length to know where the inner string ends). It stops after it can't consume anything further. The whole string is balanced if we consumed everything. That's it.
The stack is implicit here. Yeah, you have to know recursion, but that's the thing about interview questions: at some point you have to know something.
I asked elsewhere, and it hasn't been answered in this thread: if this is a bad question, what would make it a good one? I would love to see what the author's idea of a good question is.
For the real-world applicability of this: I deal primarily w/ HTTP APIs. Sometimes, that requires me to make use of certain HTTP headers, and a great deal of web "frameworks" out there do not parse HTTP headers; they just give you back the raw key-value map as strings or somesuch. Several of HTTP's headers are context-free. (They require at least a stack to parse.)
As the interviewer, all you can do is watch the developer suffers for a while, without being able to give help or shift to a different problem. That doesn't give you any indication of the ability to code or solve problems.
You asserted this in your first message. The point of my reply is to show that it's not a "puzzle", and that a reasonable line of thinking and reasoning can guide you through the problem to an answer. The naïve answer one might get here is fairly "undisciplined", in that there's no rigor in language theory, no deep discussion, but the question is still answerable.
> the magic trick to use a stack
My suggested line of reasoning does not use a stack, beyond function calling. If using the actual stack is a "magic trick", again, I think we have removed so much material from consideration as to not be able to ask anything of use.
Again, if we simply dismiss any line of reasoning that a candidate might not see as a "puzzle", then every question is a puzzle, and nothing can be asked in an interview. Simply repeating your thesis that it's a puzzle does not advance this discussion: do you not think the line of reasoning I laid out is reasonably obtainable in an interview? And if not (since I think it's a fairly minimal one), then what types/sorts of questions should an interview ask, since it would seem like I'm left with only things that are dead obvious (b/c if it wasn't, it's now a magic trick puzzle), and that leaves me with nothing to screen candidates with.
As an interviewer, I want to see you struggle with something you might not fully understand, and I want to know your reasoning and thinking as you go along with it. The real job is not going to come with a manual, after all.
What do you do if the candidate cannot come up with the solution in 10 minutes? I've been there and find it embarrassing. It doesn't indicate aptitude or lack of aptitude.
I find that system design, performance optimization or sometimes code review have the great advantage of being progressive. The candidate can go in multiple directions. The interviewer has the opportunity to lead to find strengths and match with experiences on the resume, while it's also possible to assist or to pull away from any particular aspect.
For coding questions, either stay on simple problems with straightforward solutions, could be as stupid as printing numbers from one to ten, to test the ability to actually write code. Or a progressive exercise that must have both trivial solutions and optimized solutions and then can be integrated into a bigger function.
Push on opening parenthesis. Pop on closing parenthesis. Trivial.
nesting_depth is the stack. There is only one kind of symbol that can be pushed, so it's represented as a simple count of the number of symbols that are on the stack.
balanced1 input =
let partialsums = scanl (+) 0 $ map (\x -> if x == '(' then 1 else -1) input
in all (>= 0) partialsums && last partialsums == 0
balanced2 = balanced' 0 where
balanced' count [] = count == 0
balanced' count ('(':rest) = balanced' (count + 1) rest
balanced' count (')':rest) = balanced' (count - 1) rest && count > 0
A more general version with multiple types of brackets: balanced = balanced' [] where
balanced' stack [] = null stack
balanced' stack ('(':rest) = balanced' ('(':stack) rest
balanced' stack ('[':rest) = balanced' ('[':stack) rest
balanced' stack ('{':rest) = balanced' ('{':stack) rest
balanced' stack (')':rest) = head stack == '(' && balanced' (tail stack) rest
balanced' stack (']':rest) = head stack == '[' && balanced' (tail stack) rest
balanced' stack ('}':rest) = head stack == '{' && balanced' (tail stack) rest
balanced' stack (_:rest) = balanced' stack rest import Control.Monad (foldM)
checkBalanced :: [Char] -> Bool
checkBalanced = isStackEmpty . foldM step mempty
where
step (x:xs) c
| x == c = Just xs
step ls c
| Just r <- inverse c = Just (r : ls)
step _ _ = Nothing
inverse = flip lookup [( '(', ')' )]
isStackEmpty stack = stack == Just []What do you think of this implementation I just wrote? It is generalized to work with parentheses, brackets and braces, and to handle the different types of braces I just used different scores that offset each other depending on the direction of the symbol. Couldn't really think of a better way to handle this other than using numbers that don't add up to one another (in a momentary fugue state, I used 1,-1,2,-2,3,-3 as the score values but that obviously doesn't work as [}) would be false flagged as matched. Doesn't seem elegant to use random floats to accomplish this.
It's a pretty trivial problem, but I think coming up with a clever solution to the generalization is a little more interesting.
P.S. your site is down
> What do you think of this implementation I just wrote? It is generalized to work with parentheses, brackets and braces, and to handle the different types of braces I just used different scores that offset each other depending on the direction of the symbol. Couldn't really think of a better way to handle this other than using numbers that don't add up to one another (in a momentary fugue state, I used 1,-1,2,-2,3,-3 as the score values but that obviously doesn't work as [}) would be false flagged as matched. Doesn't seem elegant to use random floats to accomplish this.
Two critiques, one minor, and one major:
Minor critique: is_balanced is a pure function. It doesn't need to be wrapped in a class, and an object doesn't need to be instantiated to call it. This adds complexity and in general is a bad habit. Languages like Java require classes, but that's Java exposing details of its underlying implementation, not a pattern to be imitated.
Major critique: try your function with the string "((((((]]]]]". In general, your approach doesn't work, because for whatever numbers you use (such as x=1 and y=1.2) the scores will "collide" at when there are lcm(x,y) where lcm is the least common multiple function. There's an even subtler bug for the string "{)(}".
> It's a pretty trivial problem, but I think coming up with a clever solution to the generalization is a little more interesting.
Yes, once you're generalizing I think the PDA becomes basically the simplest solution.
> P.S. your site is down
Thanks! It actually wasn't down, my HN profile was just linking to an old URL. I fixed it. :)
The whole Solution().runFunc() thing I just kind of picked up from LeetCode-esque constructions, but I definitely see your point on it being a pure function.
The funny thing is balanced parens can be recognized with with a state machine it is just ugly.
state_data = {
'0p':{
'(':'1p',
')':'fail',
'END':'pass',
'OTHER':'0p',
},
'1p':{
'(':'2p',
')':'1p',
'END': 'fail',
'OTHER':'1p',
},
'2p':{
'(':'3p',
')':'2p',
'END': 'fail',
'OTHER':'2p',
}
...
}
Just make sure the state machine has as many states as you need paren levels.I admit the moment that the math vernacular appears my brain seems to shut down, however after reading the proof that balanced parens cannot be described several times. It seems to depend on a couple things.
1 The string is allowed to be infinite the state machine not.
2 "But state(B, start, p) is the same state as state(B, start, q)!" why? the strings are defined to be different I see no reason they would be in the same state.
EDIT added analysis of article proof.
e.g. (((((((((())))))))))
In that example, `p` is length ten. After reading `p`, the recognizer must be in one of its states. It can’t have halted, and it can’t have recognized.
Let’s say that the recognizer has `n` states. Consider the strings (), (()), ((())), ...
After (, the machine is in some state. Let’s give that a number, 0.
If we start all over and give it ((, it must be in another state, state 1, or we must accept that two different strings end up in the same state. Then we can start all over and give it (((, and we must end up in state 2. And so we can go, adding a parenthesis each time, and the machine must end up in a different state after reading a different number of opening parentheses.
Eventually we reach state n-1, after starting from scratch and giving it n opening parentheses. We must now know that all the strings from 0 to n-1 in length lead to n different states in an n-state DFA.
So what happens when we give it n+1 opening parentheses?
It must end in one of its states, but we already know that the strings with one through n opening parentheses have ended up in each of its n states. So the string with n+1 opening parentheses must end up in the same states as one of the shorter strings with opening parentheses, we just don’t know which.
Back to the proof. The shorter of the two strings is p from the proof. The longer is q.
def is_balanced_parens(s):
return s.count('(') == s.count(')')
Think I'd fail the interview test...Coding interviews serve to check _how_ a candidate goes about solving a problem - if they submit without checking the solution meets the spec, or choose to solve a different problem without mentioning it up front, then this tells me plenty about their working style.
However, the bit at the end with the balanced parentheses matchers being a bad interview question seems to be missing the forest for the trees. A simple solution to this problem which has nothing to do with any of the computational theory discussed:
This isn't that hard of a problem, and if an interview candidate couldn't come up with a basic solution like this, I'd very much like to know that.