by cletus · 14y ago · 0 comments
I personally detest abstract puzzles like "why are manhole covers round?" or (worse) "How do you move Mount Fuji?" AFAIK these types of questions are not and have never been used in engineering hiring at Google (sales, etc I know nothing about). WSJ and other sources have made this (AFAIK inaccurate) claim. It's possible individual interviewers do this.
My own philosophy is that a simple whiteboard coding problem is an incredibly useful litmus test. I don't mean anything incredibly complicated either. If you can't write a function that gives me a row of Pascall's triangle, that's a problem. Note: I don't expect you to know what Pascall's Triangle is, merely implement it when explained.
Some of you may think such a test is a waste of time but I assure you it is not. It's astonishing how many people can't do this (and even more astonishing how many that do make it through resume and even phone screens).
The key here is "simple". One problem is that interviewers fall into the trap of thinking these problems are too simple and make the problems increasingly harder. Worse, they may get in a situation of asking someone a problem that is either something they know (because they've covered it before) or they don't (where it's not something you can simply nut out). This is a useless indicator in my experience.
Just because you can create a function to return a row of Pascal's triangle doesn't mean you're a great programmer but if you can't, it almost certainly means you aren't. It's a negative signal filter, nothing more, but an incredibly quick and useful one.
API pop quizzes I'm not a big fan of either, generally speaking, but on the other hand if you've used a language sufficiently long, basic questions about commonly used libraries aren't unreasonable either.
Interviewing is a numbers game. Your goal is to come up with a process that balances time spent by the interviewer with finding a suitable candidate. Note that I didn't say accurately assessing each and every candidate. It's sufficient for the employer to simply find one qualified candidate even if you falsely determine someone who is qualified isn't.
A certain error rate is to be expected. It reaches a point where the time investment to reduce it outweighs the benefit of higher accuracy.
One final note: I detest (both as an interviewer and an interviewee) any kind of "take home" test (other comments have mentioned this).
As an interviewer, it's extra work to assess, people cheat, good candidates won't bother and so on.
As an interviewee, I'm not going to spend hours on you without speaking to someone first to find out how likely it is that you're a good match for me and the likelihood that you believe I'm a good match for you.
I would argue that a take home test is significantly more effort than a simple coding problem that doesn't have a significant increase in accuracy.
The one exception to this is automated testing where the problems themselves are relatively interesting. Some of the Facebook Puzzles fell into this category (and some don't). People may do those anyway for kicks. But again, there's nothing stopping someone going to Github and copying and pasting someone else's solution so what value is the filter, really?
EDIT: clarified my Pascall's Triangle comment. This isn't a trivia problem. I don't expect people to know what it is, merely implement it when explained.
I have over 10 years of programming experience and I probably would have miserably failed your "litmus test", especially if it were in an interview situation in front of a whiteboard. Maybe this just means I'm a bad programmer, but I tend to think that problems like "Pascal's Triangle" don't represent what we work on day-to-day.
I was astonished at the 25 minutes you claimed this took you, so I did it myself. It took me about two minutes to write this, which worked the first time I tried it:
#!/usr/bin/env python
def pascal(i):
if i == 0:
return [1]
else:
L = pascal(i-1)
ret = [1]
for i in xrange(len(L)-1):
ret.append(L[i] + L[i+1])
ret.append(1)
return ret
if __name__ == '__main__':
import sys
print pascal(int(sys.argv[1]))
What problems did you encounter that required you to use a debugger? I'm genuinely curious, because it seems like such a simple problem.If you program for a living, ask yourself in the last 5 years how many times did you have to write Pascal's triangle? How many times did you have to solve a brain teaser at work? I'll answer for me -- 0 times.
So I am advocate of posing a relevant problem and taking the candidate on the whiteboard through that problem. Not "let's imagine you have 100 horses, now one dies, blah blah..." but "Here is what we are working on. We have 1000 concurrent users, there is an open TCP connection to each, help us solve this particular latency problem". Yeah they might not know about Pascal's triangle but they if they can understand and show an ability to solve your particular problem then they are a candidate for you.
I honestly had forgotten the definition of it (the last time I saw it was in high school algebra), but I was able to get a working solution in about 10 minutes, including looking at the definition on Wikipedia. I'd say I'm a rather average coder (I'm certainly surrounded by people far better than I am, in any case).
If you had never seen or heard of Pascal's triangle before, I'd say maybe 20 minutes to code it would be reasonable.
No, it certainly doesn't. I've never had to write Pascal's triangle, for sure, and I doubt I ever will need to. But on a daily basis I'm solving myriad little problems just like Pascal's triangle. Complicated? Of course not, especially with the libraries my programming environment makes available. But it's the bread and butter of what a software engineer does a daily basis.
If your objection is to make any sense at all, you must be contending that there exist--in the real world--people who can effectively implement solutions for complex problems but who can't code up Pascal's triangle on a whiteboard in a few short minutes. Where are these people? Pascal's triangle isn't a positive filter. It's not like we're hiring anyone who can implement it. It's a negative filter: if you can't do it, why should I believe that you can solve the much more complex problems software engineers regularly face?
There is a fine line between brain teasers and the difficult problems that are our bread and butter. To answer your question: I would categorize many particularly subtle problems I've solved at work as brain teasers, so my number is high.
Relevant problems are a great way to judge someone's problem solving skills, but any problem that gives a glimpse into the way a person thinks is sufficient. I am probably not willing to give a candidate the amount of context to describe, let alone time to solve, the exact problem that I happen to be in the middle of on the day of an interview, but rather one we have already solved and determined to be interview-worthy. This means I certainly don't care about the solution, but rather the path to the solution. If you believe, as I do, that people tend to walk similar paths through every problem they solve, and that the path is important and the solution worthless, then the relevance of the problem is irrelevant.
That is definitely not what 99.999% of the programmers do every day. Professors in colleges, may be. But not programmers.
As for coding Pascal's triangle? It took me <30 seconds to Google it and find code I could copy/paste.
To be honest, seeing about 200 lines that looked like this:
typedef struct Abc {
Abc *n;
Abc *p;
void *d;
} Abc;
Abc *foo(Abc *p, void *x)
{
Abc *n;
n = malloc(sizeof(Abc*));
n->p = NULL;
n->n = p;
n->d = x;
p->p = n;
return p;
}
Note, there are at least 3 (edit: at least 4) bugs in the above code. None should be syntax errors.Sorting it out was a bit of a challenge. I think the specific question that I was looking at deobfuscated into reading words and definitions in from the command line and maintaining them in a sorted list, then looking up the words and printing their definitions.
And I agree, it was a great interview question. I even had the ability to sit in front of the computer and test my fixes to make sure it worked.
Realizing and taking advantage of this property of Pascal's Triangle significantly simplifies the problem. I guess it should be obvious, but I didn't consider using it. I don't think it's because I'm stupid (though I might be, I'm not sure) - I think it's because these kinds of problems are far removed from what I work on day-to-day.
Exactly! The OP says he "clarified" the problem, but I can clarify tons of math problems for you where the solution is staring you right in the face yet its impossible to solve if you haven't seen it previously.
example:
We all know 2,3,5,7,11,... are the primes
So the next guy is 13.
We all know 4,9,16,25,36 are the squares
So the next guy is 49
We all know 1,1,2,3,5 are the fibonacci numbers
So the next guy is 8
..
..
..
..
..
So, what's the next guy in 1,5,7, 15, 20 ?
( Remember the solution is right in front of you, but 90% of people on average won't figure it out. These are called convolution series. The solution is 28, if you haven't figured it out yet. )
(edit: provided solution and fixed a simple numerical error: dekz, thank you for spotting that )
def pascal(i):
o=[1]
for j in xrange(1,i):
o.append(o[-1] * (i - j) / j)
return o
Recursion's nice, but this isn't really the place for it. Especially since python has a maximum stack depth.(Were one to ever write such code in production, he should be escorted from the building immediately!)
from itertools import tee, izip, chain
pascal = lambda rows: reduce(lambda acc,n: acc+[(lambda it: [sum(x) for x in (lambda it,n=2: izip(*((lambda it,n: ([next(it) for _ in xrange(n)],it)[-1])(it,pos) for pos,it in enumerate(tee(it,n)))))(chain((0,),it,(0,)))])(acc[-1])], xrange(rows), [[1]])
num_rows = 10
print '\n'.join( ' '.join(map(str,row)) for row in pascal(num_rows) ) (define (pascal n)
(if (= n 0) (list 1)
(begin
(let ((L (pascal (- n 1)))
(ret (list 1)))
(do ((i 0 (+ i 1)))
((= i (- (length L) 1)))
(begin (set! ret (append ret (list (+ (list-ref L i) (list-ref L (+ i 1))))))))
(append ret (list 1))
))))This is better scheme:
(define (pascal n) (if (= n 0) (list 1) (let ((L (pascal (- n 1)))) (append (list 1) (map + (cdr L) L) (list 1)))))
int main(int argc, char ** argv)
{
long *n1,*n2;
int row,i;
row=0; N1[0]=1L; print_row(row,N1);
while(row++ < MAX_ROWS)
{
for(i=0, n1 = N1, n2=N2; i<MAX_BUF && *n1; i++)
{
if (i==0 ) n2[i] = 0 + n1[i];
else if(n1[i]==0) n2[i] = n1[i-1] + 0;
else n2[i] = n1[i-1] + n1[i];
}
print_row(row,N2);
for(n1=N1,n2=N2; *n2; ) *n1++ = *n2++;
}
}
void print_row(int row,long*n)
{
printf("row #%d",row);
while(*n) { printf(" %ld ", *n++);}
printf("\n");
}
This works through the size of long int (at least 50 rows).So far dspeyer, has one of the most efficient algorithms.
def pascal(i):
o=[1]
for j in xrange(1,i):
o.append(o[-1] * (i - j) / j)
return o
in ruby this could be def pascal2(i)
o=[1]
i += 1
for j in 1.upto(i - 1 )
o << o[-1] * (i - j)/j
end
o
end
we could make it even more efficient if we remember a there is symmetry in a pascal triangle. So that we don't have to calculate all the values in a row, maybe just half of the values. We have to calculate the row a little different if it is even or odd in number. def pascal(i)
o=[1]
i += 1
if i == 1 then
return o
end
i.even? ? d = i / 2 - 1 : d = i / 2
for j in 1.upto(d )
o << o[-1] * (i - j)/j
end
o[0..i/2] + o[0..i/2 - 1].reverse
end
So far it up to 2x as fast. I wrote this method in Ruby to time the different methods, pascal, pascal2. def timeA(m,n)
begin_time = Time.now
send(m,n)
end_time = Time.now
p "Time elapased #{(end_time - begin_time)*1000} milliseconds"
end
these are the times I get ruby-1.9.2-p290 :037 > timeA('pascal2',40000)
"Time elapased 949.9490000000001 milliseconds"
=> "Time elapased 949.9490000000001 milliseconds"
ruby-1.9.2-p290 :038 > timeA('pascal',40000)
"Time elapased 470.48699999999997 milliseconds"
=> "Time elapased 470.48699999999997 milliseconds"
ruby-1.9.2-p290 :039 > timeA('pascal',80000)
"Time elapased 1776.224 milliseconds"
=> "Time elapased 1776.224 milliseconds"
ruby-1.9.2-p290 :040 > timeA('pascal2',80000)
"Time elapased 5722.419000000001 milliseconds"
=> "Time elapased 5722.419000000001 milliseconds"
ruby-1.9.2-p290 :041 > timeA('pascal',200000)
"Time elapased 160416.34199999998 milliseconds"
=> "Time elapased 160416.34199999998 milliseconds"
ruby-1.9.2-p290 :042 > timeA('pascal2',200000)
"Time elapased 235113.38 milliseconds"
=> "Time elapased 235113.38 milliseconds"But that is under the (large) assumption that a suitable recursive algorithm has been found. The programming or coding is not the issue here. It's understanding the problem well enough and then identifying a recursive strategy.
getRow = (n) ->
rows = [[1]]
for i in [1...n]
prev = rows[i-1]
rows[i] = []
for j in [0..i]
rows[i][j] = (prev[j-1] or 0) + (prev[j] or 0)
rows[n-1]
and a one-liner for those who appreciate: (n) -> [[1]..n].reduce (p, c, i) -> ~~p[j-1] + ~~p[j] for j in [0..i]That's about 9 seconds per line.
Unless you are typing a program that you memorized - you cannot get such speed.
#include <iostream>
using namespace std;
int main()
{
int max;
cout << "How big do you like it?\n";
cin >> max;
if(max<0||max>30)
return 0;
for(int row=0; row<=max; row++)
{
cout << 1 << " ";
unsigned int out=1;
unsigned int last;
unsigned int next=row;
for(int i=1; i<=row; i++)
{
last=out;
out=last*next/i;
next--;
cout << out << " ";
}
cout << endl;
}
return 0;
}
EDIT: there we go :D small errors correctedFor those that are just brainfucked with wikipedia's explanation 1. Wikipedia sucks as explaining math. Never use it to look something up that deals with math. 2. The best explanation is like in the middle of the article, "Calculating an individual row or diagonal by itself"... "For example, to calculate row 5, r = 6. The first value is 1. The next value is 1 × 5/1 = 5. The numerator decreases by one, and the denominator increases by one with each step. So 5 × 4/2 = 10. Then 10 × 3/3 = 10. Then 10 × 2/4 = 5. Then 5 × 1/5 = 1."
u mad?
in ruby,
def fact(n)
n == 0 ? 1 : n.downto(1).inject(:*)
end
def pascal(n)
0.upto(n) {|r| print "#{fact(n)/(fact(r)*fact(n - r))} "}
endAm i a bad programmer now if i cant get a running program in less than 5 minutes ?
I would rather let people apply with code they are proud of like in every design job than solving litmus tests/puzzles
There are plenty of software jobs where that statement is absolutely true. I am not interviewing people for those jobs.
Taking a well-defined problem such as "write code to print the Nth row of pascal's triangle" is substantially easier than most of what we deal with on a day to day basis. The hard part is discovering and defining the problem well enough to get the point where it is as easy as "here is what we need to do, write some code to do it". Once you get there, whipping out the code needs to be second nature.
As cletus said in his post - a problem like this is a negative filter. If someone has a hard time whipping out the code for a well-defined problem like that, they will have a very hard time here.
If they can't, it doesn't mean they are a bad programmer. It doesn't mean they can't be successful in the industry.
It is simply a strong signal that they would not be successful at Google. And since I'm interviewing people for jobs at Google that's what I care about :-)
Would you rather be tested on your ability to comprehend a multi-kloc codebase and make correctness-preserving modifications to it?
That depends on how rigorous and well-maintained the existing test suite is, or even worse, that it is only half done. Which half? Guess, I think you'll be surprised.
Solving Pascal's Triangle is a straightforward yet not-completely-trivial logic exercise. It's the kind of algorithm design task that "serious programmers"[1] need to do, successfully, every day. Goofed logic bugs in algorithms are Very Expensive bugs. People who can avoid them are very desirable. This particular problem can be solved in just a few lines of code with no edge cases, which makes it a great candidate for a test to detect those developers.
[1] And yes, of course one can be a "successful software engineer" without being a "serious programmer". Writing CRUD logic and the like may be its own skill (and one not helped by algorithmic reasoning), but CRUD developers are cheap and plentiful. Tests like this give you a marker for the people who are hard to find.
By the same token, you appear to be assuming that successful candidates aren't. But I'm not trying to polarize.
Wouldn't it be better to invent a scenario for which a solution/algo must be constructed, during which the interviewer and interviewee can bounce their relative expertises? Is it too much to ask for the questions not to be rote(-ish) Pascal's Triangle stuff?
Not only did I find this very helpful in evaluating prospective employees, several people that we hired told me later that it was the most fun they'd ever had in an interview. That is, of course, a biased sample; some of the people that I interviewed obviously did not find my interview style entertaining.
The litmus test that I generally used was whether they were able to, given an erroneous output of their own creation, they could reason about why it happened and fix it before the hour-long interview slot was over. Also, if I (watching over their shoulder) couldn't spot the cause of the bug, I considered that it was probably unreasonable to expect them to be able to find and correct it during the interview.
While I encountered a lot of candidates that froze in the face of compiler errors or started making changes without stopping to think about what the cause of the error might be, I never once got the feeling that anyone was less familiar with the code that they submitted than someone who had written it themselves.
For 90% of engineering tasks, you're just plugging together different technologies other people put together. Oh hey yeah, Unix + HTTP + Rails + Javascript + Some Dude's API.
The amount of SHEER INTELLIGENCE necessary to untangle the above is, I think, not very high. It's a low threshold of competence. So, for that range of problems, fumbling around for fifteen minutes in front of a whiteboard will display the necessary grasp of logic.
The hard part in interviewing (and what people usually screw up), in my opinion, is almost entirely finding someone with a can do attitude who you can get along with for 40hrs every week.
Almost anyone can string stuff together; finding people that you can trust is way harder.
You do not have to create perfect code on the whiteboard. You just need to demonstrate that you can code. Sounds like you would have been fine.
You are right! In fact I seriously doubt any serious software project that is solving business problems ever works on these sort of problems.
These problems are basically more of testing mathematical knowledge through programming.
They may make a great interview to hire professors but not programmers.
https://gist.github.com/1567842
I tend to like to rough code out Lispishly, but if I'm actually running stuff I'll often do it in C.
I've developed high-performance medical imaging applications. I've build large distributed financial systems. I've built 2D/3D games. I've done a ton of stuff. Hell, I'm a software engineering hiring manager at my company. Yet I have no idea what a Pascall's triangle is, or how to give you a row of them.
I consider questions like that to be as useless as brainteasers in determining whether or not to hire someone. Sure, it can help give clues about a candidate, but if you're seriously considering rejecting a candidate on that point alone, I think you've got a problem in your hiring process.
Pascal's triangle is simple a triangle which starts at 1 and where each number in the next row is the sum of the two numbers above it, with 0 being assumed for numbers on the edge.
A program to produce one is nothing more than a couple for-loops, printf, and some basic logic.
I would ask you to explain, you would smirk inside, I will be rejected.
I am sure google should have enough data by now to see if there is correlation between knowing this problem and performance of hired programmer. I will be suprized if it has any relation.
I'm sure cletus or any other interviewer would explain what Pascal's Triangle is to you, and provide a couple rows of example output if you asked.
EDIT: Find/replace "Pascal's Triangle" with "FizzBuzz" and reread the comment. You'll get the same insight without getting hung up on seeing a term you didn't know.
"Candidates might get hung up on the gotcha part of it: the actual snip calculation. That's not something we care about, but that the candidates will likely think we care about. We should consider just giving them the formula (or letting them use a pre-defined "snip" method)."
It's useful as a very early screening because it eliminates a lot of people who are wasting your time and is so simple as to have almost to false negatives. It has no complexity, no algorithm or concepts you might be unfamiliar with- just the for loop, the conditional, and the modulo operator. No one who claims to be a professional developer should fail it.
For reference: http://www.codinghorror.com/blog/2007/02/why-cant-programmer...
Write a program that prints the numbers 1 to 100. However, for multiples of 3 print "Fizz" and for multiples of 5 print "Buzz". For multiples of both 3 and 5, print "FizzBuzz".
Write a program that prints the numbers from 1 to 100. But for multiples
of three print "Fizz" instead of the number and for the multiples of five
print "Buzz". For numbers which are multiples of both three and five print
"FizzBuzz".
[1] http://www.codinghorror.com/blog/2007/02/why-cant-programmer...I have to ask the parent poster if they truly feel that people need to know this http://en.wikipedia.org/wiki/Pascal%27s_triangle to deliver web or mobile solutions? You are highlighting the issue that the article is talking about.
Further, a whiteboard is like giving a mechanic a drawing of a car and a hammer and saying fix the head gasket. If creating a row from a Pascal Triangle was a real issue that crossed my desk the first thing I would do is hit Google to find the mathematical formula and explanation of what it does then I would see if there is a standard library and finally I would write it if one does not exist. Your whiteboard does not have search capabilities on it, so how are you expecting someone to show you how they work when you have provided them with any semblance of an environment that they would work in.
Pascal's Triangle is not some obscure and difficult mathematical formula you are expected to have memorized...This is not "construct Pascals Triangle and if you don't know what that is, too bad..."
It's a very simple concept and doesn't require the knowledge of anything other than simple arithmetic; any competent programmer should be able to write a program to construct one once the concept is explained to them...it's just a couple of for loops, some printfs, and straightforward logic.
That's the whole point the poster was making...really simple programming problems like fizzbuzz etc are useful at quickly weeding out people who lack very basic programming ability.
Constructing Pascals Triangle is obviously not a part of normal programming, but the ability to take an algorithm that has been described to you verbally and translate it into code is at the heart of all programming...that's what programming is basically.
If you can't do it, you are ipso facto not a real programmer.
I still contend that you are not gaining much insight and are producing an unnecessary filter that can do you more damage than good. I was on a project once that was cursed, we had a developer have a stroke, I had to have my heart restarted due to SVT from sleep deprivation etc. etc. We literally lost everyone that knew the technology except for me and I was not in good shape, and there was this one guy Tom Marra, he was an artist, but the kid had passion he had never coded in his life, but we where in a really bad situation, once he found out that with source control he could hack the crap out of the code and then just re-pull to fix his mistakes, he set out to teach himself JavaScript, on his own initiative. In less than a month he was contributing code to source control and in 2 months you could not tell his code from a seasoned pro's. The one quality this kid had was passion. You can't identify Tom Marra's by making them solve trivia on a whiteboard.
Besides will you hire a novelist on how well he can solve crosswords?
I don't think the point is that you would be expected to know every historical abstract concept, but rather that given the basics of one, you could write code to implement a data structure around it.
If someone genuinely has never seen a problem before, and then figures it out in 45 mins, this person may look worse than someone who memorized the answer, and solves it in 10 mins.
The best solution is to give a previously unknown question to both the interviewee and the interviewer, and have them work out the solution together. It doesn't have to be a coding question, but the interviewer should be good enough to assess whether or not the person they are interviewing is good, not from how quickly they spit out an answer, but through how they work to get the answer.
1) I don't program on a whiteboard. It's 2012, I have tools, and they beat the whiteboard setup every time.
2) I will never implement something that I have not implemented before without at least first consulting with a search engine. You see, I am not a genius that will come up with the best algorithm for a calculation every time I am put up to the challenge. My amateur attempts will be no where near as good as what others have collectively accomplished over the years that the problem existed.
For example, in this particular case (I have never had to implement a function that generates Pascal's triangle before), I can guarantee you that anything I came up with at a whiteboard right now would be completely inferior to what the result would be if I was allowed to do a search first. So unless you're trying to see if I am capable of writing any old crappy code so long as the result is correct, your test isn't adequate.
3) Interviews still make me nervous, doesn't matter how many times I have them, I never feel comfortable going through the process. This often leads me to simply draw blanks when given a whiteboard assignment of this nature. You may think this means I am just incapable of solving your problem, or that I perform poorly under pressure, but I can tell you that this type of "put you on the spot" pressure is much different from the type one generally feels in a work environment.
2) Nobody cares how good your solution is, they care about seeing your thought process while solving it. They are likely waiting breathlessly to ask you follow up questions about your poor implementation that will further enlighten them about the way you think. It would be a downright shame to disappoint them by writing a great solution right away.
3) This is a legitimately big problem. Everyone responds to the pressure of interviews differently and it is definitely not necessarily correlated to their response to the pressures of the workplace. Ideally you would notify the interviewer(s) of your anxiety beforehand and they would be willing to work with you on either a short take-home (which a lot of people also hate for other reasons), or some type of working interview (which is often infeasible).
The original article was about a specific-language whiteboard problem, which is open to arguments about tooling and internet access, but many people ask these sorts of questions in terms of pseudocode, structured written english, or even discourse out-loud, and the goal is not to determine programming language or algorithm knowledge, but problem solving skills.
edit: phrasing
I got an interview in 2006 for Microsoft. I typed my C solution with Notepad via share screen over DSL. The code is "to find out the depth of leaf nodes in a binary tree and find out which leaf node is the shallowest/deepest" or something like that. I did that in 20 minutes and return solution to find out depths for all leaf nodes and sorted them by depth. And the interviewer saw how I worked during the session and laughed I was the first one to solve the problem in that way and much better than what they expect.
At the other hand, I got interviewed in Amazon around the same time. I completely choked on whiteboard because I did not prepare for session before like that and I still had a jet lag due to lack of sleep during flight in previous night. Then I got another interview in Bloomberg and I complete couldn't write code with pencil and paper.
My mind flows when I typed but chokes when I worked on paper/whiteboard. I guess the fluidity of editor is the key.
Later when I interview software engineers. I tried to let them to have a computer so they can write code during the session. I feel much better grasp for their potential and habit during the session than whiteboard and pencil paper test.
It's almost like Google has some sort of informal process for throwing away old interview questions this way, just for laughs...
This also makes me think I may spend too much time lurking on HN.
Well, I can assure you that as a kernel programmer, I think it IS indeed a waste of time. It's also astonishing that the moment the interviewer asks me something like this, my enthusiasm and interest in the interview drops by more than 50%. When I apply for a kernel programming a job at Google, I am dying to talk about my system internals knowledge, device driver programming experience, subtle differences between the AMD/Intel arch and what not. Instead, what do I get ? The recruiter asks me to recite by heart problems from a popular algorithms book for the pre-screening. It's like the prospective employer is telling me : I don't care what you did in the last three years. Let's start from scratch!
What also bothers me is the the test for coding skills. When a company hires a Linux kernel developer, the best possible way to test for coding skills is to look at my contributions. Instead, I am asked to write code and implement malloc so that the interviewer gets a taste of my coding knowledge. I think this is a huge waste of time.
My point being that the job interview at Google is incredibly generic. I believe that just like you should have a different resume for each job you apply to, the same applies to the interview process too.
More Info: This is very specific to my interview experience at Google. The two times that I applied at Google for Linux kernel development positions, overall I had the same experience as described above.
Some more Info : I also don't understand the idea of the algorithms test during the prescreen. If you go through the algorithms book the recruiter suggests and look up on glassdoor for interview questions, there's a very fair chance that you already know the answer to the question that's being asked!
Most of the supposed brilliant Algorithm and Math brains are basically people who crawl internet forums for puzzle questions by spending around 30 minutes everyday.
They don't know a jack about algorithms or math. Its just they know enough to game the interview.
-module(pascal).
-export([tri/1]).
tri(Depth) ->
tri(Depth,[[1]]).
calc_row_rest([_]) ->
[1];
calc_row_rest([X,Y | Rest]) ->
[X + Y | calc_row_rest([Y | Rest])].
calc_row(Acc) ->
[1 | calc_row_rest(Acc)].
tri(X,_) when X =< 0 ->
[];
tri(1,Acc) ->
lists:reverse(Acc);
tri(Depth,Acc) ->
NewRow = calc_row(hd(Acc)),
tri(Depth-1,[NewRow | Acc]).
Returns a list of the pascal triangle rows: > pascal:tri(10).
[[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1],
[1,5,10,10,5,1],
[1,6,15,20,15,6,1],
[1,7,21,35,35,21,7,1],
[1,8,28,56,70,56,28,8,1],
[1,9,36,84,126,126,84,36,9,1]]1. It falls on the interviewer to be helpful and clear enough to help a candidate understand what is being asked. Often, a brainteaser of any sort explained poorly can be a death knell for anybody, no matter how smart they are. It's imperative that the interviewer is able to thoughtfully analyze a person's line of thinking moreso than whether or not they can get to a right answer.
2. Which brings me to the second point... The issue with a lot of brainteasers for poor interviewers is that it's a binary outcome. Either the candidate already knows the answer and comes off looking like a genius, or the candidate stumbles around in no man's land with no clue what you're talking about. Again, it's key here that the interviewer is able to guide a candidate through the thinking instead of sitting back and enjoying the show (which is admittedly sometimes fun).
I definitely think there is space for brainteasers, but it really requires an interviewer with the right training to get it right (which a company like Google does not have to worry about, but a start-up may). What I've actually heard is an interesting approach for start-ups recruiting is to just have the candidate sit and try to tackle a recent problem the company has faced with the interviewer.
We did not actually give people tests to take home. :)
Interviewing is a numbers game. Your goal is to come up with a process that balances time spent by the interviewer with finding a suitable candidate.
You have to admit that this is biased towards a company, like Google, that must hire many more people per unit time than most companies do. (And the Google process seems to work remarkably well for Google.)
A more useful example was when I asked my high school AP Computer Science class years ago to test if an array of integers contained a poker straight without using a parser, assuming ace=1, jack=11, queen=12, king=13. The key was to see if they knew how to think about algorithms. I wanted them to perform a sort and iterate across the array, but was interested in what they came up with. It tested a lot of important concepts in thinking about problems, which is more important to me than correct syntax on a whiteboard or implementing valid recursion on the fly.
I watch them work and help them out as they go; I'd get a ton less info if I just looked at the finished product.
We do also have a couple of "off line" coding tasks, which are even more informative (if I had to ditch one, I'd ditch the live one).
import scala.collection.mutable.HashMap
import scala.math.BigInt
val pascals = HashMap[Int,List[BigInt]]()
def pascal(row:Int):List[BigInt] = {
val result:List[BigInt] = row match {
case 1 =>List(1)
case 2 =>List(1,1)
case n =>List.tabulate[BigInt](n)(x=>{
if( x == 0 || x == n-1 ) 1
else pascals(n-1)(x-1)+pascals(n-1)(x)
})}
pascals+=(row->result)
result
}
(1 to 100).foreach(row=>println(pascal(row)))
------
Results: ---- List(1)
List(1, 1)
List(1, 2, 1)
List(1, 3, 3, 1)
List(1, 4, 6, 4, 1)
List(1, 5, 10, 10, 5, 1)
List(1, 6, 15, 20, 15, 6, 1)
List(1, 7, 21, 35, 35, 21, 7, 1)
List(1, 8, 28, 56, 70, 56, 28, 8, 1)
List(1, 9, 36, 84, 126, 126, 84, 36, 9, 1)
List(1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1)
...and 90 more rows -------
Prints Pascal triangles some 10,000 rows & beyond. So where's my Google job ?:)
Kidding aside, In 1999,I got hired at Sun Microsystems based on a 1-hour written exam. Chap gave me a pencil, paper & few programming problems & left me alone in a room. No laptop, no books, nothing. After 1 hour, he grabbed my paper, looked through the work & said "You are hired". Then we went for coffee.
otoh, I didn't get hired at 2 quant firms in 2011 based on this Whiteboard style interviewing. I got the first puzzle right & then halfway through the 2nd puzzle the chap said "There's an easier solution" & then they upped the ante ( Stirling numbers & then convolution integral & then I think they decided I wasn't a good fit because I couldn't work out every single theorem right there and then. I can do any number of problems, but if you could please write them down on a piece of paper & leave me alone for an hour...I can't quite think and write in front of you while you are passing snide comments on my thought process. Most of my professors when faced with a problem they haven't seen before typically say "I'll get back to you", and then in an hour or two, they call me to their office and show me their work. They don't try to work out a solution right in front of a classroom of 100 gawking students. They do so in the privacy of their office. No offence ( cause I still want that google job :-)
def print_pascal(rows)
row=[1, 0]
(1..rows).each do |r|
next_row = Array.new(r + 1)
next_row[0] = 1
(1..row.length-1).each do |i|
next_row[i] = row[i] + row[i-1]
end
print row[0..-2], "\n"
row = next_row << 0
end
end
print_pascal(100) def p(row)
[1,Range.new(0, row.length - 2).map {|l|
row[l] + row[l+1]
}, 1].flatten
end
a = [1]
while true
a = p(a)
puts a.inspect
end
edit: fixed formatting, sorry :( def pascal(num)
return [1] if num == 1
res = []
prev = [0] + pascal(num-1) + [0]
(1..num).to_a.each { |i| res << (prev[i-1] + prev[i]) }
return res
endO(n) is quite easy in this problem.
in ruby
def fact(n)
n == 0 ? 1 : n.downto(1).inject(:*)
end
def pascal(n)
0.upto(n) {|r| print "#{fact(n)/(fact(r)*fact(n - r))} "}
endlet step row = zipWith (+) (0:row) (row++[0])
let triangle = iterate step [1]
take 10 triangle
2. I think an iterative function for fact would be more efficient.
3. I notice you do not memoize the result of fact even though you are calculating it twice for each call.
I suspect that you are trying to show how compact a solution can be, but in an interview situation, I would probably be more impressed by someone who is aware of the issues above.
Not that anyone will ever read this... I thought I'd managed to escape this time, but then I thought it might be some good practice, so I timed myself...
nitrogen@n2:~ $ time bash
nitrogen@n2:~ $ vim /tmp/pascal.c
nitrogen@n2:~ $ cd /tmp
nitrogen@n2:/tmp $ gcc -std=c99 -Wall -Wextra pascal.c -o pascal
pascal.c: In function ‘main’:
pascal.c:15:21: error: expected ‘;’ before ‘)’ token
pascal.c:15:21: error: expected statement before ‘)’ token
pascal.c:16:2: error: too few arguments to function ‘calloc’
nitrogen@n2:/tmp $ vim pascal.c
nitrogen@n2:/tmp $ vim pascal.c
nitrogen@n2:/tmp $ ./pas^C
nitrogen@n2:/tmp $ gcc -std=c99 -Wall -Wextra pascal.c -o pascal
nitrogen@n2:/tmp $ ./pascal 1
1
nitrogen@n2:/tmp $ ./pascal 2
1 1
nitrogen@n2:/tmp $ ./pascal 3
1 2 1
nitrogen@n2:/tmp $ ./pascal 4
1 3 3 1
nitrogen@n2:/tmp $ ./pascal 5
1 4 6 4 1
nitrogen@n2:/tmp $ ./pascal 6
1 5 10 10 5 1
nitrogen@n2:/tmp $ ./pascal 7
1 6 15 20 15 6 1
nitrogen@n2:/tmp $ exit
exit
real 4m5.621s
user 0m0.928s
sys 0m0.136s
The initial syntax errors were including an extra parenthesis after atoi() and passing a total size to calloc() instead of an element count and element size. My solution is vulnerable to integer overflow and doesn't handle a negative row parameter. Simplifying assumptions: the first row and column will always be 1, so I don't recalculate it. Everything else just gets shifted in at the right. The code: #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int row;
int *data;
int i, j;
if(argc != 2) {
printf("Usage: %s <row>\n", argv[0]);
return -1;
}
row = atoi(argv[1]);
data = calloc(row, sizeof(int));
data[0] = 1;
for(i = 1; i < row; i++) {
for(j = i; j > 0; j--) {
data[j] = data[j] + data[j - 1];
}
}
for(i = 0; i < row; i++) {
printf("%d ", data[i]);
}
printf("\n");
return 0;
}public class Pascal
{
public static long[] getRow(int rowNum)
{
long[] thisRow = new long[rowNum];
if(rowNum == 1)
{
thisRow[0] = 1;
}
else
{
long[] lastRow = getRow(rowNum - 1);
thisRow[0] = 1;
thisRow[rowNum - 1] = 1;
for(int i = 1; i < rowNum - 1; i++)
{
thisRow[i] = lastRow[i - 1] + lastRow[i];
}
}
return thisRow;
}
public static void main(String args[])
{
int getRowNum = Integer.parseInt(args[0]);
long[] pasc = Pascal.getRow(getRowNum);
for(int i = 0; i < pasc.length; i++)
{
System.out.print(pasc[i] + " ");
}
System.out.print("\n");
}
}Edit, cleaned up code:
How do I paste into here whilst preserving line breaks?
function printPascal(x, triangle) {
var row = [];
while (x) {
var next = clone(row);
next.push(1);
for (var i = 0; i < row.length - 1; i++)
next[i + 1] = row[i] + row[i + 1];
row = next;
x--;
if (triangle)
print(whitespace(x) + row);
}
if (!triangle)
print(row);
}
function clone(list) {
var clone = [];
for (i in list)
clone.push(list[i]);
return clone;
}
function whitespace(x) {
var white = " ";
while (x) {
white += " ";
x--;
}
return white;
}
printPascal(10);
Ignoring the whitespace and clone functions, is there a much simpler way of doing this? pascal = iterate (\xs -> zipWith (+) ([0] ++ xs) (xs ++ [0])) [1]
Bread and butter: void pascal(int n, int *buf)
{
for (int row = 0; row < n; row++) {
for (int prev = 0, col = 0; col < row; col++) {
int curr = buf[col];
buf[col] += prev;
prev = curr;
}
buf[row] = 1;
}
}Looking at the C version, I wondered if it could be done without temporaries curr and prev. My no-temporaries version is not really any nicer, though it does shave off a few lines. :P
void pascal(int n, int *buf)
{
for (int i = 0; i < n; i++) {
buf[i] = 1;
for (int j = i - 1; j > 0; j--)
buf[j] += buf[j - 1];
}
} for i in range(n):
p = 0
for j in range(i):
buf[j], p = buf[j] + p, buf[j]
buf[i] = 1
Of course, you can also do this in C with a riff on the old in-place swap trick, e.g. buf[j] = buf[j] + p, p = buf[j] - p, but that's too clever by half, albeit kind of cool. let rec iterate f value = seq {
yield value
yield! iterate f (f value) }
Using the above we get ... let pascal = iterate (fun xs -> List.map2 (+) (0::xs) (xs @ [0])) [1] gimli> pascal <- local {
gimli+ loop <- function(n, xs) {
gimli+ if n > 0 then do
gimli+ print(xs);
gimli+ loop(n - 1, [0, xs] + [xs, 0]);
gimli+ end
gimli+ };
gimli+ function(n) loop(n, [1])
gimli+ }
func(n) loop(n,[1])
gimli> pascal(0)
F
gimli> pascal(1)
1
F
gimli> pascal(9)
1
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]
[1,5,10,10,5,1]
[1,6,15,20,15,6,1]
[1,7,21,35,35,21,7,1]
[1,8,28,56,70,56,28,8,1]
F
To clear up what's happening in the recursive call to loop, the (+) operator represents vector addition, not list concatenation: gimli> xs <- [1]
1
gimli> xs <- [0, xs] + [xs, 0]
[1,1]
gimli> xs <- [0, xs] + [xs, 0]
[1,2,1]I put something out in Java in about 20 minutes and 50 lines using a PT class, a newRow() method that swaps the current row with the previous row and sets up the new current off of the previous (prev[element] + prev[element -1]), and a printRow() method.
My solution works well, but I'm curious how you would assess this solution during an interview. Would my language choice be a pro/con? What is the avg time you see it take an interviewee to complete this problem and how many LOC is it usually accomplished in under the pressure of an interview?
pascal 1 = [1]
pascal i = zipWith (+) ([0] ++ pascal (i - 1)) (pascal (i - 1) ++ [0])
I'm not answering your question but just wanted to pique your interest in this because you were asking about language choice and had mentioned that your solution took 50 lines.The above solution expresses the recursive solution as the sum of two earlier rows after appending some zeros. There is very little room for errors to hide and it provides you with a kind of 'definitional' starting point to begin optimizing if you want.
pascal 1 = [1]
pascal 2 = [1,1]
pascal n = [1] ++ sum' (pascal (n - 1))
sum' [] = []
sum' [1] = [1]
sum' (x:xs) = [x + head' xs] ++ sum' xs
head' [] = 0
head' xs = head xs
2) Often it's better to use fold instead of explicit recursion. If you wonder whether you can rewrite your function in terms of fold...
"A tutorial on the universality and expressiveness of fold" http://www.cs.nott.ac.uk/~gmh/fold.pdf
My implementation in 15 min using javascript. BTW I'm a freshmen CS major.
function row(len){
if (len==1){
return [1]
}else{
var p = row(len-1),
arr = [];
for (var i=0; i<len; i++){
if (i==0){
arr.push(p[0]);
} else if (i == len-1){
arr.push(p[i-1]);
} else {
arr.push(p[i]+p[i-1]);
}
}
return arr;
}
}Or as we say in the medical field, this test has high "sensitivity" :)
http://en.wikipedia.org/wiki/Sensitivity_and_specificity#Sen...
Now I've seen them I'll keep them in mind if I ever have a need for them.
Although, in my research it was stated that these were extensions to the ECMA-262 standard and may not work everywhere. Therefore you would have to write up your own Array.prototype.map and Array.prototype.reduce to make them work. Is that true? If so, wouldn't seem simple to me unless you use them on a daily basis.
It's implicit in all of these that the concept is explained to you. Nobody would ask you to "implement a X" expecting you to know what X was (be it Pascals triangle, fizzbuzz, map, etc) unless X happened to be a fundamental concept in the field you are working in (not the case for any of the examples so far)
> Therefore you would have to write up your own Array.prototype.map and Array.prototype.reduce to make them work. Is that true?
Yes, that's sort of the point here. Javascript has these functions as methods of arrays (in some implementations), but the idea of the test is to write your own. They're both pretty simple, basically a for-loop and some logic.
On another note I have a hard time believing you work in JavaScript on a day to day basis and are not working with arrays. If you use jQuery or a similar library, you are working with arrays all the time and also using map-like functionality even if you don't know it by that name.
$(".foo").click(function(){})
Takes an array of elements and maps over them.
(fn [r]
(reduce #(cons
(* (first %1)
(/ (- r %2) %2))
%1) [1] (range 1 r)))# print a row of pascal's triangle
print "1\n";
:)