
Typical programming interview questions. - gaiusparx
http://maxnoy.com/interviews.html
======
paulitex
Github (and similar evidence of actual abilities) are already making questions
like these extinct, thank god. Reading through a single project an applicant
has written themselves is _immensely_ more informative than these silly CS
brain teasers: actual solutions to actual problems, style & documentation
habits, testing practices, evidence of being able to code & ship, being a self
starter, etc... Classic example of actions speak louder than words. Thankfully
the technology is now in place so that resumes can be replaced with coding
community profiles, and interviews can focus on filling in the blanks and
assessing the compatibility of the applicant as a person.

~~~
synnik
While I'd love to agree, reading someone's code does not tell you:

1) If they actually wrote all of it, or if it derivative of someone else's
work. 2) Whether any particular function took them 10 minutes or 10 hours. 3)
What options they considered when choosing how to architect a particular
solution. 4) Why they made any particular choice in their solutions. 5)
Whether or not they will fit on your team, take constructive criticism, etc.

The questions posed in the article don't give you those answers either, but
the applicant's speed at answering, their confidence, they demeanor as you ask
further questions and discuss answers... all that communication does answer
most of the above questions.

~~~
raganwald
<http://github.com/raganwald>

1\. Do you look at my github and wonder whether I wrote it or copied it from
elsewhere?

2\. What do you care if anything I wrote took me ten minutes or ten hours? And
with rewrite_rails, the answer is more like ten _months_. Is that a problem?
Are you looking for LOC/hour or for a certain approach to thinking about
programming?

3\. A trivial coding problem will not answer this question any more than
Github will, but you can always just ask: "Reg, I'm looking at Faux, and I
wonder, what other approaches did you consider before settling on pushing
application logic down into the browser?"

4\. See above.

5\. "Reg, #andand seriously sucks. This is pervasive nil checking dressed up
in metaprogramming clothing with opening core classes as a third deadly sin.
Before I consign your soul to the abyss, what do you have to say in your
defense?"

~~~
mgkimsal
I can say on #2 that clients I've worked with aren't specifically thinking of
LOC/hour, but they do want people who are able to be reasonably productive.
Everyone's definition of reasonable is different (obviously). Looking at, say,
a 50 line block of code, I'd certainly prefer to know if it took someone a
couple of days to arrive at that solution vs, oh, say, 18 months.

Not everyone works at the same speed, but for certain types of problems and
industries, knowing that you can put out reasonable quality work in a
reasonable amount of time helps people get an idea of how to plan out other
parts of the project.

I'd rather know someone can do fizzbuzz in a few minutes vs 8 hours.

~~~
raganwald
I find it very hard to look at anything non-trivial and figure out what is
slow, about right, and fast. For example, #andand (I keep using this example
because many people have heard of it, not because I'm foolish enough to think
this is good work on my part).

I guess that after Benjamin Stein and I discussed the problem and one of us (I
can't remember whom) said "I wish there was an and-and-dot operator in Ruby,"
there was a rough implementation written fairly soon after.

But the thing on my Github now probably has a hundred hours of work
refactoring, dealing with edge cases, adding new functionality like .andand {
|foo| ... } and so on. I wouldn't be surprised if the LOC/hr. has dropped
below one at this point. And that's without considering the rewrite_rails
version which uses AST rewriting.

So for that purpose, I agree that a fizzbuzz given on the spot is far superior
to looking at someone's Github projects. Thanks for the valuable comment.

~~~
mgkimsal
I guess we're thinking about somewhat different things. "I find it very hard
to look at anything non-trivial" and in most cases the interviews I've been
involved have tended to involved 'trivial' cases, where in some cases the
interviewer wasn't sure of the _right_ answer, they just knew some of the
common 'wrong' ones to weed people out.

------
panic
_You may be asked about using Unicode strings. What the interviewer is usually
looking for is:

    
    
        - each character will be two bytes (so, for example, char
          lookup table you may have allocated needs to be
          expanded from 256 to 256 x 256 = 65536 elements)
        - that you would need to use wide char types (wchar_t
          instead of char)
        - that you would need to use wide string functions (like
          wprintf instead of printf)

_

Unicode support involves more than just the minimum number of bits used per
character.

Say you're writing a method to truncate a string to a certain length. What if
your text contains a code point outside the basic multilingual plane, and each
character can't be represented in just 16 bits? If you truncate in the middle
of a character, the result will be an invalid string. What about combining
characters? If you truncate in the middle of a combining character sequence,
you'll end up with half-formed output (e.g., letters missing a diacritic). If
you work with text, you should know this stuff!

~~~
WildUtah
The OP is a page from 2002 (or possibly 1902; didn't people remember Y2K back
then?), so I expect the recent new code points beyond U+65535 were still
outside the imagination of potential interviewers.

~~~
panic
The higher planes were added in 2001 with Unicode 3.1:
<http://unicode.org/reports/tr27/tr27-4.html>

~~~
Stormbringer
These things normally take time to trickle down to us lesser mortals.

I suggest a high level circle of protection and an astral binding. :D

~~~
voidpointer
This little thread illustrates nicely that the smart thing to do is not to
implement list or string functions yourself but to use a library that has been
tried and tested. Spend your brain cycles on the important stuff.

I find it much more interesting to ask people when and why they would choose a
linked or an array/buffer based list...

------
djhworld
I think a lot of these questions don't really reflect what someone will be
doing in their real job. It's more of a "how much do you remember from your CS
degree" test that has little relevance to your job duties of maintaining some
monolithic Java based enterprise platform.

I mean come on, Binary Trees? I know what a Binary tree is but I'd have to
look up the definitions of all the traversal types because there's no way I'd
be able to remember what Post/Pre/In Order traversals actually entail.

And this question is an absolute abomination: -

 _What is the next line in the following sequence:_ _1_ _11_ _21_ _Answer:
it's 1211 and the next is 111221_

That's a joke right? I'd personally answer 31 to this question.

~~~
Stormbringer
It's to identify those that have 'architect potential'. If you pick the
simple, easy to implement and blindingly obvious answer you don't make the
cut, sorry. :D

~~~
Deestan
"I can complicate this. I _know_ I can!"

~~~
Stormbringer
Easy, just add a layer of indirection. Then carpet bomb it back into the dark
ages with patterns. :D

------
Stormbringer
_"You have 2 supposedly unbreakable light bulbs and a 100-floor building.
Using fewest possible drops, determine how much of an impact this type of
light bulb can withstand. (i.e. it can withstand a drop from 17th floor, but
breaks from the 18th). Note that the ever-popular binary search will give you
a worst case of 50 drops. You should be able to do it with under 20."_

Maybe there's something I don't understand, because my reaction to that
question was "lolwut?"

In that scenario, with a binary search you drop from the 50th, 25th, 13th,
19th, 16th, 17th and 18th floors.

By my back of the postage stamp calculations you need to do (log N) + 1
drops...

My question: how did they get a number of 50 for binary search??? Is it
because you're limited to 2 failures? And by 'binary search' they mean
something like start at floor 2 and drop, if it is still intact go to floor 4
and then drop it, if it breaks you don't know about floor 3, so you have to
use the remaining one to check that. That's not _binary_ search, that's
_linear_.

To do it in 20 or less drops you could drop it from the 20th floor, and if it
smashes, go to floor 1 and start going up in increments of 1. Otherwise go to
floor 39 and drop it (etc). But that makes me think it is not the best for
that starting number, we can do better. Just pull out the good old (n^2 + n)/2
formula again and the first one in that progression that ticks over the 100
threshold is 14. So we drop it at floor 14 first, if it breaks then start from
floor 1 and go up. Otherwise go up 13 floors and repeat...

Our major floor increments are 14, 27, 39, 50, 60, 69, 77, 84, 90, 95, 99.

I'm not sure if there is a better solution, if you have one, feel free to chip
in. :D

~~~
patio11
Suppose that bulbs have a tolerance of 8.5. Doing a naive binary search causes
you to drop at floor 50, breaking a bulb, and then at floor 25, breaking your
second bulb. You have no more bulbs, and cannot discriminate between 25
possible values for the tolerance, so your naive strategy was not a good idea.

The binary search strategy which works is to binary search with the first bulb
until you break it, then exhaustively search with the second bulb starting
from the lowest possible tolerance and increasing until it breaks, thus
identifying the precise breaking point with the minimum number of drops. This
has a worse case performance of 50 drops, for when the bulb had a tolerance of
49.5: one drop with the first bulb, bulb breaks, 49 drops with the second
bulb. (1 + 48 = 49 if we assume that it can't break on the first floor.)

Your solution is _very_ good, but I do not believe it to be optimal. I am
working on a better one.

~~~
Stormbringer
_"Your solution is very good, but I do not believe it to be optimal. I am
working on a better one."_

Very well sirrah, I shall consider myself slapped in the face with the object
with five extrusions that is topologically identical to a plane. Your
challenge is accepted. :D Duelling algorithms at dawn it is. I keenly await
your opening salvo.

~~~
patio11
Coded both our algorithms. I win by a nose (more visible at larger building
sizes -- 1k floors, etc.) Code quality is an abomination, please excuse
exploratory programming:

<http://dl.dropbox.com/u/751473/hn.rb>

Gist of my approach: dynamically recalculate number of steps to go with each
jump we take, using the same approach that you do (find smallest k such that
k(k + 1) / 2 > n), rather than assuming it decreases monotonically. This has
superior performance around some boundary conditions.

Instructions for running script:

ruby hn.rb patio11 debug 100

ruby hn.rb stormy debug 100

Debug on or off as desired, 100 is size of building.

Then, leave off debug flags, and diff the outputs.

~~~
lurker19
Do you mean "incrementally by 1 each iteration" where you wrote
"monotontically", in your reference to Stormbringer's algorithm?

Mathematically, I do not see how any solution could beat Stormbringer's, by
considering the cases where tolerance = k+0.5 and tolerance = ((kk +k)/2+0.5,
which shows that the set of tolerances for a building of height > (kk+k)/2
requires >= k+1 drops to validate. But I have not been quite formal in my
analysis.

(Argh, asterisks!)

------
dlevine
I HATE interview questions that ask the candidate to write some trivial piece
of code. Particularly the ones that need to be written in C to give an optimal
answer "if you just do pointer math, this would be trivial..."

Not to say that some good candidates won't be excellent at C coding, but these
problems often test for specific knowledge, when they should be screening for
critical thinking skills. I've seen candidates who were "good" at this sort of
problem (probably because it was on a CS homework in College), but didn't have
much in the way of critical reasoning skills.

I prefer asking questions that require them to devise some sort of algorithm
to solve a problem (typically by walking through the situation methodically),
and then implement that algorithm in the language of their choice. No real
ahas or tricks, and I don't care if you write it in Python or Assembler...

------
jasonjei
These questions remind me of the time when I took AP Computer Science AB, many
years ago (10 years ago to be exact Freshman year). To be honest, many of
these concepts are good to know, but I find a much more useful test is to test
them on something that they probably haven't used before, especially a
technology that you use in your project.

For instance, our project uses a good deal of Jabber, so we test our
applicants if they can write a program to act as a bot responding to the
Jabber message "ping" with "pong." It tests their ability to develop rapidly
and to justify their choice of a library and how fast they can pickup our
technology. It's been a great filter as well as a useful test to see if they
can assemble a solution on their own. Even non-working solutions work well for
us because we can examine their thought process.

Asking them to develop a sort solution isn't useful for us as much as seeing
if they can develop code relevant to the components we use--because, let's
face it; you aren't going to be writing your own string class from scratch,
but it is good to know how one works. And in our case, they'll learn about
XMPP/Jabber if successful--and it will test to see if they are willing to
learn. Seeing which library they use is also interesting, because it tests
their system design skills, and in some cases, will indicate if they can make
good design decisions. But if we do have doubts about them being able to
assemble a program, we will test them _computer science_ questions, but in the
meantime, we want to see if they can _engineer_ a solution.

But if you are looking for a low-level programmer to develop you a compiler
from scratch, maybe these are the right questions to ask. But we don't expect
our applicants to build a hammer; we want them to know how it works, but we
don't expect them to build us one. I guess if we need a hammer maker, we will
find one, but if we need an applications programmer, we will have them use the
hammer. Just like your engineer knows how a spectrum analyzer works, but won't
be expected to build one. Unless you are hiring them to do that.

~~~
daleharvey
that test is quite funny considering maintaining an irc connection needs you
to respond with a pong from pings, and xmpp doesnt

------
orijing
From the link:

What is the next line in the following sequence: 1 11 21 Answer: it's 1211 and
the next is 111221

Why would 31 and 41 be illogical answers? I understand where 1211 comes from,
but 31 and 41 are totally logical IMO. It's a linear function that goes up by
10.

~~~
patio11
All problems of the form "Provide the next number of this sequence" are
attempts to demonstrate that you think, or are capable of thinking, in a
fashion similar to the way the decisionmaker thinks. 31 is a totally
reasonable answer to that question, mathematically. So is pi. So is "zebra".
(The question was "Provide the traditional lexicographic sorting in English of
the elements zebra, one, twenty one, and eleven, except o comes before e.")

The reason that 31 is not a good answer in terms of securing a job is because
your decisionmaker prides himself on being intelligent and he does not see
arithmetic sequences as being sufficiently impressive. The reason pi is not a
good answer is, despite there being uncountably many mathematical phenomena
for which {1, 11, 21, pi} are correct answers, it is insufficiently
elegant/tricky for what he has in mind.

~~~
lkozma
I agree about 31 but not necessarily about zebra or pi. A reasonably
meaningful metric is compressibility of the sequence, or how short code could
produce it. Although that just opens a different can of worms, it could be
argued that 31,41 is better solution than the one given in answer in OP which
is better than pi or zebra.

~~~
patio11
That is begging the question -- it moves the "I am totally winging this
because it makes me feel superior" from the "prefer 'elegant' answers" to
"prefer 'elegant' languages for writing compressed descriptions of problems".

A rigorous program expressing the sequences to which "pi" and "zebra" are the
next answers takes only 0 bits and 1 bits respectively to compress in Patio11,
a pedantic language created purely for the purpose of this post. It is far
more rigorous than either English or C-style pseudocode, has a well-defined
grammar, and could have an interpreter written in any common programming
language that would fit on the side of a business card.

I stick with the original contention: any problem of this nature is about
either identifying birds of a feather or lording one's intellectual
superiority over the candidate.

~~~
lkozma
The problem arises when you are asked to provide further (possibly infinite
nr) elements of the sequence: the first would still compress nicely as

"a(i)=i*10+1."

yours would be "a(3)=pi, a(4)=zebra, a(5)=cheetah, a(6)=akrcqfztaf a(7)=666"
etc.

But I agree, if the question is just "what is the next element?" and so far
only 3 are given, your answer is as good as anything else.

------
barmstrong
I'm surprised that these are commonly asked and I'm guessing these aren't for
a position building web apps.

Most of these are distant memories from a CS degree and rarely used concepts
in the word of y-combinator startups where Ruby and Python are common.

I think people building web apps look more for developers who write
maintainable code, design good user interfaces, write good tests, make cross
browser solutions, etc.

These would be nice to have but too low level for everyday use at most
startups.

------
oniTony
At top-tier software companies, expect all of the (applicable) questions to be
accompanied by the "and what is the runtime complexity of your solution"
followup question. Depending on your abilities, the interviewer will try to
lead you towards an optimal solution.

------
akavlie
What sort of programming positions?

I've done a fair amount of web development in PHP & Python (as well as
introductory C++ & Java). I had to look up "linked list" on Google just to get
some understanding of what that is.

~~~
naner
A linked list is a pretty elementary data structure. That being said, these
questions seem like they're for a job writing client software on Windows some
time before .NET existed.

~~~
Stormbringer
No, even in VB you wouldn't do that.

Of course, way back in the dark ages when _I_ wrote VB for client Windows apps
I was all "lets keep this nice and simple, nice and simple.... arrrrrrghhh,
why doesn't this POS language do what I want?! _HULK SMASH_ ", and then I'd
break out the Win32 APIs and hit it with the big guns.

I feel a little sorry for the 'normal' VB programmers, because they'd be
following my code and then _BLAM_ it'd disappear into hyperspace, and re-
emerge and something magical† would have happened.

†Read as: a sufficiently advanced technology

~~~
Vivtek
Ha! Fond, fond memories of VB for Word 6.0.

------
darkxanthos
"You are given an array with integers between 1 and 1,000,000. One integer is
in the array twice. How can you determine which one?"

Sum(Array) - 1000000 _(1000000 + 1)/2 = X

For the other part it's just

1000000_(1000000 + 1)/2 - Sum(Array) = Y

EDIT: n*(n+1)/2 is the formula for the sum of the numbers from 1 to n

~~~
JeanPierre
This function would be good if you know that all other integers are in the
array _once_. However, this isn't elaborated within the question. A perfectly
legal array with the restrictions we've been given is this:

    
    
      [1, 3, 3, 9, 42]
    

All numbers in the array are integers between 1 and 1,000,000, and one integer
is in the array twice.

As for the solution, allocate 1,000,000 bits and do a "bucket sort". If the
next number in the array is _n_ , check if the _nth_ bit is 1. If it is,
you've found the integer appearing twice. If the nth bit is 0, change it to 1
and continue.

~~~
darkxanthos
Good point tyvm for correcting me. Using just a bit in a bucket sort is a
great approach.

------
raganwald
> The interviews were pretty evenly split between very large, large, and
> startup-sized tech companies.

Really? One person is looking for a job in a big company or a startup?? One of
the most common programmer interview questions is _What type of job are you
looking for?_ I suspect that "Oh, I don't know, maybe cubicle dweller in
BigCo, but then again a startup might be fun" is not the best answer, and
describing each company as being your ideal destination is dishonest.

Then again, another possibility is that he looked for a startup job, and when
he couldn't find the right spot he tried some medium sized companies, and so
on. That might make sense in an interview: "I was really interested in
exploring a startup, but when I actually looked into it I realized it was far
more romantic in theory than it was practical. I like the idea of writing
great software, but it turns out that the companies I met with aren't very
committed to some of the best practices that interest me."

So I won't jump to conclusions about the OP, but certainly I am interested in
hearing what chain of events led to what appears to be a wide spread of
environments.

~~~
fjh
I honestly don't think that everyone cares about the size of the company
they're working for. I'm currently applying for internships for this summer
and I am far more interested in what kind of work I could be doing than how
big the company is. I don't think that's uncommon.

~~~
raganwald
I know that many people don't care about the size of the company they're
working for, but turn it around: Do you think that employers care about
whether an applicant cares?

To make this perfectly clear, let me propose this interview question: _What is
more important to you: The company and culture or the work that you'll be
doing?_

I think that people being people, they will prefer applicants who honestly are
more interested in the company and culture than the work. This is absolutely
true of BigCo, and applies to startups as well. What if the company needs to
pivot and you are no longer working on whatever excited you about coming to
work on day zero? Will you start looking for somewhere else?

~~~
fjh
Well, I'm a student, so it is entirely possible that I underestimate the
importance of company and culture. That being said, I'm not sure why I should
care more about culture than my actual work. I obviously want a certain work
climate (no annoying micro-management, smart and friendly co-workers etc.),
but that should be possible in big companies in startups, no?

> What if the company needs to pivot and you are no longer working on whatever
> excited you about coming to work on day zero? Will you start looking for
> somewhere else?

Honestly: If it is a massive change for the worse, why wouldn't I? Example: I
am interested in algorithms and low-level bit-fiddly stuff. I don't
particularly care about HCI and web design. If I was to join a company that
works on, say, databases and file systems, I would probably do it with the
expectation to work on the kind of problems I find interesting. Would it
really be unreasonable to look for something new if it turned out I could no
longer do that?

~~~
raganwald
It isn't for me to say what you should look for. I can tell you my experience
of what employers want, but then again most employers probably want .NET
experience, so what most employers want isn't the most important thing. The
question is, how do you find the one employer that's right for you!

One way to find a middle ground between your interests and a company's
concerns is to restate your interest in terms of the company culture. For
example: _I'm looking for a team that owns its stack and uses that ownership
to do interesting and disruptive things with its product. For that reason, I'm
less interested in the size of the company than in the way it approaches
technology. If a team is working from algorithms and bit -twiddling on up, I'm
sure I'll be happy._

That answer might apply to any company from Apple on down to a YCombinator
startup.

------
wh-uws
This is a great resource but lists like these without the accompanying answers
are always frustrating to me.

I would like a way to be able to check that I am right.

~~~
Symbol
It bears repeating: good interview(er)s will try to determine how you think,
not your end result. I do a decent amount of interviews (maybe 2-3 a month),
and we by and large are looking for people who can think through a problem,
defend a solution, ask good questions, not give up, and appear to be cool to
work with. That's it. Some of these questions are great, fundamental CS stuff
that I would expect any engineer to have in their back pocket, but some are
trivia. Trivia is great, but if you dont't know it I wouldn't hold it against
you. I guess my point is to relax. If you thought about some of these things
and answered them, great. You're better prepared for next time. Memorizing
answer sheets doesn't help in the long run

~~~
rimantas
> good interview(er)s will try to determine how you think,

I can say up front: I don't usually do my thinking at the interviews.

~~~
sh4na
Oh, if only I could upvote a million times...

------
Vlasta
If I were given questions like these, I would politely refuse to answer them
explaining they have nothing to do with the important things a typical
software developer does.

Having a solid portfolio of past successful projects to demonstrate your
abilities (including participation in a open source development) is way safer
than being able to solve artificial problems.

~~~
synnik
And we would politely end the interview and not call you back. Questions like
these are not made to decide who to hire -- They are made to establish a base
level of competence.

The ability to answer these questions does not prove anything. However, the
INABILITY to answer these questions says quite a lot.

So you gotta ask.

------
huhtenberg
There is a lesser known variation of "find a cycle in a linked list". Given a
function

    
    
      int f(int arg);
    

that returns a value computed solely from _arg_ , find the length of the
repeating sequence in

    
    
      f(x), f(f(x)), f(f(f(x))), ...
    

The primary use is determining the period of a state-less PRNG such as a
linear congruential one.

~~~
psykotic
> There is a lesser known variation of "find a cycle in a linked list"

There's also a lesser known alternative to Floyd's tortoise-and-hare algorithm
called Brent's algorithm. It's a little faster in practice, but more
importantly it represents an algorithm design technique that everyone should
know.

~~~
RiderOfGiraffes
See <http://news.ycombinator.com/item?id=1068715> for a lot of discussion on
this.

------
smikhanov
The bottom line here is that though today's interviewers' repertoire is a
little bit different, it only takes a small practice to excel in the questions
they ask. Author seem to make the same point.

Usual comments from "ninjas" in this thread are very amusing though.

------
wulf
These sequence questions drive me up the wall. It's so unbelievably stupid
that out of the near infinite functions that can produce a given list you
should come up with the one the interviewer thought was the "obviously
correct" one. The sequence in the example: 1, 11, 21, x ... with the
information given then the X=31 is just as valid as anything that the
interviewer came up with.

~~~
obitoo
yes of course thats a valid reply; the next question they'll ask you is "Can
you think of another one?" and try to steer you towards it.

------
Hominem
All this is still useful. I have to fix code all the time where the original
developer paid no attention to complexity and a algorithm that was fast with
the 10 items they tested with is dog slow once it makes it to production and
there are 10,000 items.

------
tszming
I also recommend the book "Programming Interviews Exposed", it contains the
absolute minimum every software developer must know about...

------
AndrewMoffat
Well, I feel pretty stupid now.

~~~
Stormbringer
Problem is, when would you ever do any of that in the real world?

Has anybody ever needed to reverse a string in place since the 80s? (Demo
scene excluded of course, they swallowed a different colour pill from the rest
of us)

I'm aware for instance of the XOR trick to swap to variables in place. I think
I used it _once_ in the last ~20 years, and really only then because I was
being pleased with my excessive cleverness.

These days I wouldn't bother, because it would just make the code fractionally
harder to read, it makes for a speed-bump for the mind, whereas spelling it
out with a temporary variable lets your brain keep cruising at interstate
speeds.

