#412. Fizz Buzz
- Difficulty: Easy
- Company: Cisco
- Optimization: Yes
- Review: November 23, 2024
- Select: Math, String
- Solve: Yes
- Tried: 1
Understanding the Problem
- Multiples of 15 is “FizzBuzz”
- Multiples of 3 is “Fizz”
- Multiples of 5 is “Buzz”
My Answer
/**
* @param {number} n
* @return {string[]}
*/
var fizzBuzz = function(n){
let answer =[];
for(let i=1;i<=n;i++){
if(i%3===0&&i%5===0){
answer.push("FizzBuzz");
}else if(i%3===0){
answer.push("Fizz");
}else if(i%5===0){
answer.push("Buzz")
}else{
answer.push(i.toString());
//answer.push(i+"");
}
}
return answer;
}
- Time: O(n)
- Depends on the size of n(input n).
- Space: O(n)
- The
answer
array stores the result for all numbers from 1 to n.
- Since the size of
answer
array grows linearly with n, space complexity is O(n)
- Description
- The
toString()
method is used to convert numbers into string as the return requires an array of strings.
i+””
can convert number to string. It is little faster than toString() method.
Reflection
Best Answer
/**
* @param {number} n
* @return {string[]}
*/
var fizzBuzz = function(n) {
let final = Array(n).fill(""); // Initialize an array of length n filled with ""
// Use the map method to transform each element of the array based on FizzBuzz rules
return final.map((tempValue, index) => {
const i = index + 1; /// Start numbers from 1 (index starts from 0)
const three = i % 3 === 0 ? "Fizz" : ""; /// "Fizz" for multiples of 3
const five = i % 5 === 0 ? "Buzz" : ""; //// "Fizz" for multiples of 5
const current = three.concat(five);// Combine "Fizz" and "Buzz" if applicable
return current === "" ? i.toString() : current;//Each element of final will be returned
//If the current variable is "", Convert i to string and return
//If the current is not "",return the current(Fizz,Buzz,FizzBuzz)
});
};
- Time: O(n)
- Space: O(n)
- Create the
final
array depends on the length of n
(O(n)).
- Utilize the
map
method depends on the number of the final
array(O(n)).
Note: Map and concat
array.map(()⇒{})
- The
map
can approach all element of array. Inside the map, Callback function is working when the map approach each element
- The
map
method iterates through all elements of the array and applies a callback function to each element.
- The callback function’s return value is used to create a new
array
.
- (tempValue,index,originalArray)⇒{}: The callback function has three parameters.
- tempValue: Represents the current element of the array being processed. It is available only during the execution of the callback function.
- index(option): The index number of each array element
- originalArray(option)
- The array on which
map
was called. It allows you to access or reference the entire array during mapping.
- This array didn’t affected from the call back function.