Navigating the Maze of Conditionals: Order Matters!

Here's the classic pitfall.

The order of conditionals in FizzBuzz is an often overlooked detail that makes all the difference. Let's dive into understanding why the sequence is important, and then we can talk a bit about performance.

The Conditional Trap

Remember the earlier example where we used the following if-else ladder in various languages?

1if num % 3 == 0 {
2  // fizz
3} else if num % 5 == 0 {
4  // buzz
5} else if num % 3 == 0 && num % 5 == 0 {
6  // fizzbuzz
7} else {
8  // return number
9}

This isn't quite right!

Here's where many people also go wrong. Why? Because the order will short-circuit the fizzbuzz condition, which needs both 3 and 5 as divisors.

In our conditional, we'll want to address the fizzbuzz scenario first, since it needs to go before the fizz and buzz blocks. Because it is requires being divisible by both 3 and 5, it will get short circuited by either the 3 OR 5 cases first.

To restate, I mean that we need it to pass through the i % 3 == 0 && i % 5 == 0 condition before either of the individual % 3 or % 5 ones. Those cases are still true (and their logic will execute) even in cases where it's true for i % 3 && i % 5.

The time complexity is O(n) as it involves a single loop that iterates through each element once. When you're in a coding interview, pointing out the time complexity can score you extra points.

Some more helpful links: