Every single programmer worth his salt is inspired by great programming puzzles. Some puzzles are intended to sharpen your analytical abilities while some others make your programming abilities better.

Programming puzzles are the soul of infotainment in the programming community.

What are your favorite programming puzzles?

For the validity of this question, you may want to check out: Posting programming/algorithmic puzzles on SO

EDIT (From Rob Cooper - NOT OP)

Can we please not have lots of links for "Project Euler" and the like, post the "ACTUAL" puzzles that you find difficult/good - Please get CONTENT on StackOverflow, not just links.

+1  A:

Make you robot not die to the other robot.

Very simple to say, nearly impossible to do.

Looks good, can you please expand on your answer to explain a little more about it? People then visiting the thread here will be able to vote accordingly.
Rob Cooper
Terrarium is a .NET version of this

Project Euler has series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve.

edit: why it is so bad to copy text from the link. I just wanted to post the link and add little description if someone new doesn't know this site. I think those problems is fun to solve with different programming languages. Feel free to edit or delete this post.

Nice. You literally just copied the text from the site...! Dude!
Its bad because it offers nothing of real value. The question asks for a difficult puzzle, not a link to a site containing puzzles. Find a hard one and paste a link to that and outline the puzzle. Be useful, not a link engine ;)
Rob Cooper
+1  A: 

Joels Fizz Buzz.

Not because it is a challenge however, but because it makes it simple to cut the chaff on whom should not be working as a programmer.

Additionally, there is the challenge in writing a fizzbuzz that nobody can understand but still works perfectly, and trying to see whom you can scare with code that should be simple.

Kent Fredric

I find the best problems to sharpen my problem solving skills to be real world problems. Once a friend asked me to look at the game "Magic the gathering" and make a better way for him to find specific cards. So I figured out a way to get a complete listing of cards in the game and fed it to a little custom parser than can direct the important attributes to a spread sheet or a database(never tested that part though). The game has like 15000 with a whole host different attributes, advantages, disadvantages, etc...

So this problem was very unique and interesting to work on. Granted I enjoyed the game already but, adding a new layer of logic and problem solving was an illuminating experience.


I liked the one with chessboard and question how many "queens" (or was it "bishops"?) can you place on it so they cannot attack each other. Normal computing would take a lot of time, but smart data structures made the trick. I think it's some classic puzzle so it can be googled...


As a data structure question I enjoy asking people how they would define the structures needed to support the question:

How would you find a needle in a haystack?

I look for data structures like:

  • Haystack class
    • derives from some sort of IEnumerable<IFarmObject>
  • Hay class
    • implements IFarmObject
  • Needle class
    • implements IFarmObject
  • Searcher class
    • has Find(IEnumerable<IFarmObject> objectToSearch, Type typeOfObjectToSearchFor) method

I can then take it a bit further depending on the data structures that they come up with by asking them to implement in code the data structures they defined and the Find method that they described.

I don't have any java background. But I would ask If I can have preprocessing or not. If pre-processing is allowed, I will construct a trie data structure of all the elements. In that case, search will take O(1).If I am not allowed to do any pre-processing, and there is scope for asking multiple queries, I will sort the items and then I can do binary search in O(logN).
+1  A: 

The puzzle I like is a great interview question. Count the set bits in a byte. Sounds simple right? The follow up is, how can you make it faster? Pretty soon you asking whether it's faster to do it in tight assembler running in level 1 cache, or whether a look-up table generated at compile time is faster.

This problem is better known as a population count, or finding the Hamming weight. The book Beautiful Code has a nice chapter on this.
Is __builtin_popcount a valid answer to both question and follow-up? ;-)
Steve Jessop
+20  A: 

The Eight Queens or N Queens problem is a very interesting algorithmic exercise that I have been asked to solve on a white board during a technical interview. I would not ask this to an interview candidate without prior warning or unless they were interviewing for a senior developer role.

The basic problem statement is:

Given N Queens place count the number of different ways they can be placed on an N x N board so that no queen can attack another queen given one move.

The problem requires an algorithm that implements backtracking:

  • place a queen in column 1 in the first square from the top
  • place a queen in column 2 in the first square
  • check if queens are safe if not move queen in column 2 down one square
  • if queen in column 2 can not be placed on the board go back to queen in column one and move down one place
  • restart process with queen in column 2
  • do this process for each column until a solution is found
  • backtrack as far as you have to each time a queen can not be placed

Heuristics (rules of thumb) can also be used to greatly improve the performance of the basic implementation. So if you are testing someone on algorithmic implementation or development this is a great place to look for how they can develop heuristics.

For instance;

  • queens can not share columns, rows, or diagonals so you can immediately eliminate all cases where this is the case
  • given one solution you can mirror the board to find additional solution without actually computing them, the same is true for non-solutions.

This problem can also be easily tweaked by asking for solutions with other types of chess pieces (rooks, bishops, knights, etc...). Or even a combination of different chess pieces.

Exactly the answers this question should be getting. Good job. +1'ed
Rob Cooper
Yeah buddy, one of the issues stack overflow moderators need to pay attention to is real answers vs just link pasting. It kind of sucks to work hard on an answer just to see that someone that just pasted a link from Google got awarded the answer and all the up votes.
Totally with you man I will down mod, comment, take the flames, everything. I don't care :D I want StackOverflow to stay useful and not be just a spam board like everywhere else. Shame not all the mods push for the same quality. :(
Rob Cooper
Knuth came up with an interesting solution to this using doubly linked lists.
One more heuristic could be that "If you placed a queen at (i,j) then don't check the column (i,j+1),(i+1,j) and (i+1,j+1)". Assuming that we are moving forward always.
+4  A: 

One of my favorite programming puzzles was the one given to volunteers as part of an informal study on the efficacy of various programming languages (original here).

A synopsis of the task:

  • Each letter in the English alphabet corresponds to a single digit, similar to how characters are mapped on a phone.
  • You get a dictionary of words, and an input set of phone numbers.
  • Your software must, for each phone number, try and construct a string out of words in the dictionary, and display every possible permutation.
  • Where no words are available, a single digit may be used, but never more than one digit in succession.
  • There are few other minor rules and a very comprehensive example to resolve ambiguities in the spec.

The beauty here is that this problem is trivially solved in any number of ways; a good programmer should be able to complete the task in 2-4 hours, but the variability in the solutions is astonishing. Some exhibit very good performance, some exhibit very low memory utilization and some are merely elegant, but the results of this programming exercise alone can IMO give a very good gauge of the quality of a programmer. Which data structure and algorithm was chosen? How well-factored is the code? Are corner cases handled properly?

Plus, it's genuinely fun to solve...

Tomer Gabel
It took more than 10 hours for a half of C++ and Java programmers in the study to complete the task.
J.F. Sebastian
True, but if you were trying to make a point I missed it :-)
Tomer Gabel
I think the phrase "for each phone number, try to construct a string out of the words in the dictionary" is somewhat confusing. Do you mean "for each phone number, try to find a word in the dictionary that maps to that number"? As written, it implies (at least to me) that you asking for a sequence (aka, string) of words from the dictionary for each phone number, but that doesn't really line up with the statement that "each letter [...] corresponds to a single digit".
Dale Hagglund
While each letter corresponds to a single digit it's not the other way around - 123 can map to BFG or to BEG. At any rate it's my own wording you're taking issue with, perhaps the original puzzle is more clearly specified.
Tomer Gabel
+2  A: 

The Seven Bridges of Königsberg is a great algorithmic problem as it rely on graph theory for a solution. It is also historically relevant as it lead to Euler's introduction of graph theory to mathematics in the 1700's.

The basic problem statement is:

A city is built on boths sides of a river with two islands between the east and west side of the city. Seven bridges connect the islands to each other and the mainland, the two sides of the city are also directly connected. How can someone walk around the city and cross each bridge only once?

This is somewhat of a trick question in that there is no actual solution. If the above problem is expressed as a graph you will see that each node in the graph has an odd number of edges. For this problem to be solvable at most two nodes source and destination can have an odd number of vertices, the reason for this is that as you travel from one island to another you need a coming and a going bridge. If there are an odd number of bridges you can come and go and come but you can not leave again.

Because there are 4 nodes and you only need to introduce an edge to two of those nodes for a solution to be possible the introduction of an 8th bridge to the question makes it solvable.

I may be a good idea to post a picture of this one.
Brad Gilbert
Federico Ramponi
Sadly enough, some of the bridges don't exist anymore. See 54 42' 24" N 20 30' 34" E on google maps (the center of Kaliningrad, formerly Konigsberg).
Federico Ramponi
+8  A: 

The function rand5() returns an integer between 1 and 5, inclusive (that's 1,2,3,4,5), with equal probability. Use rand5() to create a function called rand7() that returns an integer between 1 and 7, inclusive, with equal probability.

Sounds easy, but it's not. Assume that rand5 generates very high quality random numbers. Can you write a rand7 that has the same randomness quality (e.g. even distribution AND randomness)?

Nils Pipenbrinck
I'd say that is easy, but then I play RPGs, and you learn what's possible with polyhedral dice pretty quickly.
Steve Jessop
Interesting one. My first idea would be to get a Rand5() exactly 7 times, then ... do something with those 7 answers... ?
BradC, good idea. but what to do with the numbers? You can't average them. That would distort the propability. Think of two dices. If you average them you get an answer of 3 or 4 much more ofthen than 1 or 2.
Nils Pipenbrinck
No, you'd have to do something crazy like: If exactly one dice rolled a value of [1], then use the index of that die as the new Rand7(). If not, then re-roll.Of course, that's massively ineffecient.
How about this: Get a value from Rand5() twice. So exactly 25 possible values, right? We are going to take exactly 21 of those possibilities, and map then to 1 to 7. We will ignore the other 4 options, and re-roll. Doesn't really matter exactly WHICH 3 possibilities you map to each Rand7 answer.
Ok, here it is: Get Rand5 twice, call them A and B. Return the following:If A is 1, 2, or 3, then return the value of B. If A is 4, then return "6" if B is 1, 2, or 3. Otherwise, re-roll.If A is 5, then return "7" if B is 1, 2, or 3. Otherwise, re-roll.So each answer has a 3/25 chance.
Use rand5() as a source of random bits. Write random bits to /dev/random. Read from /dev/random random bits and use them for rand7().
J.F. Sebastian
In other words here are two problems: given rand5() generate random stream; and given random stream get rand7(). On average there is log(7)/log(5) calls to rand5() for each rand7() call.
J.F. Sebastian
should it have a finite worse-case time complexity?
I would use the below algorithmrand7(){ return ((rand5()*rand5()*rand5()*rand5()*rand5()*rand5()*rand5())%35)%7;}This guarantees that all the values are having 100/7% probability.
Just as a reference to people who come by - intense discussion on this question is here:
+3  A: 

There are many different kinds of problems that I've found interesting.

First there are those that are interesting because solutions use interesting techniques. For example the Hamming sequence is the list of positive integers whose only factors are 2, 3, and 5 (repeated any number of times. It starts off 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20... However it gets more sparse, for instance the 2999th Hamming number is 278,628,139,008. What is the 5000th number in the Hamming sequence? If you wish to see the techniques behind a solution discussed, read Infinite Lists in Perl.

Then there are problems that are fun because there are many possible solutions. An example was the person who had an array of positive integers and wanted to break the array into n columns of as close to the same length as possible. Note that the order does not change, you are only breaking up the list. See Puzzle: need a more general algorithm for where this was asked on another site, and many resulting attempts at solutions of different levels of efficiency. (The most efficient was in another thread at Re: Balance columns.)

There are problems that are fun because they look impossible. For example write an algorithm that will break a list of integers into two lists whose sums are as close to even as possible. It should always be right, and should be able to handle a list of 100 integers of size 1-500 in reasonable time on a PC. There is an obvious exponential solution that won't work. If you search, you will find that solving this implies a solution to the Partition Problem, which is NP complete. Yet, believe it or not, the problem as stated is solvable.

Then there are arbitrary constraints. See the many golf problems that are out there. To state a simple one, suppose we have two arrays. The first is an array of characters. The second is an array of words made out of those characters. If the first array defines some alphabet in order (it might not be sorted in ASCIIbetical order), write a function that takes references to both arrays and returns the second array in "alphabetical" order. See Golf: Arbitrary Alphabetical Sorting for a series of ever better solutions in Perl.

I must say that although I admire golf solutions in principle, in practice asking a programmer to produce them is like asking a firefighter how best to burn down a hospital: it falls within the bounds of professional knowledge, but is directly contrary to accepted professional conduct.
Steve Jessop
The 3rd problem about breaking a list of integers into two whose sum is as close to equal as possible is not the same as the partition problem. You put a bound on the possible values of the integer while the Partition problem does not bound them. So you aren't solving an NP complete problem.
@Steve Jessop: I beg to differ - code golf is more like writing poetry (or haiku if you will) - the verses can be pretty pr clever but most likely inapplicable to a job description. Not to mention writing stanzas under a gun-point is not something i think i can do :)
Nas Banov
@Nas: sure, and equally you can ask someone to write code without using the letter 'e', or for that matter to write code in iambic pentameter. Eventually the analogy breaks down because professional programming is ruthlessly practical. There isn't really a place for poetry, or for aesthetics at all, except because they can aid code design and comprehension (but golf emphatically does not). So this is all play, not work, and I'm not sure how much useful information about an interviewee you can get that way.
Steve Jessop
+1  A: 

Write a program which outputs its own text.

Reading source code from file and output it to console is inappropriate solution.

Two variations:
1. Character codes can be used.
2. Character codes can NOT be used.

This puzzle is also known as quine.

Better known as a "quine."
Simple java quine:public class Quine { public static void main(String[] args) { char c=34; System.out.println(s+c+s+c+';'+'}'); } static String s="public class Quine { public static void main(String[] args) { char c=34; System.out.println(s+c+s+c+';'+'}'); } static String s=";}
dogbane, thanks. I updated answer.
@fahdshariff what about without usage of char c=34 ? (second variation)

Using 2 6-sided dice, be able to show all the days in a 31-day month.

What numbers do you put on the dice?

0/1/2/3/4/5 and 0/1/2/6/7/8 and use upside down 6 for 9. Although nice it is not a programming puzzle.
@sdkpoly: Very creative. However, you don't need that trick with this: 012456 and 123789
You need the trick if the requirements are to have leading zeros for numbers 1 through 9
Programming puzzle could be like this.Given coin denominations and number of each denomination available, find the minimum coins needed to represent all the numbers <= N.
+4  A: 

I like the classic, detect a loop in a singly-linked list. This puzzle is just easy enough to ask a candidate in an interview, and have them solve it iteratively on the spot. By iteratively, I mean that most candidates will first come up with an algorithm that is slow or memory intensive, or both. For example:

  1. Create an empty set of nodes visited
  2. Begin walking the list
  3. For each node visited, check if it has been visited before by looking in the set
  4. If it has, you have found a loop
  5. Otherwise, add this node to the set
  6. If the next node is null, you are finished and the list has no loop
  7. Get the next node and GOTO 2

This solution executes in O(n * log(n)) time and uses O(n) memory. Not great. Other crummy solutions exist, but a good solution runs in O(n) time and uses O(1) memory.

Starting only with the first node, or with the first node and a nodecount?
Steve Jessop
Relink each node to a special sentinel node (next = node->next; node->next = sentinel). If you encountered the sentinel then there are loops. The downside is It destroys the list.
J.F. Sebastian
The set solution only needs O(nlog(n)) time if you assume a set with log(n) insertion and lookup. Unordered sets can have amortized constant insertion and lookup which give O(n) time.
Unordered sets have O(1) lookup? Please show the algorithm... :-OIf you mean hash tables: please show the proof that it's O(1).
Jonas Kölker
I can think of this solution that fits O(N) time and O(1) memory. It requires one assumption that all the memory addresses of the list are in increasing order. In that case, you can check if the next memory address is less than present memory address and detect a loop.
Floyds cycle-finding algorithm is a really nice and efficient solution for this (also called "Tortoise and the hare"). And is most likely the previously mentioned "good solution". Wikipedia has a nice text about it at:

As far as I know, this puzzle is solvable in C language, but I think it is possible to solve it in other languages too.

You have two variables X and Y, and you have to exchange values between those two variables without using a third variable.

a) try first with numbers: X = 10, Y = 20 b) then with strings: X = "hello", Y = "goodbye"

x = x xor yy = x xor yx = x xor yThe same general principle can be applied to strings, but they would need to be of equal length.
Mike Thompson
Also, if they both point to the same memory location, you're hosed:

This is a good one.

A census taker came to a house where a man lived with three daughters. "What are your daughters' ages?" he asked.

The man replied, "The product of their ages is 72, and the sum of their ages is my house number."

"But that's not enough information," the census taker insisted.

"All right," answered the farmer, "the oldest loves chocolate.

What are the daughters' ages?

Did you leave out the house number or is that part of the puzzle?
The house number is not necessary.This puzzle is due to Martin Gardner (I think). The basic idea is that if two of the three daughters are twins, the other daughter must be older than the two of them. It's simple factoring after that.
2/3/12, 2/6/6, 3/3/8, 3/4/6, 2/4/9, 2/2/18 all meet the requirements of the product equaling 72. I don't see anything mentioning twins, but even then there are duplicate solutions. Am I missing something?
Out of all (13) triplets with product=72 only 2 have same sum (and census didn't know answer at the beginning, but knows house no.):2/6/6 and 3/3/8. The oldest exists (and likes chocolate) only in 3/3/8. Although nice it is not a programming puzzle.
Not so, since even in a pair of twins one is usually older (by minutes). Anyway two daughters could have the same age in years and not be twins, either because the census fell in the right 3 months of the year or because they're only half-sisters. The old man isn't as clever as he thinks he is.
Steve Jessop
I don't know if I'd say that this isn't a programming problem. Ever seen Constraint Logic Programming (CLP)? It is ideal for problems like this. The hard part is *building* a CLP system.
Mark Brittingham
Interesting to see no-one has considered a 1 year old daughter (1 being the multiplication identity makes this puzzle simpler). My solution is (1,4,13), although there are so many others.
Charlie Somerville
Charlie: Isn't 1*4*13 = 52?

The puzzle I like the most goes like this: You have a read only array with n + 1 integers that are in the range 1..n, find one integer that appears at least twice in this array in O(n) time and O(1) extra memory.

Find the sum of these numbers and subract from n(n+1)/2.
@Algorist, your solution only works when exactly one integer appears twice and every other integer in the range 1..n appears once. But the problem is solvable if some integers in the range 1..n do not appear at all and correspondingly there is more than 1 repetition. I'm not going to give hints, since this is quite a nice puzzle.
I think I can construct a hash table and if there is a collsion, I will know the element. Do you know a better way to solve this?
A hash table requires more than O(1) memory, hence hash tables can not be used. But there is a solution that only requires O(n) time and O(1) extra memory. This is why the problem is nice.

My favorite problem is given a binary tree attach a integer weight >= 1 to each leaf such that the sum of the weight in the left and right sub tree of every non leaf node is equal. What is the minimal amount of weight needed to make every node balanced?


It's not a single puzzle, but I've really been enjoying my time spent on the ones from Project Euler.

So far easily my favorite has been problem 15, as I ended up spending several hours deriving the formula to solve it and had some cool realizations and learned quite a bit in the process (I wont give anything away here;)).

Starting in the top left corner of a 2×2 grid, there are 6 routes (without backtracking) to the bottom right corner (See link for picture).

How many routes are there through a 20×20 grid?

Lawrence Johnston
This can be solved with pen and paper
BlueRaja - Danny Pflughoeft
+1  A: 

Given a list of words, find two pairs of words where the pairs are permutations on each others' letters.

For example, if the words are U.S states then one pair is ("south carolina", "north dakota") and the other pair is ("north carolina", "south dakota"). (This is a nice trivia question by itself. It's funny because people try to permute states' letters and when they are told the answer they are surprised how simple it is)

The solution is to make a canonic representation of the letters in each pair (sort the letters). Then sort all the pairs by their sorted-letters and see if then any two consecutive pairs have the same sorted-letters. The sorted table should be keeping indexes/pointers to the original pairs so you will find the answer.


I messed around with writing a sudoku solver and grader for a while. The grader is the hard part. There are many interesting opportunities for puzzle solving when coding a puzzle solver. One thing that comes up in sudoku is finding the canonical form of a solution. The canonical form is used for grading and comparing.

You can swap all occurrences of any two digits and get an equivalent board. You can swap any two rows or columns in a box, or any two box rows or box columns, and the board will be equivalent. Every board has roughly 600 billion equivalent forms and the one that compares least as a string is the canonical form. It will start with 1 through 9 in the first row.

So the puzzle is simply to write an efficient algorithm for finding the canonical form of a sudoku board. You do not need recursion. You do not need much storage.

With a 9x9 board there are roughly 5 billion canonical solutions with 6^8*9! equivalent forms each. For a larger board the complexity of finding a canonical form quickly grows.

+1  A: 

Given only a random bit-generator which is biased (probability of 0 or 1 is not 50/50), can you create a perfect random bit-generator (probability of 0 or 1 is exactly 50/50)?

You don't know anything about the exact probabilities of the bits other than they are > 0%

BlueRaja - Danny Pflughoeft
+4  A: 

alt text

Even though it is more of a calculus thing.
Thomas Ahle

Has anyone seen the Toughest Developer Puzzle Ever? Looks like they just launched 100 new levels yesterday. Pretty cool stuff.

Jeff Blankenburg

This is an interesting problem I came across -

You are in the center of a room which has balloon of various sizes at random location. You have a high powered laser gun which when fired will burst all the balloons which come in its path. So the question is , how will burst off all the balloons in minimum number of shots fired from the laser. You are given the coordinates (x,y,z) of the balloons and also the radius of each. You can assume the laser to be at position (0, 0, 0)

Idea is to find co-linear points and choose line with max number of point on it.How to find co-linear points is itself quite challenging problem. N^2 solution is to take pair of points and store its slope.
Once first line is taken out, recurse on rest of the points. This will give you one of the possible approximate solutions. At the end, it will boil down to 1-0 knapsack problem..

A couple of my favourite algorithmic puzzles are:

1) Given an array a1 a2 ... an b1 b2 ... bn rearrange it to become b1 a1 b2 a2 ... bn an in O(n) time and O(1) space.

2) An O(logn) (integer arithmetic operations) algorithm for computing the nth fibonacci number.