Member-only story
Fizz Buzz is one of the first technical interview practice questions I’ve encountered.
The problem entails outputing an array of string representations of numbers from 1 to n. If the number is a multiple of three the string representation should be ‘Fizz’, if a multiple of five it should be represented as ‘Buzz’, and if a multiple of both represent it as ‘FizzBuzz’.
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
We can take the naive approach of solving this and solve it by using if statements in a single loop.
var fizzBuzz = function(n) {
let answer = []
for(let i = 1; i <= n; i++){
const divisibleBy3 = (i % 3 === 0)
const divisibleBy5 = (i % 5 === 0)
if(divisibleBy3 && divisibleBy5){
answer.push('FizzBuzz')
} else if(divisibleBy3){
answer.push('Fizz')
} else if(divisibleBy5){
answer.push('Buzz')
} else {
answer.push(i.toString())
}
}
return answer
};
Since we’re using a singular for
loop with if/else if/ else statements, the time complexity is O(n) and a space complexity of O(1).
Something to keep in mind when solving is thinking about scalability. What if we said for multiples of 7 we add ‘Pop’. A more scalable approach is:
var fizzBuzz =…