FizzBuzz: One Simple Interview Question

FizzBuzz: One Simple Interview Question

Ten years ago, a friend of mine called Imran
wrote about hiring programmers. He said that he was seeing people being interviewed with good computer science degrees who, while they knew all the theory, had no idea about how to actually code in
the real world. And he proposed a simple test. Now, hiring programmers is a tricky job. I don’t think that asking complicated
lateral thinking questions is a good way to hire people, and neither is picking folks who you think
will “just fit in”. But a simple test to make sure that someone
can actually code: yeah, that makes sense. So here is the test that Imran proposed: code something that’ll play the children’s
game of FizzBuzz. FizzBuzz is really simple. Traditionally, it is played between two people, and you count up in turn, 1, 2, 3, 4, except every time there’s a multiple of 3, you say “Fizz” instead of the number. And every time there’s a multiple of 5, you
say “Buzz”. So: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, and so on and so on! And when it’s a multiple of both,
at 15, you say “FizzBuzz”. Right, so anyone who’s going in for a job
in computer programming should be able to pass this test: write a program that outputs FizzBuzz for
the numbers 1 to 100. And it’s a clever test for a number of reasons. First, there are many possible approaches. I’ll run through a couple of them here, but you folks will be able to come up with
loads more. If you want, pause the video now
and have a go at it. The approach that people choose, and how they work through the problems, will also give you a good insight into the
style of programmer they are. Do they quickly just bodge things together to make it work and fix immediate problems, like I do, or do they start out planning for the future
and try to figure out what might change later? As well as that, FizzBuzz includes something
that’s a little tricky to express well while programming: If it’s a multiple of 3, you do something. If it’s a multiple of 5,
you do something else. If it’s a multiple of both,
you do a third thing. And if it’s neither,
you do a fourth thing. That’s not instantly translatable into code. So I’m going to show you how I would do it, the quick bodge-it-together approach, and then we’ll see how we can start
to push it a little bit further. I’m writing in JavaScript: it’s not the best
language in the world, but it is one of the easiest
to get started with. First and most obvious step: create a loop. We’re going to want to run through the numbers
1 to 100, so we create a for loop. A for loop works like this:
first, run that bit of code. It creates a variable, i, and it starts it out with the number 1. Then every time it reaches the bottom
of the loop, where the bracket is, it goes back to the top
and runs that bit of code, increasing i by 1, and then checks it against that bit of code. If i is less than or equal to 100, it runs
this code again. If not, it exits the loop. So whatever’s inside here? We are doing it 100 times, and in each loop i
is going to be increased by 1. Programmers use the letter i for variables
like this because… er, actually, I have no idea, it’s just tradition. Okay. Next up. We need something to output the results. In JavaScript, the sort
that’s in a plain text window, you use console.log() for this. If you were putting it in a web page you’d
use something else. So: console.log(i); Output whatever is in the i variable. Test it, and sure enough,
you get 1 through 100. Sometimes, though, we want it to output
‘Fizz’ or ‘Buzz’ instead. So let’s put that in an if statement. If… If what? If i is a multiple of 3, we need to write
‘Fizz’. So: code. That % sign is the modulo operator. It returns the remainder
after you divide something. So here, it’s saying, divide i by 3
and return the remainder. If the remainder is zero, then we know
i is a multiple of 3, and we run that code. And if the remainder’s anything else, then i is not a multiple of 3,
and we skip it. So now again for 5. Now what about FizzBuzz, if it’s a multiple
of both 3 and 5? Well, that’s already been done for us, right? If it’s a multiple of both, then both these tests are
going to return true, and we get ‘Fizz’ and ‘Buzz’. So the last bit: if neither of thode are true, just output the number. In this case, we want that: Okay, it doesn’t look simple,
but I promise it is. That means “not equal to”. And that means “and”. So this whole section will only return true if both the bits in brackets are true. Cool. Let’s run it. And that’s… well, it’s OK, I guess. It does the job. Except… what’s going on at 15? That doesn’t say FizzBuzz. That says “Fizz” and then “Buzz”. Two separate lines. Two separate answers. That is not technically correct, ‘cos it needs to say ‘FizzBuzz’ there. One line. So we can add a few more tests. Let’s add a separate one for FizzBuzz there, using what we’ve learned already. If both of those tests return true, print
“FizzBuzz”. And then let’s add some more tests in there,
so they don’t fire twice. This is getting quite ugly. Repeating yourself like this is a sign of
dodgy code. It’s clumsy, it’s difficult to read
and difficult to maintain. So let’s change it around a bit. Let’s test for both being true first. Now we can use an ‘else’ statement: if it’s not a multiple of both, is it just a multiple of 3? And if it’s not, if is just a multiple of
5? And if it’s still not, then we know to just output the number. But to me, this is still dodgy. Because if someone says, ‘okay, now we want it to work on
multiples of 7, not 5’, and that’s a common sort of follow-up question
for something like this, you have to remember to change all the 5s. Not a big problem in a
section of code this small, but once you start working on something big, this is really bad practice. Ideally, you shouldn’t run the same test twice. But how else can it be done? Well, here’s how I wrote this
the first time I tried it. Create a variable called “output” that’s just
an empty string. A blank bit of text, nothing in it. If i is a multiple of 3, you add “Fizz” to
that line of text. You don’t output anything yet,
you just store that for the future. If i is a multiple of 5, you add “Buzz” to
that line of text. Don’t replace it: just add it. And then, don’t test the number again —
test that string of text. If it’s empty, we know none of these tests were true, so you just make the text the value of i. Now at the end of the loop, you output…
well, the output. So now, if whoever’s running the interview
says ‘make it work on 7s, not 5s’, you only have to change one thing
in an obvious place. If they say ‘make it work on
3s, 5s, 7s, 11s and 13s’, you just copy and paste that line
and it just does. Programming that with else statements
would be a nightmare. Now I think there are still
better ways to code this, particularly if you wanted to plan
long into the future. After all, those lines there… I’m technically repeating myself. But I’ll leave fixing that as a problem for
someone else. This is good enough for me. Now there are still some companies who use
this particular test for hiring, particularly because, y’know, some interviewers
can’t think of anything better. But there are also many problems like it: things that a lot of computer science degrees
don’t teach because they’re all about the theory. Me? I’m more in favour of bodging things together
and making them work well enough. Just don’t leave too much of a mess for whoever comes along to maintain your code
once you’re done with it. Thank you to everyone here at the Centre for
Computing History in Cambridge for letting me film and thank you to all the proofreading team
who helped make sure I got my script right.

93 thoughts on “FizzBuzz: One Simple Interview Question”

  1. I really hope that all the people in the comment who say that "i stands for [word beginning with 'i'] understand that 'i' does not intrinsically stand for anything (well there may have been some type issue with i back in the bad old days of Fortran, but we're way past that now). 'i' stands for whatever you want it to; it's just an entry in a symbol table like any other identifier. Nothing special about it at all.

  2. Андрей Логвин

    Я посмотрел это видео и отупел. Как такие задачи можно использовать для рекрутинга… Если человек решил – это значит только то, что он не умственно отсталый

  3. best approach to this problem:
    Create a config parameter that links divisers to their expected output (could be a simple hashmap or a dictionnary)

    Create a fizzbuzz object that takes as attribute a config parameter.
    Create a fizzbuzz method taking as parameter an input and gives the given output. (a for loop on each element in config that returns output if input%%element==0 and returns input if no output matches.)

    Then instanciate a fizzbuzz object with the given parameter and loop from 1 to 100 calling the fizzbuzz method.

  4. 2:55 . i is short for integer. It just indicates that it is an integer variable. When I was a mainframe COBOL programmer its use was heavily frowned upon. Meaningful variable names were encouraged as it made it easier for somebody else to maintain the code later.

  5. If you want to be sure to get the job, comment your code, even if it seems obvious and self-explanatory to you. It demonstrates good practice and that you think about code maintenance

  6. This is actually easy enough to translate into code, as long as you remember that you can print Fizz and then Buzz later if it turns out to be a multiple of 5.

  7. I remember being told by a friend of having an exercise in college where they are asked to write the dodgiest code, no notes, that they could for some simple task. Any task they wanted. The trick was they exchanged code and had to figure out what the other person was doing and changes to it without talking to the person who'd done the code to begin with. I'm probably incorrectly remembering parts of this but i thought it was a fascinating look at how to teach this field

  8. python3
    print('n'.join('FizzBuzz' if not i % 15 else 'Fizz' if not i % 3 else 'Buzz' if not i % 5 else str(i) for i in range(1,101)))

  9. numb = 1

    numb_list = [str(1)]

    for n in range(1,100):

    numb += 1

    if numb % 15 == 0:



    if numb % 3 == 0:



    if numb % 5 == 0:






  10. A better way would be to delete the line:

    if(output == “”) { output = i; }

    and instead put:

    console.log(output || i);

  11. In R:

    controller = data.frame(divisor=c(3,5),names=c('fizz','buzz'))
    for(i in 1:100){
    output = ''
    for(n in 1:nrow(controller)){if(i %% controller[n,1] == 0){output=paste(output,controller[n,2],sep='')}}
    if(output == ''){output = i}

  12. I took this test on a website (Hackerrank, I guess), a few days back and submitted my answer like 4:50, but the site said the answer is wrong. And so, I didn't continue any more questions on that website thinking the programmers of that site was stupid. But it turns out that I'm the stupid one.

  13. I was watching this video and tried to make my own version in php before I saw how you did it and I find it actually funny how we basically took the same approach

    (my codes if you wonder)

    $fizz = 3;

    $buzz = 5;

    $limit = 400;

    for ($i = 1; $i <= $limit; $i++) {

    if ($i % ($fizz * $buzz) == 0) {

    echo "fizzbuzz<br>";

    } elseif ($i % $fizz == 0) {

    echo "fizz<br>";

    } elseif ($i % $buzz == 0) {

    echo "buzz<br>";

    } else {

    echo "$i<br>";




  14. I now feel overly confident in my ability to learn code.. So much I feel I can ace an interview before actual training 😀

  15. i being used as a general purpose integer is a holdover from Fortran, where identifiers with names starting with the letters i to n were implicitly typed as integer.

  16. When someone forces you to do it in Javascript, there can only be one solution:
    x = NaN === NaN;
    Array.prototype.valueOf = () => x+=1
    while((i=+[]) < (+true + (+false + "") + (+true + "")))
    let str = (i % (true + true + true) == false ? 'fiz' : "") +
    (i % ((+true+(+false+""))/2) == false? 'buzz' : "");
    String(+str) == +{}+'' ? console.log(str) : console.log(i)

  17. I learned beginner programming in a basic course- my roommate was a CS major and I got a waiver to be in the class, despite it being more complicated than the normal course. This is exactly the stuff we went over.

  18. Way easier in python :

    for a in range(101):
    if a%15==0:
    elif a%3==0:
    elif a%5==0:

  19. The best solution I can make:
    options = {

    'Fizz': 3,

    'Buzz': 5}

    def main():

    output = ""

    for i in range(100):

    for x in options.keys():

    if i % options[x] == 0:

    output += x

    if output == "":

    output = i


    output = ""


  20. Last day of law school my lecturer said “is there any law school in the world that doesn’t let you go without being prepared for practice”. The answer is no. And I guess it’s the same with programming

  21. A 16 y/o's attempt at making an expandable version in python:

    nums = [3,5]

    adds = ["","","Fizz","","Buzz"]

    for i in range (1,101):

    output = ""

    for j in range(len(nums)):

    if i % nums[j] == 0:

    output += adds[nums[j]-1]

    if output == "":




  22. My favourite test is getting a candidate to write a game of tennis. The application takes inputs to say who has scored and it should keep track of the score of the game and who wins. All controlled from unit tests. It's really good because most people can suss out how to make it go 0-15, 15-15, 30-15 etc, but you then get deuce and advantage which weeds out the less capable. Same effect as fizzbuzz.. you'll see some people drive straight in and others plan ahead

  23. I use this as a "warmup question" Fizzbuzz is so well now that among the candidates I interview I expect them to honestly be insulted that I asked them fizzbuzz. But, despite that, virtually all the candidates I've ever interviewed were completely unable to solve it.

  24. In my IT class I saw the same problem. People could do programming exams but when it came to our programming projects where you were just given a topic they had know idea where to use for loops, text files, databases, sql, functions, procedures, how to Design a proper effectivel gui, etc.

  25. My fizzbuzz program. For simple task, surprisingly simple, small, fast and complete program. Some limitations apply though. Any other similar tools to solve the problem?
    Is it low bar actually?
    Also you could ask to write several different variants and then ask to compare relative merits. Each with every language company is using or should have knowledge of.
    seq $1|sed '0~15c fizzbuzz
    0~5c buzz
    0~3c fizz'

  26. CHALLENGE ACCEPTED! This took me a minute or so to write:

    function fizzbuzz(limit) {

    for (let i = 1; i <= limit; i++) {

    if (i % 3 === 0 && i % 5 === 0) console.log("FizzBuzz")

    else if (i % 3 === 0) console.log("Fizz")

    else if (i % 5 === 0) console.log("Buzz")

    else console.log(i)




  27. I know absolutely zero computer programming, but my maths brain says use a logic tree: "If A and B, output FizzBuzz; If A not B, output Fizz, If B not A, output Buzz. If neither A, nor B, output number." glad to see you can get half way there with just logic!

  28. At least for python:
    num = range(101)

    for itme in num:

    if (itme %3 == 0) and (itme %5 == 0):


    elif (itme % 3 == 0):


    elif (itme % 5 == 0):




  29. I love JS because you can do more with less code..

    for (let i = 1; i <= 100; i++) console.log((i % 3 ? '' : 'Fizz') + (i % 5 ? '' : 'Buzz') || i);

  30. python 2 oneliner:
    print "n".join([("fizzbuzz" if x%15==0 else "fizz" if x%3==0 else "buzz" if x%5==0 else str(x)) for x in range(1,101)])

  31. I was told that i,j,k for loops came from mathematics. In Math, x,y,z is for variables, a,b,c for parameters, and i,j,k for summation conditions (traditionally)

  32. My solution in R (because stats):
    fizzbuzz <- function(fizz, buzz, n){
    for(i in 1:n){
    output <- ""
    if(i %% fizz == 0) output <- "fizz"
    if(i %% buzz == 0) output <- paste(output, "buzz", sep = "")
    if(output == "") output <- i

    fizzbuzz(fizz=3, buzz=5, n=100)

  33. Simples!

    (doseq [n (range 1 101)]
    (match [(mod n 3) (mod n 5)]
    [0 0] "FizzBuzz"
    [0 _] "Fizz"
    [_ 0] "Buzz"
    :else n)))

  34. I’ve been learning java and it made me really happy that I could pass this! I know it’s not exactly the same as JavaScript but, hey, better than nothing!

  35. This is what I ended up with after taking in all the tips from the video.

    number_to_count = int(input("How high shall we count? "))

    for number in range(1, number_to_count + 1):

    result = ""

    if number % 3 == 0:

    result += "Fizz"

    if number % 5 == 0:

    result += "Buzz"

    if result:



    For adding more variables you could make a dictionary of multiples/word pairs, and have it loop through those, I think.
    It might be messy to stack for loops like that, but it's how I've always done it.

    num_replace = {3 : "fizz", 5 : "buzz", 7 : "fuzz", 11 : "bizz", 13 : "biff"}
    for item in sorted(num_replace):
    if number % item == 0:
    result+= num_replace[item]

  36. Modulo would be slow, I would just add variables for adding to instead and just add to them every time i is equal to them, as for the name of i I think it was just originally short for index/item

  37. Lazy excel attempt =if(mod(A1,N*M)=0, "FizzBuzz", if(mod(a1,N)=0, "Fizz", if(mod(a1,M)=0,"Buzz",A1))) I know there's a more elegant way with boolean function but meh

  38. py3 code if someone wants it:
    for x in range(1, 101):

    if x % 5 == 0 and x % 3 == 0:


    elif x % 5 == 0:


    elif x % 3 == 0:




  39. This is how I did it in golang:

    package main

    import "fmt"

    func main() {

    Fizzes := []int{3, 7}

    Buzzes := []int{5, 11}

    for i := 1; i <= 100; i++ {

    output := ""

    for _, f := range Fizzes {

    if i%f == 0 {

    output += "Fizz"




    for _, b := range Buzzes {

    if i%b == 0 {

    output += "Buzz"




    if output == "" {

    output = fmt.Sprintf("%d", i)





  40. before watching the rest of this video, I would probably do something like

    int isdiv;
    for (int i = 0; i < 100; i++) {
    isdiv = 0;
    if (i % 3 == 0) {
    isdiv = 1;
    if (i % 5 == 0) {
    isdiv = 1;
    if (!isdiv) {
    printf(“%d”, i);

  41. I'm genuinely curious about this, how would you not make it repeat? Like some numbers might output "fizzbuzzbuzz".
    Would you use an if statement on the output? Like:
    If(output = "fizz"&&"buzz"&&"fizzbuzz"&&"")

    Else (

    In my mind this says that if the answer anything other than fizz,buzz, fizzbuzz, or blank then the answer is automatically fizzbuzz. Is this correct?

  42. Solution in C# that can take as many variables as you want.
    void FizzBuzz(IDictionary<string, int> dictionary, int max)


    for(int i = 1; i <= max; i++)


    var output = "";

    foreach (var (k, v) in dictionary) if (i % v == 0) output += k;

    if (output == string.Empty) output = i.ToString();




  43. i as in iteration. Great video as always, and as a hobbyist of programming, I could see an answer as soon as the question was asked, which is really cool!

  44. hmmm I am 2 years late but I'll post my solution

    import java.util.HashMap;

    public class HelloWorld{

    public static void main(String []args){
    HashMap<Integer, String> map = new HashMap<Integer, String>();
    map.put(3, "Fizz");
    map.put(5, "Buzz");
    for(int i = 1; i <= 100; i++){
    String output = "";
    for (int key : map.keySet()) {
    output = i%key == 0 ? output + "" + map.get(key) : output;
    output = output == "" ? ""+i : output;

  45. денис дроздов

    Well i was one step off, i thought of checking for both cases to print numbers and storing 3 and 5 as constants or defined statements in the beginning of the code. But that's just me hating any operations on string variables.

  46. Just a very stupid solution in java that guarantees you will not be taken:

    for (int n=1;n<=100;){System.out.println(!(n%3==0||n%5==0)?n++:(n%3==0?"fizz":"")+(n++%5==0?"buzz":""));}

  47. i stands for a bunch of stuff but the reason why it's stuck around is that back in FORTRAN all variables are considered real numbers by default, except i, j, k, l, m, n default to integers when the type is undeclared. That's why all those are often used for loop counters and other integerial things…. the reason why they are considered real numbers in FORTRAN is that they are traditionally used in math and engineering for representing integer types.

Leave a Reply

Your email address will not be published. Required fields are marked *