
The Worst Programming Interview Question - talhof8
http://www.nomachetejuggling.com/2014/06/24/the-worst-programming-interview-question/
======
JonnieCache
Hypothetically, if when asked this question in an interview I were to reply
"I'd look up the canonical solution on the internet and just implement that. I
have better things to keep in my brain than linked-list algorithms, and
there's no way I'm going to beat decades of phd work off the top of my head",
what would happen?

Obviously it depends on the job I was interviewing for. Let's assume I'm not
angling for a position as lead on a distributed load balancing layer or
something.

I suppose if they're looking to see my problem solving workflow then I'd look
like kindof a dick. But then, as the article points out, so would they.

~~~
vinkelhake
That's probably fine if you're going for a junior position where your job is
to bang out code for designs that others have come up with.

But if you go up a few steps then suddenly the problems might not be that
clearly defined and the set of possible solutions can be huge. A person who is
constantly relying on Google to come up with solutions is probably not going
to be that useful in design discussions.

I'm not defending the particular question, but on-your-feet problem solving is
a real and valuable skill.

~~~
JonnieCache
Oh I agree. That's exactly the stuff I keep in my brain instead of linked list
algorithms, which have a _mathematically proven optimal solution._ Remembering
them when I don't use them regularly would be a waste of brainpower which
could be better used for solutions to business/UX/architecture problems, which
one cannot solve with pure logic.

~~~
boomzilla
I am not so sure. It's not just about solving the problem, but sometimes it's
also the willingness and mentality to tackle something that's outside your
comfort zone, as well as the approaches.

For example, given the loop in linked lists question, even if a candidate is
not able to solve it completely, a reasonable approach would be to break the
general case to more specific, trivial cases, such as: what if the loop has
known length, what if the loop starts at a known location, etc. Interview
questions are not binary decisions, you can learn a lot from a candidate just
by seeing how they respond to a question.

~~~
JonnieCache
(Just to be clear, as this is a permanent and public record, I'm perfectly
capable of doing this kind of thing. It's not really an unreasonable question
to ask. I'm just being facetious because it's friday afternoon.)

------
mankyd
This question has an "a-ha" moment, but it is not required to solve the
problem adequately. I wholeheartedly disagree with this statement:

> People like to pose puzzlers to “see how people think” but that’s nonsense
> in the case of puzzler questions. You can’t reason your way through a
> puzzler, that’s why it’s a puzzler

There are plenty of ways to solve this problem. They're not all optimal, of
course, but you don't ask these questions to get the optimal solution, you ask
these questions to understand how the person reasons about them.

This more falls on the interviewer than the candidate. It's upon the
interviewer to encourage a dialogue about the problem and talk aloud through
it.

Yes, some qualified candidates are bad at this. I'm sorry to hear that, but it
can be practiced. Being good at interviewing can be learned. It's not terribly
difficult. My number one pro-tip? Never do this:

> If you don’t have the a-ha moment in the interview, you won’t get it, and a
> good chunk of your brain will be devoted to thinking “oh shit I’m blowing
> this interview” rather than focusing on the question at hand.

Never think that you're blowing the interview. I got a job at Google and I
know for a fact that I didn't get the optimal solution to some of my
questions. It's not about the solution, it's about the process.

~~~
joesmo
I've never been asked such a question, provided a sub-optimal answer, and been
allowed to continue. Every single time, the next question then is 'Can you
make it <faster|better|etc.>?' Maybe, but by this point, I already know this
is a terrible place to work.

~~~
mankyd
I've been in this exact same situation. And I was offered positions. I guess
that's my point - I didn't always find the perfect solution. I was pressed to
continue to think about the problem until whatever allotted time was up. I
wasn't [entirely] judged based on my final solution; I was judged on my
ability to reason about the problem and demonstrate competency in my coding
abilities.

------
patrickmay
It's a bad question if you expect a quick, explicit answer. It's somewhat less
bad if you're looking to have a conversation about how to solve problems the
candidate hasn't seen before.

I've used an arguably "puzzle" question that was presented to me in an
interview with some success -- the missionaries and cannibals problem. There
are three missionaries and three cannibals that you must get across a river.
The boat holds only you and one other person. The cannibals on either bank
must never outnumber the missionaries on that bank. It's a good question to
see if a candidate understands how to apply some basic computer science
concepts. It can easily lead to a 30 minute discussion at the white board,
with no need to get working code.

My favorite question is completely different. "What do you like best about
your favorite programming language and what would you change about it if you
could?" Anyone who doesn't see any flaws in their favorite language,
particularly if it's Java, gets politely shown the door.

~~~
lmm
> My favorite question is completely different. "What do you like best about
> your favorite programming language and what would you change about it if you
> could?" Anyone who doesn't see any flaws in their favorite language,
> particularly if it's Java, gets politely shown the door.

What about the poor people who've found a language that they actually like,
and understand the tradeoffs that were made? I suspect I recently failed an
interview for not having a good answer to that question, but really, what am I
supposed to say? If I thought there were significant problems with my
favourite language, I'd find a better one.

~~~
jsight
I once voted -1 on someone for not having a good answer to this one a language
that he had used for years. I regretted the vote later, as he turned out to be
excellent.

Having said that, it does surprise me that people have a hard time with this.
Certainly I hope that you like your chosen language and understand the
tradeoffs being made, but that is the point of the question really. Surely you
can reason about these tradeoffs and have a discussion in this area? If your
language is Java and you talk about how you are ok with their decision on
erasure because of the legacy concerns, that's a good answer. I may (or may
not) agree, but it's still a perfectly good answer. :)

OTOH, it is strange to me that someone would have worked in a language for 10+
years and literally can't come up with anything that they dislike (even
understanding the reasons for those limitations). No matter how good something
is, it is hard to imagine working with anything (or anyone) for ten years
without coming up with a few pain points.

~~~
lmm
> If your language is Java and you talk about how you are ok with their
> decision on erasure because of the legacy concerns, that's a good answer. I
> may (or may not) agree, but it's still a perfectly good answer.

I wouldn't feel comfortable answering "what would you change about X" with
something I actually wouldn't change about X (though maybe I should).

(FWIW my language was Scala, and while I've only been using it for ~5 years
there's very little I would change. The answer I gave was to use HLists rather
than Tuples in the standard library, but that feels like a nitpick more than
anything else)

------
incision
I appreciate all the technical discussion of this question in the article and
here in the comments, but I think the question is just a symptom.

The root issue here is the other interviewer and the apparent interview
process.

 _> 'In the post-interview pow-wow, all of the engineers who’d interviewed him
gave him the thumbs up, except my interview partner except my interview
partner, who refused to hire him...'_

Yes, yes, optimizing for false negatives over false positives is all the rage,
but this just sounds broken - wasting the efforts of a full panel only to
accept an arbitrary single-question veto.

 _> '..on the grounds that he completely flubbed this question, and "any
engineer worth his salt should be able to answer it."'_

Good engineers don't necessarily make good interviewers. Outright excluding
someone based on any single question is just horribly self-satisfied behavior.

~~~
pekk
If you look at the structure of their pow-wow rather than its labeled purpose,
you see that its real purpose is not to find a competent engineer but just to
build a consensus. E.g. so nobody complains they wouldn't have hired the
candidate.

It's the same principle which puts multiple men on a firing squad.

~~~
walshemj
Good way to hire a camel when you need a mustang - your optimising for
mediocrity.

Everyone does know the joke about a camel being a horse designed by a
committee?

And should not have the chair/leader of the committee over ruled the outlier
anyway.

~~~
qbrass
You should absolutely get a camel over a mustang.

Even though they look like they're designed by committee, camels are an
example of form following function. They're very well suited for their
environment, and although they're stubborn, make good work animals.

A mustang on the other hand, is a feral horse. They're harder to domesticate
because they've known freedom, and they've adapted to living in the wild by
being smaller and more timid than horses selectively bred for doing work. If
you really do need a horse, there are few cases where you need that horse to
be a mustang.

If someone is hiring you because they think you're a mustang, you better hope
they're caught up in the romanticism of cowboy stories instead of them being
desperate for cheap labor or meat.

~~~
walshemj
__WARNING __contains Sarcasam _WARNING_ *

Of course that why history is full literally full of elite heavy camel units
who turned the tide in so many battles and why Alexander's companions rode
camels and of course the charge of the heavy camel brigade in the Crimea.

------
shmerl
_> With all of those hundreds and hundreds of minds, this problem remained
open for 12 years._

A very good point. Some people just forget that while solution can look simple
when it's already known, actually finding it can be extremely hard and more
akin to invention breakthrough. So such question is more similar to asking to
prove some difficult theorem really, than to anything else.

------
blahedo
This article raises, sort of incidentally, one of the issues I've noticed
recently teaching intro CS. Every CS2 class teaches linked lists, right?
(Except for the ones that hit them in CS1, of course.) But: when was the last
time you had to roll your own linked list?

Once, not _that_ long ago, it was important to cover linked lists (and other
data structures) because you'd have to be writing them in order to implement a
program of any significant size. Now, though, all the common ones are already
implemented for you (and to be honest, we don't even use LinkedList all that
often---array-based lists are better in most real use cases).

So now their role in (my) CS2 is chiefly as setup. I still need to cover
linked lists because they establish concepts that will be important when we
get to trees (links) and to more general graphs (cycles and the lack thereof),
as well as in operating systems (continuation inodes, memory allocation) and
other areas.

But implementing an honest-to-god plain-old linked list holding ints or
strings or whatever? Who does that anymore?

~~~
belovedeagle
This is a question I see asked all the time and it's absolutely mind-boggling
to me that you could ask it. Who do you think writes the linked-list libraries
you use? Do you think the libraries just magically appear when someone wishes
them up? Do you think we should use the current set of libraries forever,
calling them "good enough", and limiting ourselves to current programming
languages for all of history? That's what will happen if we no longer teach
people to write these things; or else (more realistically) we leave it up to
them to make the same mistakes and waste time solving the same problems which
were solved decades ago, because no one ever bothered to teach them the
answers. Give it a few years and we'll have no one left who can program in
anything but javascript; no one left to write the browsers! --- or so I worry
when I read HN sometimes.

~~~
blahedo
You'll notice I'm not suggesting we stop teaching them. But what you describe
are specialised applications; my point is that where linked lists were once
something that every programmer, large and small, could reliably expect to
have to write repeatedly, they're now something that are only _directly_
relevant to, say, library maintainers.

------
skywhopper
I think an unreasonable question (ie, of a practical situation in which no one
will ever find themselves) deserves an equally unreasonable answer:

Write a program that starts at the head of the list and in a loop follows the
"next" pointer on the current list entry, halting when the pointer is null.
Run the program and wait. If the program never ends, there's a cycle in the
list.

~~~
gohrt
I have had this problem in real life. I had a graph database, and I needed to
find the end of a path in the graph. If the the path looped back on itself, my
program would not terminate.

~~~
hugofirth
This occurred to me as well: the graph data model is one of the few areas in
which you might practically need to address this problem. Again, however, a
lot of these issues specific to the graph data model are open research
questions and not really appropriate to an engineering interview.

------
raldi
What if you gave the answer immediately after asking the question and then
judged the candidate by how much their face lit up?

~~~
potatolicious
But why? One puzzling thing about our industry is our obsession with finding
suitable proxy indicators for programming ability.

But we can test for programming ability directly.

~~~
raldi
Oh, I agree. I just thought it was interesting to think that a bad question
might be improved by giving its answer away.

------
jameshart
Disagree that this problem never arises if you're not implementing a linked
list data structure.

Here's a file a customer sent you that describes their organizational
hierarchy:

    
    
      ID    Name            Manager
      1     Alice           4
      2     Bob             1
      3     Charlie         8
      4     Dave            -
      5     Elise           3
      6     Fred            2
      7     Gemma           1
      8     Henry           5
    

Is this a valid hierarchical tree? Okay, it's not exactly the same problem,
but it's certainly similar...

~~~
phaedrus
Technically in the context of an org hierarchy that would be detecting cycles
in a directed graph, not a linked list cycle. I don't think the algorithm to
detect cycles in a linked list applies to general graph problems, and the
problem is much harder for graph cycles.

~~~
jameshart
It's not a generic directed graph either, though - each node only has one
outbound link. The sequence of parents for any given node is a linked list,
and a cycle in that list is invalid. You certainly don't need to run tortoise
and hare for every node path looking for cycles. There are other approaches,
clearly - reachability analysis starting from each root node, for example.

But if I were to ask you to write a routine to find the root node for a given
node based on that data, then ask you to guard that routine against finding
yourself in an infinite loop or stack overflow, tortoise and hare would be a
legitimate answer.

Just trying to make it clear that just because the question asks about linked
lists, doesn't mean it's always about abstract data structures.

------
dfox
The article seems to imply that the turtle and hare algorithm is only valid
solution for this problem, which is certainly not the case.

This problem can be also solved by building big set of already seen list nodes
or adding bit to list nodes themselves. Whis is both something that everybody
should be able to come up with and implement.

I think that this is in fact quite good interview question because while there
is one non-obvious perfect answer, it also has some sub-optimal solutions that
are pretty obvious and simple to implement.

~~~
potatolicious
You're right, though I think he's talking about the weird type of interviewer
who expects candidates to know obscure, non-intuitive optimal solutions to
these problems.

I once met an interviewer who liked to use the "reverse a string" question,
except he was expecting candidates to know the XOR trick. Suffice to say few,
if anyone, ever got past his "filter".

Primadonna interviewers who use interviews as ego-strokes are a problem in our
industry. It's where the stupid "why are manhole covers round" questions came
from, and it's where these hyper-optimized algorithms questions come from.

------
dllthomas
_' Between 1955 and 1967, the problem of “how do we de­ter­mine if there is a
cycle in a linked list without mod­i­fy­ing the list” was an open problem.
Meaning, any number of PhD can­di­dates in Math­e­mat­ics or Com­puter Science
could have written about it as part of their dis­ser­ta­tion. With all of
those hun­dreds and hun­dreds of minds, this problem re­mained open for 12
years.'_

Were there any computer science graduate programs between 1955 and 1967?

You're not dealing with "hundreds and hundreds of minds", you're dealing with
those minds who 1) heard about linked lists, 2) heard about or realized there
was a cycle detection problem, and 3) devoted any energy to that problem as
opposed to the myriad other problems available to a mathematics or electrical
engineering graduate student. All of this has to have happened between 1955
and when the problem was solved _in advance of_ starting to write the paper on
it, _in advance of_ publication of the paper in 1967. The paper also
presumably included a proof of correctness that isn't being asked for in the
interview.

The interviewee has the further advantage that they know there _is_ an answer
in the space of the constraints the interviewer has drawn. As they suggest
less optimal solutions, those constraints get tighter, and the answer gets
easier to find. If they have been through an undergraduate computer science
course, they probably _also_ have more familiarity with linked lists than most
of the people attempting to solve the problem before 1967.

None of which is to say that failing to find the answer deserves
disqualification - that's probably still unreasonable - but the picture is
nowhere near as absurd as presented.

------
yodsanklai
I disagree with the author that this is a "puzzle question" that requires an
"a-ha" moment. Quite the opposite, it is an easily solvable algorithmic
question (maybe with a little guidance after the candidate suggest suboptimal
solution). Also, the good thing from the candidate point of view is that it is
the sort of questions you can prepare for.

~~~
sergiotapia
>sort of questions you can prepare for.

The point is why do you need to prepare for and regurgitate these silly
answers that you will almost assuredly never ever ever use in your day to day
job?

~~~
eweise
+1 to that. Most programming jobs are about integrating a bunch of different
technologies together to solve a business problem. In 20 years I've never
written a linked-list or sorting algorithm for work yet interviews are
increasingly narrowly scoped to algorithm questions. I've found that these
questions are usually asked by young people because they are fresh out of
school and have been led to believe that knowledge of algorithms is the most
important consideration. Give them a decade of creating products based on css,
html, node.js, nosql, yessql, etc and they will come to realize that
programming is more about understanding what a customer needs and finding the
most efficient way of delivering a solution. Ability to work with other, lead
a team, write clearly, explain to customers the tradeoffs and costs of
different solutions are actually way more important than knowing how to find a
cycle in a linked list.

~~~
twistedpair
But how do I test all of that in 30min or less? Do I have to actually get to
know the person, their work history and their strengths? Does that mean I have
to read the resume before I enter the room?

------
aleyan
Has anyone actually answered this question on the spot without help and
without knowing it? Probably not without help, but then how do we judge the
amount help given to an interviewer?

I have been going through my own crises of interview question. My go to
question for interviews which I have asked of about half a dozen candidates so
far, wasn't completely flubbed only once. The only people I know who gave the
good answers besides myself were my boss and our intern from MIT during mock
interviews. I have been grading the candidates not on being able to write the
solution in code like I intended, but on being able to come up independently
with bits needed for the solutions. This has been quite unsatisfactory. How do
I know if my question is too hard, or if something else is wrong, like
prescreening of candidates?

~~~
alain94040
Yes, I did figure it out. Actually, the answer I came up with was slightly
different: it was pretty clear that I had to move the first pointer to get
inside the cycle. Once I was inside, I thought the second pointer would need
to move a lot to find the cycle, rather than just going two hops. So I
proposed to advance the first pointer by n, and the second one by exp(n).
Maybe it would go faster, who knows.

By the way, this was the question at my first interview ever, so I do remember
it quite well.

PS: I interviewed many candidates since, and I would never ask such a
question.

------
gabemart
> In this case, the generally “correct” answer is a tortoise-and-hare
> algorithm, where you have two pointers at the head of your linked list, one
> traverses the list two nodes at a time, and one traverses the list one node
> at a time; if ever the pointers point to the same node, you have a cycle
> somewhere.

I'm an extreme novice to programming. I don't fully understand this.

1) How can you traverse a linked list two nodes at a time? Is this just short-
hand for "go to the next node, then go to the node after that, and call that
one operation"?

2) If you can detect when two pointers are pointing to the same address,
couldn't you solve the problem by traversing the list one node at a time,
storing the addresses of each node in an array, and checking to see if the
array contains any duplicate values at intervals?

~~~
aquamongoose
With regards to (2), this is one way of solving the problem. However, your
solution uses O(n) memory (where n is the size of the linked list), and the
tortoise-and-hare algorithm uses only O(1) memory. Here's how it works:
[http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_ha...](http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare)

~~~
thisone
unless the interviewer plans to move the goal posts, there was no specified
memory restriction in the original question.

~~~
gohrt
Complexity optimization is a generally useful skill.

"moving the goal posts" is called "every month at work, when you finish 1 task
and then move on to another task, instead of going home and getting paid to
rest on your laurels"

~~~
thisone
moving goal posts, is "I asked you for x, you provided me with x, but I really
wanted y, so now I'm going to tell you you're wrong"

You want someone to answer a programming question within a particular set of
boundaries, you set those boundaries.

~~~
dllthomas
I don't think it has to be "wrong". If I were asking this question, and I was
provided with "store them in a hash", I would say something along the lines of
"that's a correct solution" and _then_ add additional constraints.

"How you adapt in the face of additional constraints" is very much relevant to
programming.

------
davidjeet
Had that exact question given to me before, but it was in the form of a closed
book "pre-screening" written test.

I simply put down my pen, walked out of the room and told the recruiter if
this company was hiring based on these type of questions I would be a terrible
fit :)

~~~
twistedpair
They were likely hiring to fill a PHP dev roll writing CRUD web forms too,
right?

I've been places with tough interviews and incompetent developers and the
opposite as well. One does not necessarily correlate with the other.

------
nsxwolf
I would love to find the definitive resource for preparing for interviews like
this. Besides answers like "just be awesome", is there such a book or page?

In the past I've searched for various compendiums of algorithm interview
questions and saw the cycle detection one come up. I knew I would never be
able to solve such a problem on the spot. This blog post initially put it in
perspective for me, that its pretty much a BS academic question that you have
to already know the answer to - until I read the comments here, full of
totally awesome alpha SV nerds who are saying "I instantly got the optimal
answer without any foreknowledge". Now I don't know what to think.

------
ollysb
After a 10 minute phone screener I now rely on a paid pair-programming session
to identify good candidates. This is what you're going to hire them to do so
why waste your time asking questions that at best form a poor approximation of
their skills?

------
ssw1n
If I do not know any better, the first thought that would come to my mind
would be: "Wow, this company has really messed-up code base, and people here
cannot even get linked-list done right. Do I really want to work here?"

------
sjs1234
I had this in an interview (back '96). Came up with a linear time constant
space solution: create a new node, push it on the front, reverse the list,
check if the 1st node is the same one you pushed, if so it has a loop,
otherwise it doesn't. The downside is you need to reverse again to get the
original list.

Another answer is to mark nodes using the low bits of the next pointer. Also
linear time, but also requiring clean up. I can see how not knowing c would
cause people to think this question was somewhat unfair, but I didn't see it
that way.

~~~
herge
How would you reverse a linked list with a loop?

~~~
nmrm
If your list is laid-out a contiguously in memory as structs with both next
and prev ptrs, you can visit each member using ptr arith and switch the values
without actually walking the list using next and prev. Ditto if there's an
underlying data-structure involved such as an array.

~~~
herge
How could you have a linked list with a loop in contiguous memory? Or in an
array?

~~~
dllthomas
You allocate an array of objects that contain pointers, then link them
together. It does not have _all_ of the typical benefits of a linked list (in
particular, there's a hard max size and may require a _fixed_ size, depending
on just what you're doing to it here) but it does allow O(1) reordering
elements for a list-order traversal, while also allowing a linear traversal
through memory.

~~~
herge
If the linked list has a loop, but you don't know it, how do you figure out
the length of the list to allocate enough space for your array? How do you
copy the list into the array without traversing the list? How do you traverse
the list without hitting the loop and looping infinitely?

~~~
dllthomas
If you know that all the elements in the loop are _already in the array_ then
traversing it is easy. Of course, if you have an upper bound for the length of
the list, there's an easier check...

------
jerrickhoang
I don't think interview must entirely be related to the practical world. I
mean having a very hard and interesting practical problem is the best of both
world but not necessarily the only way to go. If you want to know if the
candidate can really build things you can check out his github/resume. I think
the 45-min interview is just to determine how smart the candidate is. If you
want to determine if someone is smart you put them in a very hard situation
(not necessarily a practical one) and see how they reason about it.

------
dualogy
Timely yet on-topic ;)
[https://twitter.com/tom_forsyth/status/482337551718440962](https://twitter.com/tom_forsyth/status/482337551718440962)

~~~
justinvh
Tom Forsyth listed one of the reasons--when a storage is explicitly expressed.
The other two that I can think of are for external linkage and non-constant
expressions on the rhs. In the end, you really don't know without some
introspection. It's up to the compiler. External linkage is one that will
force storage, but in general const will require internal linkage and fold
expressions accordingly (at least for primitives).

Edit: I would never expect anyone to actually remember or need to know that
for an interview. It would be definitely something you would re-
discover/discover because you _had_ to run into it.

------
peaton
I completely disagree that this question is irrelevant. I can imagine this
exact situation in compiler design where you have dependent types that can't
have infinite loops (in pseudo-code where forward declarations are not needed
or implied):

type a = b

type b = a

If a program has a structure like this with cyclic dependencies, then the
compiler must be aware of this and break. (At least, I can imagine a situation
where this could be a desired attribute.)

~~~
sz4kerto
You are mixing up cyclical linked lists with loops in a graph. The reason why
the question is bad stems from the fact that it's specifically about linked
lists.

~~~
peaton
I could definitely be mistaken, but I don't see a difference between a linked
list and a graph. They are two ways to represent the same thing. That being
said, if he asked me to find cycles in a linked list, I might determine the
adjacency matrix and check for loops:

[http://stackoverflow.com/questions/16436165/detecting-
cycles...](http://stackoverflow.com/questions/16436165/detecting-cycles-in-an-
adjacency-matrix)

This is at least very easy to reason about. However, if you are still right my
thought process is just very wrong.

~~~
dllthomas
_" I could definitely be mistaken, but I don't see a difference between a
linked list and a graph."_

A linked list is a particular type of DAG (or at least DG). The relevant
distinction between linked list and the general case is that a linked list
restricts nodes to (zero or) one outbound edge. This is relevant to the
problem at hand, because you only have one tortoise and one hare and so they
can only follow one path.

~~~
groovy2shoes
Right. As a graph theorist might put it, a linked list is a directed graph
with a vertex-disjoint path cover consisting of exactly one path. I.e., linked
lists are specialized graphs. The tortoise-and-hare algorithm can be
generalized to detect cycles in any connected graph, as long as a consistent
traversal order is used.

~~~
dllthomas
_" The tortoise-and-hare algorithm can be generalized to detect cycles in any
connected graph, as long as a consistent traversal order is used."_

But not in O(1) space, right?

~~~
groovy2shoes
I think it depends on how the graph is represented. With the "standard"
representations, it would be O(n) space in the worst case, where n is the
number of nodes in the graph. You'd still only need the 2 pointers, but the
traversal itself would need to also remember which paths it has not yet
visited. The worst case is when the number of paths is much larger than the
length of any particular path. The best case (apart from the null graph) is
equivalent to the linked list, where there is only one path in the cover.

I can imagine representing the graph as a list of paths, in which case the
tortoise-and-hare algorithm is O(1) space, though the graph itself would be
(potentially much) larger. Virtually every other operation on such a graph
would take a performance hit, too.

There may be other factors I haven't thought of, but you're right that the
generalized algorithm could not be as space-efficient as the special
algorithm.

It's worth noting, though, that the original question poised in the article
did not place an O(1) restriction on space.

~~~
dllthomas
_" It's worth noting, though, that the original question poised in the article
did not place an O(1) restriction on space."_

For sure.

------
S4M
The page is down, so here is the cached version:
[http://webcache.googleusercontent.com/search?q=cache:rwL5dDE...](http://webcache.googleusercontent.com/search?q=cache:rwL5dDEDvTsJ:www.nomachetejuggling.com/2014/06/24/the-
worst-programming-interview-question/+&cd=4&hl=en&ct=clnk&gl=uk)

------
tzs
A not quite serious solution [1]:

    
    
       Let m = size_of_current_process / sizeof(list_node) + 3
       Let np = pointer or reference to first node in list
       while (np != null)
           if (m-- == 0)
              return HAS_CYCLE
           np = np->next
       return NO_CYCLE
    
    

[1] this approach might actually be acceptable in some circumstances

------
option_greek
I don't want to complain but one of the major culprits who conducts these
kinds of interviews is Amazon. After going through their interview process,
I'm of the opinion that they basically want you to memorize careercup,
geeksforgeeks and leedcode and just spit it out in chunks at appropriate times
during the interview.

------
mcguire
" _... 'Write a func­tion that can detect a cycle in a linked list'...You
can’t reason your way through [that question]...all you’re doing is testing if
someone has seen your par­tic­u­lar puzzler before or not._"

I think I'll take a pass on interview advice from this character.

------
general_failure
Once in an interview I was asked to implement a synchronization mechanism
between processes using shared memory. It turns out this is the petersons
algorithm. I mean if I could solve this, I would be Peterson :) heck, even
smarter because I would do it in 20 mins.

------
azov
I'm no fan of this particular interview question, but the article takes it too
far. You can figure out tortoise-and-hare algorithm by reasoning (I'm pretty
sure I did the first time I've seen the problem - although not in an interview
setting). The key is to recognize that there's a very limited number of things
you can do given all the constraints: moving pointers is pretty much the only
tool you have.

If it indeed took 12 years for the algorithm to appear, it's likely because
finding loops in a linked list isn't a very common problem, not because the
algorithm itself is that hard.

~~~
peaton
Nor is the 12 years thing particularly good reasoning... By that thought
process, it took humans hundreds/thousands/millions of years to develop a
compiler, so how can I be expected to develop one over the course of 4 years
in college? Or even over the course of my life?

~~~
csallen
Not exactly a valid analogy, because his start date isn't "the beginning of
human history", rather it's the development of the linked list data structure,
which is the first point at which humanity possessed sufficient knowledge and
tools to figure out the cycle-detection algorithm.

Given that we didn't have the knowledge or tools necessary to make a compiler
hundreds/thousands/millions of years ago, you'd have to bump up your start
date considerably.

~~~
peaton
Sure, I stretched that too far. But hopefully the point is made. Then should
we expect no students (or anyone) to be able to build a compiler (or os
kernel) in any amount of time given the internet and whatnot? While I may be
articulating this poorly, I think my fundamental issue with his point is
solid.

------
prelud
I am the guy who asks that question on every interview. You can hate on me
now! Let me clarify. I don't expect the candidate to get to the "a-ha" moment
at all. I make my expectations very clear upfront so that the other side
wouldn't panic. However, I expect to see how the candidate would approach the
problem with the right attitude so I could get some insight of his/hers
thinking patterns. I personally wouldn’t mind if an interviewer asked me
something in the lines of "how would you build a nuclear plant?", although I
have no knowledge on the matter.

------
rgawdzik
Uh we did this in our first year CS curriculum...you are telling me your
interview candidates can't even do what a first year CS freshmen can?

~~~
nmrm
Are you referring to tortoise-hare algorithm? I refuse to believe CS freshmen
regularly come up with this _on their own_. Maybe a few percent, everyone else
is googling or relying on huge hints from the lecturer.

If you were referring to a more trivial algorithm (e.g. linear space), I think
you misinterpreted what the interviewer was expecting and would not have
gotten the job.

It's also worth noting -- esp if you're referring to the TH algorithm -- that
CS curricula are not standardized and that there are probably dozens of
"clever trick" algorithms you haven't seen and couldn't come up with on the
spot (e.g. can you initialize an array in constant time?), but someone else
thinks is trivial because they happened to see it in a lecture/read it online.

------
Kenji
My solution would have been: Simply have a wrapper around the linked list that
keeps count of the elements (+1 for insert, -1 for delete, initialized with
0). Traverse the list. If your traversal takes more steps than there are
elements, you can stop it and conclude there's a cycle. I wonder how the
interviewer would value this answer...

~~~
probably_wrong
If you argued that many programming languages already provide list.size() or
equivalent (more so if I told you "in a language of your choice" before), I'd
swallow my pride and accept it.

Then I'd suggest you try the other way, but it's a perfectly good answer.

~~~
anon4
_list.size()_

The problem is, in Java and probably many others, that method computes the
size in linear time by traversing the list. The javadocs for
java.util.LinkedList note that this was a decision taken so that splitting a
list at an arbitrary node, etc. could be a constant-time operation.

------
joesmo
What all algorithm and idiotic interview questions (like moving Mt. Fiji) are
great for is the interviewee himself, not the interviewer. They are a _huge_
red-light indicator that there is something wrong with the engineering culture
and department at the company you're interviewing. While there are exceptions,
in my experience, there is such a direct correlation between the two, that
questions like this have led me to walking out of interviews (politely of
course). Why continue if you know you won't take that horrible position?
Obviously, if you're hired to write algorithms, then it _might_ be a different
story, but most programmers are simply not writing new algorithms. Ever.

~~~
jiggy2011
Isn't writing algorithms almost the definition of programming?

~~~
nmrm
I think "coming up with interesting algorithms" was the intended meaning.

In which case, no, everyday programming is mostly not about designing
algorithms. Otherwise, programmers would spend most of their time with
journals and books, with a few days of programming each month.

~~~
jiggy2011
Interesting is fairly subjective but ultimately you are designing processes to
solve problems. If you cannot demonstrate ability to solve a simple, well
trodden problem how will you be able to solve a new one?

~~~
nmrm
> Interesting is fairly subjective

Interesting is a social construction. As such, I would define interesting as
worthy of publication in a first or second-tier conference at some point in
the history of the field.

> If you cannot demonstrate ability to solve a simple, well trodden problem
> how will you be able to solve a new one?

0\. I've seen many well-respected researchers who have solved truly
interesting, new-to-humanity problems stumble on well-known problems others
consider easy and/or fundamental. In fact, this is probably true for every
single researcher. And doubly so for practitioners. One person's fundamental
technique is another's blind spot.

1\. Simple != easy to come up with. Often _exactly_ the opposite! Take the TH
algorithm as an example. It's a very simple algorithm. Small. Simple. Optimal.
Awesome. Not trivial to discover, however.

2\. Well-trodden -> unless the algorithm is absolutely fundamental and taught
everywhere (e.g. sorting), you've given up on testing problem solving skills.
You're just testing whether the person's intro/DS/algo professor covered this
particular algorithm (and maybe their memory). Or, more likely, rather their
random interview studying happened to hit your pet problem. Since curriculum
is not anywhere close to uniform in CS -- even among top schools -- this is
just silly.

3\. Simple problems don't always have (simple) solutions. Create a fair voting
scheme.

~~~
jiggy2011
It depends on why you are asking the question. Are you literally demanding the
candidate spit out the optimal answer immediately? If they can they it means
they can remember their algorithms class which is a good signal.

If not, can they solve it with a naive method and then make reasonable
attempts to iterate on that, even if they never hit an optimal solution?

It is a little like a high end restaurant asking a trainee chef to make an
omelette, which is apparently common in the culinary industry.

~~~
nmrm
> Are you literally demanding the candidate spit out the optimal answer
> immediately?

I think the author of the article is indicting situations where this is the
case. Perhaps he could have been more explicit up front, but reading between
the lines this is the situation he's complaining about.

> If not, can they solve it with a naive method and then make reasonable
> attempts to iterate on that, even if they never hit an optimal solution?

If I were asking the question, absolutely.

> It is a little like a high end restaurant asking a trainee chef to make an
> omelette, which is apparently common in the culinary industry.

Are there omlettes that are "optimal" (very awesome in some sense)? I honestly
don't know (and if so, man, I want one!)

------
bitL
Come on, this is like the easiest problem you could have gotten during
Google's, Microsoft's or Facebook's phone screening interview. If you can't
figure it out in 10 minutes, then you should forget about working there.

I miss the old times when these puzzlers were asked during interviews. My
theory is that you can recognize an excellent place of work with a great
future when they actually ask you these sorts of questions as it attracts
certain kind of excellent and creative people. I could see the
"interestingness" of companies being shifted as they abandoned these
questions, first Microsoft (picked up by Google), then Google (picked up by
Facebook), like they were passing some kind of "greatness" token (MS->G->FB).

I was told at Google that I solved two problems like this during an interview
that nobody solved before me in 15 minutes (one led to a super complicated
math formula and dynamic programming, the other I solved optimally but
differently to their solution, and provided an optimality proof based on
discrete calculus). It was the greatest and most challenging interview in my
life. I miss it, all interviews nowadays are just boring as hell :-/

~~~
eddd
What did you exactly prove during this interview? That you know to write
readable code? That you are know to code in team? Did you write any test case
during this inteview? Any docs?

~~~
bitL
I proved that my solution had optimal time complexity using discrete calculus,
for a highly non-trivial problem that requires to come up with unexpected
ideas under huge stress.

They saw my own open-space real-time software 3D rendering engine with
texturing and shading (C++/Asm) at SourceForge already, they saw my own SQL
server (many students at my first university were ripping it off for their own
class projects in the next years so it was a mistake to make it open) as well
as other projects I did prior to that interview so they were familiar with my
coding style and quality.

Also, before that while working at SUN I did some work on a test suite with
10,000s of tests, many of them for SUN's own compliance with one of their
standards, making sure it was executing on a distributed cluster every day for
every branch they had in order to ship the best quality to customers. Many of
these tests were for obscure cluster failure cases using custom bleeding-edge
test frameworks. So the answer is no, I didn't write any test at Google
interview, it wasn't required.

How can you prove you can code in a team during an one-on-one interview? At
best you can give hints that you are willing to discuss stuff and change your
progress on input from the interviewer and explore if there is any sort of
chemistry between you two, which is about all you can do.

I really hate this kind of nitpicking, averaging everyone to a "normal" level,
trying to find something wrong in someone because she or he goes against (IMO)
lazy typical stereotype. Enjoy your mediocrity! Are there still hackers on HN?

