
Programming trick questions - duckerude
https://qntm.org/trick
======
sethammons
Decent examples. I'd like to toss another in that, years ago, a colleague gave
a candidate. He thought of the question that morning in the shower.

Morse Code. All letters are combinations of one or more dashes and/or dots.
Here is a sentence of Morse Code where the spaces are stripped. Decode it to
get the original ASCII sentence.

He gave it and failed the candidate. Sounding like an interesting problem,
some of us in the office tried it. Turns out that it is a very hard problem.
You have to make a tree of possibilities and it is easy to accidentally make
your solution O(n!).

Moral of the story is never give out a coding question that have not
personally solved. Second moral: be open to out of the box solutions.

~~~
DesiLurker
protip from someone in the trenches: until you have given the problem to many
people in interviews and evaluated their responses to calibrate your
judgement, problems like these serve only one purpose in an interview that is
satisfying interviewers ego about how smart he is.

~~~
ALittleLight
I've proposed (and been rejected) where I work that we have both high and
underperformers go through mock interviews for their roles, to see if our
interview questions could distinguish who was who.

I understand that this is going to be awkward, especially for the low
performers, but at the moment I don't think our interview practices are based
on anything. We ask questions and then later have a conversation about how and
whether or not our questions revealed the presence of the attributes we were
supposed to be assessing for and it feels very made up and make believe. Plus,
people could be given incentives for going through the process and bonuses for
passing the mock interviews to encourage them to try

If we could get people where we already knew how good or bad they were to
rerun the interview process then we could start to figure out which questions
and which evaluation methods were useful in separating good candidates from
poor ones.

~~~
VRay
just make everyone in the company do it IMO, and let the managers distinguish
who was an over/underperformer later on

Of course, you'll just find out that there's practically no correlation.. Some
of the least useful teammates I ever had ended up at Google, and one of the
best programmers I've ever met makes $10/hour at a fucking call center out in
the middle of nowhere

------
baron816
I think “problem solving” questions are pretty much useless. Engineers need to
solve problems, but they don’t have to do it in under an hour and under
stress. Plus, solving tricky problems is not something you do everyday, or
maybe even every week.

What I care about when I do interviews is how they organize their code. I want
to see what people’s instincts and habits are, because that’s what’s going to
determine the quality of 99% of the code they write.

I’d rather have someone who can come up with objectively good abstractions
instead of writing one giant, unintelligible block of code than someone who
can come up with something very clever on the spot to a totally esoteric
problem.

------
whatshisface
I disagree with the answer to #3, you can reverse a Unicode string with
"&#8207;". ;)

[https://en.m.wikipedia.org/wiki/Right-to-
left_mark](https://en.m.wikipedia.org/wiki/Right-to-left_mark)

~~~
zyx321
Will not reverse languages that are right-to-left by default, such as Arabic
or Hebrew.

Will not reverse composed ligatures, e.g. ﷺ is synonymous to صَلَّىٰ ٱللَّٰهُ
عَلَيْهِ وَسَلَّمَ‎‎, but صَلَّىٰ ٱللَّٰهُ عَلَيْهِ وَسَلَّمَ‎‎ with a LTR
directional override is ‭صَلَّىٰ ٱللَّٰهُ عَلَيْهِ وَسَلَّمَ‎‎ while ﷺ remains
as ‭ﷺ.

Will not reverse 겁 into 벅.

~~~
seiferteric
Makes me wonder if we should not have tried to make a single "unicode" and
instead had distinct types for each language like EnglishString ArabicString
etc. and programmers can handle each case as needed.

~~~
zyx321
No. If that's how it worked, how many programs would have Arabic support at
all? Everyone would use EnglishString for everything (because that was the
example code they copied from StackOverflow) and the whole thing comes
crashing down if I enter even just an umlaut.

~~~
seiferteric
No, I was thinking of something a little more sophisticated than that. Classes
of strings would be sub-classed from others like English would have multiple
sub-classes like American, British etc. Each class could have it's own
parameters like whether it supports being reversed. You would not necessarily
implement just for English. If you were making a palindrome finding app for
example, you would only care if the class passed in supports reversing for
example. Eventually you could have a language DB library, not so different
that the time zone database that can be periodically updated with new rules.

------
ddevault
qntm.org is a website worth browsing, if you've never been here before. Some
of my personal favorites:

[https://qntm.org/destroy](https://qntm.org/destroy)

[https://qntm.org/excellent](https://qntm.org/excellent)

------
vortico
#1 got me and I had a good laugh. I wonder if there's a faster method for #2
using AVX and bit tiddling, or if the optimizer is smart enough to find the
most efficient code for a particular architecture.

~~~
leni536
These are the five numbers in binary, to give some inspiration for a bit
twiddling algorithm:

    
    
                              110
                            11100
                        111110000
                    1111111000000
        1111111111111000000000000

~~~
vortico
Hmm, I can't think of a way to use the mathematical structure of those numbers
to speed up checking.

However, the reason I said AVX is because it can be used for checking equality
of 5 (well, 8) numbers simultaneously. This solution requires AVX2 and is
probably faster than the optimized reference code.

    
    
        // Copy x to all 8 elements.
        __m256i a = _mm256_set1_epi32(x);
        // Duplicate 6 because we need to fill all 8 elements.
        __m256i b = _mm256_set_epi32(6, 28, 496, 8128, 33550336, 6, 6, 6);
        // Check for element-wise equality.
        __m256i c = _mm256_cmpeq_epi32(a, b);
        // Check if any bytes are nonzero.
        return _mm256_movemask_epi8(c) != 0;
    

[https://godbolt.org/z/6W8rZy](https://godbolt.org/z/6W8rZy)

~~~
OskarS
I have a hunch that the actually fastest version is to change all those "||"
to "|" in the original version. Short-circuiting and adding branches probably
just slows the whole thing down compared to just running the comparisons,
which will probably pipeline really well.

Interestingly the compiler doesn't do this optimization, even though it could.
So maybe I'm wrong. No real way to know without benchmarking, though.

~~~
vortico
Good idea. This does change the optimized assembly, but it doesn't seem to
make a measureable difference in performance on my machine.

------
hwayne
I like these a lot! I'm seeing them less as "interview questions", which
they'd be terrible as, but as "annoy your friends questions" after you've all
had a couple drinks.

One I heard a while back: "You have a list consisting of every college student
in the US. What's the fastest way to sort them by age in years?"

~~~
amptorn
Other than sorting by birth date, what's your intended solution to this?

~~~
hwayne
Almost all of the students are going to be somewhere between 17 and 23 years
old, so you first do one pass as a bucket sort for each of those seven values.
Then sort the remaining students however you want. While it's technically
still O(n log n), almost everyone is sorted in that first pass, so it's
practically indistinguishable from O(n).

~~~
sethammons
That is actually a decent optimization. If you know the final cardinality, you
just create that many buckets, and drop records in it. Not unlike how
histograms work.

------
llarsson
Are other professionals subjected to the same scepticism during interviews?

Are lawyers given tough questions and expected to come up with a clever
response on the spot? Doctors given a list of symptoms? Teachers given a
difficult student and told to teach them some concept from physics?

Serious question (albeit a bit facetious in my examples).

~~~
dahfizz
Lawyers, doctors, and teachers are all positions that have some form of
certification. Potential employers can be guaranteed that all potential
employees meet the basic knowledge and skills requirements.

Nothing of the sort exists in the programming field. That, coupled with the
high salaries, means fraud is a real problem when trying to hire programmers.

------
mgamache
These are fun brain candy and a reminder of the value of lateral thinking, but
I hope no one actually uses these as employment screening.

~~~
techslave
why not? they are trivial. not “trick” in the sense of poor questions which
are easy enough once you’ve studied the problem for 20 years and know some
trivia that is rare knowledge, but are otherwise insanely difficult.

i think these are good. TELL the candidate they are trick questions. again,
they are trivial. i was actually disappointed.

~~~
barrkel
Better questions are those that more closely simulate a work sample, being
aware that an interview is high stress and time boxed and thus not actually
like work. I like an hour or more pair programming in a language the candidate
is comfortable with on a simplified problem with some relevance to work.

For more senior candidates, you definitely wouldn't want to waste everyone's
time with brain teasers because if the high risk of a hasty rejection - a
deeper probing into systems they've built and and designed in the past, with
an angle on relevant problems for the business, along with the pair
programming.

------
hermanschaaf
Here is another one I thought of the other day.

Q: Given V (the number of vertices), E (the number of edges) and L (a list of
the edges) for a connected undirected graph, determine whether the graph is a
tree.

\----

A: It can be done in O(1) by: return V == E + 1

The number of vertices in a tree is always one more than the number of edges.
We also know that the graph is connected, so it has to be a tree.

------
bobblywobbles
This is what I can't understand about hiring interviews, and I thank 1/2 of my
interviews haven't involved such trickery. Sure - it's "easy" to say "Oh
you've solved this great puzzle, you'd be perfect since you are smart on your
feet", but you can be great at writing UI's, but struggle on the backend.

This culture needs to end. I don't spend my time at work solving puzzles, I
spend time at work meeting with stakeholders, organizing meetings, discussing
options and timelines. I spend my time coding and iterating, not wasting my
time at puzzles.

I hate puzzles, because I like to do work that actually produces results (and
isn't a measure of how smart one might be). Puzzles are a waste of time in my
opinion, a much better proof of pudding would be a programming portfolio of
things you've written (ie. Github).

------
ameixaseca
Interview questions should be trivial examples so you can see if the candidate
know what programming is or how to program on the language, not what libraries
he/she knows. Ideally nothing that depends on any particular OS std libraries
as well. Of course this does not apply if you are hiring someone for a
position where knowledge on a particular library is a requirement, but in my
experience that is usually not the case for either junior nor senior
positions, maybe only for in-between.

If you need anything more advanced you should do an assignment to allow time
for proper design and reasoning, otherwise you'll never be able to fully
evaluate what the candidate really can do and how he/she approaches problems.

------
stephc_int13
I've tried trick programming questions when I started interviewing coders, the
SNR was simply awful and it was frustrating for me and the candidates.

Any evaluation system have to be calibrated on a large enough pool of
candidates, when you're building a company and start interviewing you don't
really have the luxury of wasting the first dozens applications.

Today I tend to completely avoid programming questions, except to reject
complete newbies.

~~~
tasty_freeze
Since I work from home, I haven't had to do interviews in a long time, but
back when I did, I did always ask one programming question, but it would be
only one step harder than trivial.

I'd say use whatever language you want, even make one up, so long as you can
explain parts where I might have questions. I didn't care about syntax, or
performance, or cleverness -- just does it work. If they can't do that, you
don't want them for a coding position.

------
masswerk
Regarding reversing Unicode strings: This is simple, just render the string in
a purposefully crafted mono-space font using distinct, non-overlapping bit
patterns for glyphs (this will be a rather huge font, we may suggest a 0xFFFF
x 0xFFFF matrix for glyphs to be on the safe side), slice the resulting bitmap
image, detect and recompose. ;-)

(Obviously, this is a trick answer.)

~~~
chapium
I know next to nothing about unicode. If I took the bits and arranged them in
reverse order would I be asked to leave the building? It didn't state the
output should also be unicode.

~~~
masswerk
This is much like the practical paper tape answer: punch it on a 8-bit tape
(ASR-33 TeleType) and flip the tape. :-)

------
acangiano
My favorite trick is to not ask trick questions.

------
yters
While I know it is common practice to dismiss problem solving questions, a
good problem solution can be the difference between intractable NP complete or
worse, and a solution that is O(lg N). Additionally, a good solution is
elegant and easily maintainable, while a bad solution is bloated and has large
code debt.

------
whoopdedo
Render string to canvas. Use glyph width to divide into characters. Rearrange
the characters. OCR back into Unicode.

------
ajross
I dunno, these aren't very interesting to me. Question one is good.

Question two relies on the answerer knowing specific details about the
distribution of perfect numbers, which isn't a "trick" in any meaningful
sense. Either you know it or you don't. Contrast with "Are the arguments to
memcmp() declared const in ISO C99?". Is that a "trick" question?

And question three is just senseless pedantry. It says that unicode symbols
don't make "real" strings if you reverse their orders. Which is true, but not
really what the question was asking. ASCII strings aren't "real" if you
reverse their order either, because "real" is a human distinction that doesn't
live at the data layer. It is certainly true that a reversed unicode string
containing ligatures and combining characters is a VALID string per the
unicode standard, which seems to meet the phrasing of the question as asked.

------
misiti3780
How can one get better at questions like these (im horrible at them)?

~~~
nebulous1
Experience. You "should" have been able to get the first one, I think the
other two are pretty debatable as they require knowledge you might have to
research first if you didn't already know about perfect numbers or at least
some of the complexities of unicode.

As far as the first one goes, you could go through some of the questions on
[https://codesignal.com/](https://codesignal.com/) . They're geared towards
interview practice, but ignoring that they provide reasonable problems, a
decent environment to write code in and after you get your solution accepted
you'll be able to access other solutions to get new ideas. The aim here is
just to learn how to think through a problem and allow your brain start to
make connections that it wasn't making before.

~~~
pmiller2
For the perfect number question, you can always just argue that precomputing a
512 MiB bit array that has 1 in position n if n is a perfect number, then
indexing into that bit array is O(1). Because the range is constrained, you
don't need to know anything about perfect numbers to come up with this.

------
zzo38computer
The first question is easily enough; I figured it out. I knew the third
question also, but not the second question.

(Unicode is not suitable for all uses, anyways. Unicode is very messy.)

------
scythe
I wonder if this would be faster on average (most numbers fail all five
comparisons) for #2?

int y = x ^ (x-1);

return x == y * (y+1) / 2 && ([comparison list]);

------
testplzignore
For #1, it really depends on what you mean by "array" and what you need to use
it for. Sounds like an XY problem.

If you take it to mean a more abstract concept of a list of things that can be
iterated and accessed by index, then the fastest implementation is O(1): build
no data structure at all - just implement the iterator and index functions.

If you take it to mean physically manipulating atoms on a chip to be in a
certain state, then you'll actually have to do something :)

~~~
zyx321
An array is a data structure that can be accessed using the Array operator
`[]`. C# will allow overloading the operator, Java will not.

------
kolbe
Does everyone understand something I don’t about #1? It never said they were
unique integers.

~~~
kmill
The array is length N, and it says it contains _the_ integers 1 through N
inclusive, as in, all of them. If there were any repeats, then you'd have an
array of length greater than N.

~~~
kolbe
Seems like somewhat ambiguous semantic garbage to me. Especially when there is
a much clearer three letter word to use (all) that would actually communicate
the the point of the question.

------
lojack
They’re trick questions, so I think it’s fair to be pedantic. It’s asking for
fastest method not the one with least complexity. I would argue the fastest
method would be to pick a random location in memory and get lucky.

------
ape4
I like that its impossible to do "string reversal" until "string" and
"reversal" are defined. Oh you want me to sort an array... how do you define
"sort" and "array".

------
bmn__
Concerning Unicode reversal, the author's statements "This has not been done",
"there is no genuine real-world need", "The algorithm doesn't exist" are wrong
(see UAX #29 §6.4), "suitable metadata might need to be added" has already
been done, and "what a 'string' is considered to be" is well-defined and
requires no deliberation or reinterpretation. His text is surprising to me
because I know the author programs in Perl, JS, Python, so he should really be
knowledgeable about this topic. With the following code samples, all the edge
cases written about in the article are taken care of.

[https://docs.raku.org/routine/flip](https://docs.raku.org/routine/flip)

    
    
        $some-str.flip
    

[https://p3rl.org/unicook#℞-32:-Reverse-string-by-
grapheme](https://p3rl.org/unicook#℞-32:-Reverse-string-by-grapheme)

    
    
        join '', reverse $some_str =~ /\X/g
    

[https://php.net/grapheme_extract](https://php.net/grapheme_extract)

    
    
        ...
    

[https://github.com/dart-lang/characters](https://github.com/dart-
lang/characters)

    
    
        ...
    

[https://grapheme.readthedocs.io/en/latest/grapheme.html#grap...](https://grapheme.readthedocs.io/en/latest/grapheme.html#grapheme.graphemes)

    
    
        from grapheme import graphemes
        "".join(reversed(list(graphemes(some_str))))
    

[https://npmjs.com/package/grapheme-
splitter](https://npmjs.com/package/grapheme-splitter)

    
    
        const gs = new(require('grapheme-splitter'));
        gs.splitGraphemes(some_str).reverse().join('');
    

Rust deserve special mention because the language implementers did the correct
thing and put it in the language: [https://doc.rust-
lang.org/1.3.0/std/str/struct.Graphemes.htm...](https://doc.rust-
lang.org/1.3.0/std/str/struct.Graphemes.html) … only to take it out again for
no good reason, thus rendering the programming language not Unicode compliant
in the process. Talk about snatching defeat from the jaws of victory! m-(

Other languages: try to find a binding for libpcre or libicu.

[http://www.pcre.org/current/doc/html/pcre2pattern.html#Exten...](http://www.pcre.org/current/doc/html/pcre2pattern.html#Extended%20grapheme%20clusters)

[http://userguide.icu-project.org/boundaryanalysis#TOC-
Charac...](http://userguide.icu-project.org/boundaryanalysis#TOC-Character-
Boundary)

------
draw_down
Why are people talking about this in context of employment interviews? The
article doesn’t go there, and neither should anyone else.

Trick questions do not “show you how the candidate thinks” or whatever.
Judging candidates on them is not acceptable.

------
jks
Here's a similar one: What's the best possible time complexity of a program
that plays perfect chess, assuming we could write such a program?

Answer: O(1), since it could be written as one big lookup table from game
state to optimal move. To get a nontrivial complexity class, you have to have
some parameter that can vary, so e.g. the question "what's the time complexity
of a program that plays perfect chess on an n-by-n board?" (assuming a
suitable generalization of the chess rules is given) is much harder to answer.

~~~
clarry
I think that works only if n-by-n can vary to infinity. Otherwise I'll just
have a lut for every possible board size.

By the same method, you can sort any finite sequence in O(1).. but then you
don't really sort infinite sequences, do you? So I'm not sure this is a good
trick question.

