FizzBuzz Overanalyzed

Fizzbuzz is a common coding competency challenge that tests your ability to work with basic math and logic. The challenge is to write a block of code that accomplishes these goals:

  • Iterate over an incrementing integer. 0, 1, 2, 3… We’ll call this $i. We’ll call the current iteration $n.
  • Write “fizz” when the $n is a multiple of 3.
  • Write “buzz” when the $n is a multiple of 5.
  • Write “fizzbuzz” when both the previous conditions are met.
  • Write the value of $n if none of the above conditions are met.

Commonly the challenge might stipulate that your code should be written as a function. In this case a “fizzbuzz” function will accept one integer $n and return or print the result.

For the FizzBuzz challenge this is what I would consider a fairly typical response (as written in PHP) which we’ll call “Solution 1”:

function fizzBuzz ($n)
{
	if($n % 3 == 0 && $n % 5 == 0) {
		return 'fizzbuzz';
	} 
	else if($n % 5 == 0) {
		return 'buzz';
	} 
	else if($n % 3 == 0) {
		return 'fizz';
	} 
	else {
		return $n;
	}
}

for ($i = 1; $i < 50; $i ++) {
	echo fizzBuzz($i)."\n";
}

The output of this FizzBuzz will look something like this:

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
...

The Gotchas

There’s two main ‘gotchas’ that solution 1 misses. This first is an outright error; the very first check in FizzBuzz should be for the number 0. While the sample codes on this page don’t make use of 0, it’s good to anticipate it depending on who you’re presenting a FizzBuzz to.

if($n == 0) {
	return 0;
} 

The reason for this is because the modulus operator used in FizzBuzz responses returns remainders. If a modulus operation returns 0, it’s a clean division, making it a multiple. Except for 0. 0 will always return a remainder of 0 but isn’t actually considered a multiple of integral numbers. It always surprises me know many FizzBuzz solutions neglect 0.

The second common ‘gotcha’ is known as the “15” condition. Often we see something like this:

if($n % 3 == 0 && $n % 5 == 0) {
	return 'fizzbuzz';
} 

There’s nothing wrong with this response, but it can alternatively be written as…

if($n % 15 == 0) {
	return 'fizzbuzz';
} 

The basic premise is that instead of using two checks (for 3 and 5) in the “fizzbuzz” condition, you can instead use one check for 15. Between any multiple of 3 and 5 the lowest common denominator is 15, and using that to avoid a check potentially saves hundreds of calculations if running the fizzbuzz check thousands of times.

Ultimately, there’s no wrong response to the 15 check, but I would ask any author why they used one method over the other. If they used the two-check method my preferred answer would lean towards readability or “self documentation”. Yes, it’s less efficient, but glancing at the code you more readily have an idea of what the author might be trying to do. If they used the one-check method I’d be fishing for either an answer in outright efficiency or general mathematics. If someone performed the 15 check and didn’t have an answer I’d be a bit more concerned that it’s not their logic and they just read about using 15 somewhere.

Given all this, a more thoughtful FizzBuzz response might look something like this, which we’ll call “Solution 2”;

function fizzBuzz ($n)
{
	if($n == 0) {
		return 0;
	}
	else if($n % 15 == 0) {
		return 'fizzbuzz';
	} 
	else if($n % 5 == 0) {
		return 'buzz';
	} 
	else if($n % 3 == 0) {
		return 'fizz';
	} 
	else {
		return $n;
	}
}

for ($i = 1; $i < 50; $i ++) {
	echo fizzBuzz($i)."\n";
}

Going Ternary

There is, also, further evolution of a good answer which compresses the code down by several lines, and also gives additional performance perks which we’ll call “Solution 3”;

function fizzBuzz ($n)
{
	if($n == 0) {
		return 0;
	}
	else if ($n % 3 == 0) {
		return $n % 5 ? 'fizzbuzz' : 'fizz';
	}
	else {
		return $n % 5 == 0 ? 'buzz' : $n;
	}
}

for ($i = 1; $i < 50; $i ++) {
	echo fizzBuzz($i)."\n";
}

In this more compact variant we not only look at the reduced line count, but also use more efficient codepaths. In this solution we use ternary expressions inside our return statements. Ternary expressions are essentially a more condensed if condition. The above code could be written as nested if statements, but many developers avoid nesting more than a few levels deep as it makes code progressively more difficult to navigate.

On the efficiency front this solution better accounts for modulus (%) not being an efficient operator to use, as far as operators go. Leaving aside the 0 condition the two solutions have what are called “best case” and “worst case” costs to run the function. Below shows these cases, along with the average number of % checks performed after 1000 iterations.

Best “%” CaseWorst “%” CaseAverage “%” CaseAverage Execution Time
Solution 1243.734973837.016
Solution 2132.734688097.077
Solution 32223843310.965
Number of “%” Calls per solution. Average Execution Time is against 10000 iterations with 1000 samples, compared using hrTime.

At first blush the best case scenario is better with solution 2, but solution 2’s best case only applied to one of every 15 iterations. You could shuffle the conditions so the second most efficient path applies to one third of the checks… but in general you’re just pushing a flat logic tree if you do that, when a couple of branches in logic paths will serve you better.

I don’t think anybody in their right mind would expect people to know the performance metrics of FizzBuzz. It’s not exactly real-world code, but if a developer is writing a solution to the FizzBuzz challenge beyond a competency level, I’d be very interested in seeing them push a little bit beyond the basics.

While we don’t want to try micro-optimizing this fairly trivial piece of code, it is always worth seeing when someone tends to write in more efficient manners, or at least, can. If nothing else, it’s always good to see someone push their code just a little bit harder beyond what’s strictly necessary.

Or maybe I’m just overanalyzing it.