A “FizzBuzz” Faux Pas

fizzA little while ago while writing this post, I came across the post by Jeff Atwood where he talks about the FizzBuzz test (originally found here). I remember seeing that post for the first time a couple of years ago and thinking that I would be a little insulted if someone asked me to write something that trivial in an interview. Seeing it again the other day I realized that my feelings hadn't changed. It IS an insulting question. Sure you may quickly weed out complete incompetents by asking it, by you will also alienate just about every competent developer. There is really no reason to ask a question that simple. You might as well ask something more complex, that could really test a programmer's skills. The incompetent will still have no chance, and you won't make the decent developers feel like you're making fun of them. If you can't think of any interesting programming questions to ask (and you don't like my quine question :)), I will try and cover a few decent, straight forward coding questions at some point in the future. But, that's not what this post is about.

You see, when I was reminded of the "FizzBuzz" question, what I actually thought to myself was something along the lines of:

What an insulting question, I could do that in 10 seconds or less!

Of course having thought that, I immediately had to prove to myself that I actually could do it (curse you developer personality :)). So, I took the subsequent 10 seconds to come up with this (in Ruby, of course):

(1..100).each do |index|
  if index % 3 == 0
    puts "fizz"
  elsif index % 5 == 0
    puts "buzz"
  elsif index % 3 == 0 && index % 5 == 0
    puts "fizzbuzz"
  else
    puts index
  end
end

Trivial right?

Did you spot it yet? What I gigantic fail on my part. Here is a snippet of the output:

...
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizz
16
...

Everything is fine until we get to 15 and – no "fizzbuzz". Of course, there is no way we could ever get a "fizzbuzz" with the above code. If a number is divisible by 3 AND 5 it must be divisible by 3 OR 5 and so the first two conditions of the if..else block would match before we ever get to the third one. It should have been this:

(1..100).each do |index|
  if index % 3 == 0 && index % 5 == 0
    puts "fizzbuzz"
  elsif index % 3 == 0
    puts "fizz"
  elsif index % 5 == 0
    puts "buzz"
  else
    puts index
  end
end

Now everything is fine:

...
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
...

The lesson here is this. It is never a good idea to write code mindlessly. No matter how trivial you consider a problem to be, don't just switch off and write it on autopilot. Even if it was only going to take 10 seconds, take a few seconds more to think, before you jump in and then take another 10 seconds to make sure you didn't miss anything once you've finished. Not only will you write better, less buggy code, but you will also never end up in one of those embarrassing situations where you feel insulted by a "fizzbuzz"-type question and get it wrong anyway :). It just doesn't pay to mentally switch off in our line of work. I thought that little snippet of wisdom was worth sharing and even if you already consider it common sense, it never hurts to be reminded.  

Image by Vidiot

  • Jeff Dege

    Seems to me that whether it is insulting or not depends upon how it is asked.

    If the question is phrased as we’ve found that we have been receiving thousands of automatic applications by people not really interested or qualified for a programming position, and have been having problems filtering out the actual programmers from the crowd. Because of this, we’re asking applicants to submit an answer to a very simple programming problem, as a sort of “captcha”, to help us filter out the non-programmers.

    In other words, the request shouldn’t be phrased in such a way as to give the impression that it was meant to challenge anyone’s programming skill.

    That said:

    int foo = 0;
    if (i%3==0) foo |= 1;
    if (i%5==0) foo |= 2;
    switch (foo)
    {
    default:
    case 0:
    printf(“%d\n”, i);
    break;
    case 1:
    printf(“fizz\n”);
    break;
    case 2:
    printf(“buzz\n”);
    break;
    case 3:
    printf(“fizzbuzz\n”);
    break;
    }

    • http://www.skorks.com Alan Skorkin

      That’s a fair point, I don’t think anyone would be offended if it was pointed out that the question is not meant as an insult but rather more of a programmer/non-programmer screen. A more difficult question would do this just as well though, if they don’t know where to even start with a more difficult question, the amount of time spent is approximately the same. But, you’re right the way a question is phrased will have a lot to do with how it is received.

  • http://www.mostlymaths.net Ruben Berenguel

    It is quite an easy error to do, more if you just code without even thinking. My students do these kind of errors a lot of the time… and so do I when I rush to write without thinking. Even when I do think I can do these kind of things, everyone can :) That’s what testing is for, isn’t it?

    More to the point of the question… I would probably feel it was insulting if I was presented with it, but would take it just as a test. Tests can usually be insulting, you go and eat it. From a very good book on go (the oriental board game), the most important thing for improvement is knowing really well your fundamentals. If you keep this hard within you, you won’t feel insulted as a “pro” when asked about the fundamentals: you know the are that, if you don’t know them you don’t deserve anything.

    That are my 2c ;)

    Ruben

    • http://www.skorks.com Alan Skorkin

      I’ve written about fundamentals before and I agree with regarding their value. But, writing a for loop is less of a fundamental and more a of basic. It’s like the difference between being able to hold your breath under water as a diver and being able to breath period. One is a fundamental of the job, the other you need just to be able to live :).

      You’re right though someone with a professional attitude wouldn’t show offense at the question. I wouldn’t, I’d just do it, but inside i’d be thinking that this company is a a bit amateur hour. I might change my mind 5 minutes later, but a crappy first impression will have been made already.

      • http://www.mostlymaths.net Ruben Berenguel

        I think I agree with the distinction fundamental-basics. It is probably a too easy question. I would like to see it implemented someday, with real case studies. I don’t think the other teachers in my course would agree to make it into the next test, but it would be fun to do so :)

  • http://sirupsen.dk Sirupsen

    Now it makes more sense why this one can be quite tricky. I solved mine like this:

    class Fixnum
    def fizzbuzz
    buffer = ”
    buffer += ‘Fizz’ if self % 3 == 0
    buffer += ‘Fuzz’ if self % 5 == 0
    buffer.empty? ? self : buffer
    end
    end

    (1..100).each {|i| puts i.fizzbuzz }

    So I didn’t run into this trouble. :)

    • http://www.skorks.com Alan Skorkin

      Haha, nice one.

    • rjp

      > So I didn’t run into this trouble. :)

      Yabbut you ran into other trouble instead.

      > buffer += ‘Fuzz’ if self % 5 == 0

      “Fuzz” != “Buzz”.

      FizzBuzz: tripping people up every single day.

      • http://sirupsen.dk Sirupsen

        Haha. Damn. It’s not the code though, it’s bad ram in my mind.

  • http://metalelf0dev.blogspot.com/ Andrea Schiavini

    You could have taken 30 seconds instead of 15, and write a unit test before writing your code. I’m sure this would have helped you finding the correct solution at first glance. ;)

    • http://www.skorks.com Alan Skorkin

      Very good point, if I had voting for comments on this blog, I’d promote your one to the top :). Seriously it is amazing how quickly even the most test-crazy developers forget about unit tests outside of their normal work flow.

      • Srdjan Pejic

        I came to make that exact comment. When I first did the FizzBuzz test, I wrote 4 tests. 3 for the conditionals and one for a boundary condition.

        Now, even when I do a throwaway or one-time-use program, I write a small test suite checking the boundaries, possible errors in logic, etc. It’s a good way to get into TDD.

  • http://nithinbekal.com/ Nithin Bekal

    Speaking of insulting questions, I was once asked to write a function that prints “Hello world”. In python!!! At another I was asked how I would swap two integers without creating a third. I guess that’s the level that employers have come to expect of people applying for programming jobs.

    • http://www.skorks.com Alan Skorkin

      Just imagine the relief they would feel when someone can write a “hello world”, it would be an instant hire :). I think as an employer, you’re looking for people at a certain level. It is really not necessary to know if the potential hires can operate at a lower level, you need them to work at a level that you expect. The question you ask should be designed to test this.

  • Amber Shah

    When I read that you found the question insulting, my first thought was that this must be someone who hadn’t conducted many, or possibly any, interviews. I have no idea whether or not that’s true, but speaking as someone who’s conducted my fair share (as well as been interviewed), I don’t think the question is insulting at all.

    Let’s say you put an ad out for a medium-level software developer. Basically you want someone competent with some experience, but not necessarily a guru, who can fit in and be productive on your team. You post an ad on Dice stating something like “2-5 years of experience in language X” and get a 100 resumes (that’s generously low, actually).

    First you weed out people who did not even fit the stated requirements or have blatant spelling errors or other “big” issues, and you’re left with 50 resumes (again, low). Then you select the top 10 that seem compelling to you and you bring them in for an interview (or do a phone screen). So that’s a minimum of 10 hours, assuming you’re not lucky enough to find someone in the first few (and you really aren’t).

    Now, take someone who can’t answer the Fizzbuzz question. Try asking them a more complex question (as you suggested). Often, they won’t even understand, and you’ll have (flustered) try to restate what you thought was obvious. There will be awkard silence. They will fumble. They will try something way off base and you won’t even know what to say. It will literally prolong the entire thing.

    It makes much more sense to start off with something easy, and not bother with something hard unless it’s relevant. It’s a simple process of increasing difficulty, starting at a place where many people will actually fail.

    I realize that part of the point of the post was to state that even trivial problems are not so trivial. But as an applicant I would not be offended by people who would ask me easy questions at the beginning (and then follow up with more difficult ones) as I would be happy to be interviewing with a savvy interviewer.

    • http://www.skorks.com Alan Skorkin

      Hi Amber,

      I haven’t done a lot of interviews, but I’ve done a few :). How would asking a more complex question prolong the entire thing? I think it would shorten everything considerably.

      You: “Could you please explain how a binary tree works? ”
      Them: “A binary what…?”
      You: “Ok, don’t worry, how about you write a function to flatten a multidimensional array?”
      Them: “A multi who?”
      You: “Thanks very much for your time.”

      Total time taken is 2 seconds. If you instead ask them to write what amounts to a basic loop they will at least attempt it, which means you get to sit there for the next 10 minutes watching them stuff it up.

      What is the benefit of asking questions of increasing difficulty. What if the answer the first half of the questions but not the second half (the more difficult ones), do you hire
      or not?

      As I said, you know what kind of level of person you’re looking for, you know what kind of question you would expect them to answer, you might as well start asking questions at that level straight away.

      As an interviewer you should be nice and friendly and considerate, but you’re not there to hold hands with the applicants, just ask the toughest question you would reasonably expect them to answer.

      You’re right, part of the point was to say that even a trivial problem deserves your full attention, but the very reason I switched off on it was because it was so trivial. That was a bit of a fail on my part :), but as an interviewer, do you really want to ask the types of questions that can potentially make the candidates switch off during the process.

  • http://www.michevan.id.au/ Evan

    I think you might be missing the point a little of what the Fizz/Buzz tests are trying to achieve. From what I read of Jeff’s article and related links, it was solely used as a litmus test, not to see how good you are as a programmer, but that you in fact _are_ a programmer. Employers and agencies have basically have to use it in self-defence against the 90.5% of applicants which are just BS artists trying to get a job they are not qualified for.

    “…the fact that 199 out of 200 applicants for every programming job can’t write code at all.”

    I also viewed the article talking about about Fizz Buzz as a _class_ of interview tool with a specific purpose. If you don’t like the actual Fizz Buzz problem, by all means come up with our own litmus test which achieves the same purpose.

    I’ve never been asked asked to write a Fizz Buzz program in an interview, but I would not be offended if I was. I would actually take it as a positive indication that the employer is serious about hiring decent staff and may actually know a think or two about managing programmers, and are just making sure I fall into the 0.5% of applications that are real potential candidates.

    Oh, and here is my small refinement of your ruby code. It requires less comparisons:

    (1..100).each do |index|
    if index % 3 == 0
    puts ( index % 5 == 0 ) ? “fizzbuzz” : “fizz”
    elsif index % 5 == 0
    puts “buzz”
    else
    puts index
    end
    end

    Peace and chocolate.

    E.

    • http://www.skorks.com Alan Skorkin

      Hey Evan,

      I’ve had a chat to a couple of people now (as well looking at a few of the comments above), and many seem to have a similar opinion to your, so perhaps I was being too harsh regarding the fizzbuzz question :).

      I guess if you use it as a pre-screen it is not such a bad thing, i.e. come in for a 5 minute pre-screen interview and if you can pass it we can take the process further. Or even do this question over the phone, i.e. schedule a phone interview time when a person has access to a computer and ask them to e-mail you the code while you’re on the phone.

      I do still believe that there is no reason to ask a question like this in a serious interview, designed to test a person’s coding skills (for reasons I outlined in replies to some of the comments above).

      I like your refinement of the code :).

      • Jeff Dege

        We use it as a screening filter, not a part of the interview. That is, we don’t go through the applications, pick out the most promising, and then give the applicants a problem like fizzbuzz. At that point, it would be an insult. And if we were to ask for a solution to a programming problem, we’d use a much more challenging problem.

        We ask for a solution to a fizzbuzz-type problem as a part of the application. That is, we ask for it up-front, as a part of the ad, and expect to receive a solution along with the resume and cover letter. It lets us toss the 9900 junk applications immediately, without review, so we can begin the actual selection process with the 100 applicants who can actually write a line of code.

        • http://www.skorks.com Alan Skorkin

          Hi Jeff,

          I’ve got no issue at all if it is used in that fashion. Infact I believe a small upfront coding task is a great idea as part of every programmer interview, before you get any interview face-time.

          I am thinking that perhaps I am just failing to appreciate the amount of applications companies get for programming jobs. I thought, surely it can’t be 1000′s, but apparently it can be :).

  • http://www.michevan.id.au/ Evan

    *Sigh* Excuse the bad grammar in the previous comment. Should be, “Employers have basically had to”, and “know a thing or two”.

    Read the bloody thing twice before hitting submit too. :-)

    • http://www.skorks.com Alan Skorkin

      Haha, believe you me, I know all about reading it twice and still getting the grammar/spelling screwed up :).

  • Korny

    If you want to know someone can code, I’d prefer to leave it up to them:
    “Describe a tricky code problem that you solved, and the solution, and how you would do it better if you did it again”. Though people can dodge the question, of course. If I were suspicious, I could keep something like FizzBuzz available just in case.
    Though generally, if someone can answer a slightly technical question like “what is the difference between a mock and a stub” or the like, usually they can code. The trouble is too many interviewers aren’t even willing to ask this level of technical question, and too many interviewees can fake them out by sounding amazing, so you think “I shouldn’t ask this one a code question – that’d be insulting”. So I *always* try to have some genuine only-answerable-by-a-coder questions on hand.
    (Of course, the second interview should be “ok, let’s pair on some code”, which means you’ll weed them out at that stage anyway!)
    oh, and:
    puts (1..100).collect do |x|
    case
    when x % 15 == 0
    “fizzbuzz”
    when x % 5 == 0
    “fizz”
    when x % 3 == 0
    “buzz”
    else
    x.to_s
    end
    end.join(“\n”)

    • http://www.skorks.com Alan Skorkin

      Agree with pretty much everything you said. The only thing is, there are always coding questions you can ask that most people wouldn’t be insulted by even if they are top coders. You can always ask one of those to see if they have coding chops.

      As I said I’ll post some of them some time soon and no I don’t really consider my quine question to be one of them, that one is just an interesting/diverting puzzle (tells you how interested a person is in all things programming, but doesn’t really give the coding skills a work out).

  • Korny

    damn – after posting mine, I pasted it into irb, and it failed :(
    Turns out that I needed *two* extra pairs of brackets:
    puts (((1..100).collect do |x|
    case
    when x % 15 == 0
    “fizzbuzz”
    when x % 5 == 0
    “fizz”
    when x % 3 == 0
    “buzz”
    else
    x.to_s
    end
    end).join(“\n”))

    • http://www.michevan.id.au/ Evan

      Again, the purpose of F/B is _not_ to measure programming prowess, it is purely an up-front first line of defence screening process to weed out the BS artists who say they can program but can’t that would otherwise be wasting more of your time. It is a quick, easy, and apparently effective filtering mechanism. It serves no other purpose.

      Whatever other tests your throw at candidate once you’ve started interviewing them would have other intents (presuming they’ve already done a F/B test) – and probably need to be thought out and designed much more carefully.

      I was thinking after my last comment, I’ve actually had Fizz/Buzz type tests come at the end of the interview, “just to make sure”. In retrospect it seems a bit the wrong way around.

      P.S. Korny – my version on the solution still does less comparisons and a lot less string concatenation. :-^ (Can you tell I cut my teeth writing C code and loading it into EPROMs?)

      P.P.S. See you at MXUG on Wednesday?

      • Korny

        See, I cut my teeth writing C and inline assembler for 80386s … but these days I prefer to optimise for minimal side effects, terseness, and readability, rather than for speed. :)

  • James Martin

    Seems like the question may be valuable in identifying two kinds of people I wouldn’t want to work with:

    1. People who are unable to solve the problem and are unsuitable from a technical perspective
    2. People who are too proud or egotistical to engage with basic problems

    Even the act of solving the problem (including whiteboarding/describing thought process) may reveal potentially useful information about the candidate.

    • http://www.skorks.com Alan Skorkin

      Hi James,

      That’s potentially true, but you have to be careful that some of the candidates don’t “weed out” your company as a result of asking questions like this one. Admittedly this is unlikely to happen if you just use this in the spirit it was intended, (as some people have mentioned, as a pre-screen before a serious coding interview). However if you go overboard with questions like this one, a decent candidate might reconsider working for your company simply because they would be unsure of the kinds of people they would be working with.

  • http://dotnet.kapenilattex.com Jon Limjap

    I have been doing interviews the past two weeks with FizzBuzz as my first question, and it has been immensely helpful in figuring out who was “senior in years” and “senior in ability”, and helps with the fact that the position we’re hiring for (.NET developer) tries to get mid-level and senior devs in one go.

    In several cases I’ve got “Microsoft Certified Professionals with X years of experience” with X > 5 who begin faltering with FizzBuzz. They don’t know what modulo operators are and would resort to looking for decimal points in the division result’s string.

    So insulted? I’ve stopped caring if they get insulted with the question — pride has no place in stringent hiring processes. I let follow-up questions (more difficult/challenging, and many of them conceptual and non-programming) soothe the egos of developers who are initially insulted in having to be asked FizzBuzz in the first place.

    • http://www.skorks.com Alan Skorkin

      Hi Jon,

      I guess I’ve been lucky to have worked with decent people my whole career, and while I’ve seen some developers who I would have considered to be worse than mediocre, none of them would have had trouble with the fizzbuzz. I suppose it’s all relative and if you see enough truly awful “programmers”, the fizzbuzz starts looking like a decent question simply from the amount of people that can’t answer it.

      Well, your story has made my eyes go a little wider and I am shaking my head :). I am sad for our industry and wish there was something more I could do to help it.

  • http://mawson.wordpress.com Jem

    Fancy some codegolf? In scala:

    (1 to 100).map(i=>if(i%5!=0&&i%3!=0) i else if(i%3==0) “fizz%s”.format(if (i%5==0) “buzz” else “”) else “buzz”).foreach(println)

    • http://www.skorks.com Alan Skorkin

      Haha, that’s great, scala FTW :).

  • Mike Woodhouse

    I think it was probably in reaction to the Coding Horror article that I wrote

    1.upto(100) { |n| puts n % 3 == 0 ? n % 5 == 0 ? “fizzbuzz” : “buzz” : n % 5 == 0 ? “fizz” : n }

    But it’s not necessarily the question itself that matters, it’s what you get from the interviewee’s answer – the if/elsif solution given (and my short one above, for that matter) contains some duplication, for example (tests for modulus 3 or 5, repetition of “fizz” and “buzz”) . So a the reaction to a followup question such as “how might you refactor that?” might be informative, or “how would you minimise the locus of change if I introduced ‘foo’ for 7, or wanted an arbitrary set of numbers and words?”

    If asked to refactor, I might write something like the following. I may also comment that it’s probably overkill in this relatively trivial case but I’d hope to show that I have some grasp of advanced (?) concepts like DRY and refactorings such as Extract Method.

    def fizzbuzz(n)
    fb_string = [[3,'fizz'],[5,'buzz']].inject(”) do |output, fb|
    divisor, replacement = fb
    output << ( n % divisor == 0 ? replacement : '' )
    end
    fb_string.size == 0 ? n : fb_string
    end
    (1..100).each { |n| p fizzbuzz(n) }

    I might also comment that, should it be worthwhile to really hone the code, I would like to try simplifying more to remove the temporary string assignment and size check.

    • http://www.skorks.com Alan Skorkin

      Hi Mike,

      You’re right, I guess there is always a way to turn even a relatively trivial question into a more complex one, you just need to be creative and know what you’re trying to find out.

  • http://www.collegebookrenter.com/selltextbooks.cfm sell textbooks online

    It’s great how you can go back and remind yourself although things may seem easy and trivial of you rush threw something just because you think it’s easy or no big deal you are more likely to make mistakes. There is a reason your teachers back in school used to tell you to always double check your work before handing it over!

  • Cecil

    I’ve never been asked this question yet, but if I do I’m totally pulling out J.

    ((0 i.~15 3 5|]){::’FizzBuzz’;’Fizz’;’Buzz’;”:)”0>:i.100

  • http://www.workingsoftware.com.au/ Iain Dooley

    Bit of a latecomer to this post … Just discovered this blog and finding it curiously addictive so I’m reading many old articles at once.

    One important part of the original post I think everyone is missing, especially the TDD responses, is that the interviewee is expected to write the code on paper, obviously not being able to execute it before submitting it.

    That would certainly make me respect the question and take my time writing my solution! I remember questions like these on Uni exams were the downfall of many.

    If you ask me to submit code without compilation/execution I start to get nervous, and I think for obvious reasons – several of the above responses had simple errors that would have meant they failed the test if they didn’t see the code run first before handing it over for examination.

    • http://www.skorks.com Alan Skorkin

      I am glad you’re enjoying it :). It was a while since I wrote this, but the way I am feeling at the moment I think the onus is both on the interviewee and the interviewer. The interviewee loses nothing by taking all questions seriously, so might as well respect the question even if it seems stupid. The interviewer gains by not being a syntax nazi and making allowances for the conditions, as long as they’re heading in the right direction I don’t really need things to be correct.

  • Dilip

    Somewhat off the topic question: How is this ‘FizzBuzz’ problem asked in English? In kids parties, to entertain them, I used to ask exactly the same question with same variations, to young kids sitting in a circle. I would say:

    When your turn comes, say the next number. But,
    1. If your number is a multiple of 3 say 3 instead.
    2. If your number is a multiple of 5 say 5 instead.
    3. If your number is a multiple of both 3 & 5 (like 15, 30), don’t say either 3 or 5, instead say 15.

    I think something on these lines would be a better statement of the ‘FizzBuzz’ problem.
    So. if the 3rd condition was just: if your number is a multiple of 15 say 15.
    Then, 3 (instead of 15) is not a wrong answer, as the last part was not explicitly spelled out.
    Incomplete business problem definition :)

  • Pingback: The Main Reason Why You Suck at Interviews: Lack of Preparation