3 points · by anon987987987 · 13y ago · 4 comments
Given a permutation [1..n] inserted into a BST, write a function to calculate how many other permutations of the input produce the same BST.
I have been studying up for a few months: Cracking the Coding Interview, Elements of Programming Interviews... is it just me, or is this a very difficult "first phone screen" question? I feel like my shot at Google was just obliterated. After an additional 1 hr later after the ph screen I was able to come up with a solution...
It's an interesting question. And it's certainly much more difficult than any phone screen questions I've been asked by other companies, and also harder than my phone screen question at Google, but not as hard as some questions I had on-site there (I didn't get an offer).
Suggestions: eventually you'll want to get to some sort of recursive formula, but start with small, concrete examples and reach the answer simply by counting.
For instance, get the permutation [1, 2, 3] (or even just [1,2] then [2,1]), draw the tree and think about how many other permutations would generate that same tree. The point is to confirm with interviewer that you got the question right. Then you consider [2, 1, 3] and the other permutations. At this point you'll probably get a hint of one case when you can swap 2 numbers and one case when you cannot. Then you test it with some 4-node trees. Hopefully at some point you can come up with an informal, English-language formula on how to calculate the answer for a tree if you know the answer for the 2 subtrees. If necessary, refine it, but I don't think the interviewer would necessarily expect you to give a closed formula answer.
If it makes you feel better, I've recently had a phone interview with a certain large market data company and all they asked was HR bullshit like "what does make motivate /demotivate you?". Apparently I didn't give the expected answers, and I didn't pass.