Given an integer n, for every positive integer i <= n, the task is to print,
- "FizzBuzz" if i is divisible by 3 and 5,
- "Fizz" if i is divisible by 3,
- "Buzz" if i is divisible by 5
- "i" as a string, if none of the conditions are true.
Examples:
Input: n = 3
Output: ["1", "2", "Fizz"]
Input: n = 10
Output: ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz"]
Input: n = 20
Output: ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz", "16", "17", "Fizz", "19", "Buzz"]
[Naive Approach] By checking every integer individually
A very simple approach to solve this problem is that we can start checking each number from 1 to n to see if it's divisible by 3, 5, or both. Depending on the divisibility:
- If a number is divisible by both 3 and 5, append "FizzBuzz" into result.
- If it's only divisible by 3, append "Fizz" into result.
- If it's only divisible by 5, append "Buzz" into result.
- Otherwise, append the number itself into result.
C++ // C++ program for Fizz Buzz Problem // by checking every integer individually #include <iostream> #include <vector> using namespace std; vector<string> fizzBuzz(int n){ vector<string> res; for (int i = 1; i <= n; ++i) { // Check if i is divisible by both 3 and 5 if (i % 3 == 0 && i % 5 == 0) { // Add "FizzBuzz" to the result vector res.push_back("FizzBuzz"); } // Check if i is divisible by 3 else if (i % 3 == 0) { // Add "Fizz" to the result vector res.push_back("Fizz"); } // Check if i is divisible by 5 else if (i % 5 == 0) { // Add "Buzz" to the result vector res.push_back("Buzz"); } else { // Add the current number as a string to the // result vector res.push_back(to_string(i)); } } return res; } int main(){ int n = 20; vector<string> res = fizzBuzz(n); for (const string& s : res) { cout << s << " "; } return 0; }
C #include <stdio.h> #include <stdlib.h> void fizzBuzz(int n) { for (int i = 1; i <= n; ++i) { // Check if i is divisible by both 3 and 5 if (i % 3 == 0 && i % 5 == 0) { // Print "FizzBuzz" printf("FizzBuzz "); } // Check if i is divisible by 3 else if (i % 3 == 0) { // Print "Fizz" printf("Fizz "); } // Check if i is divisible by 5 else if (i % 5 == 0) { // Print "Buzz" printf("Buzz "); } else { // Print the current number printf("%d ", i); } } } int main() { int n = 20; fizzBuzz(n); return 0; }
Java // Java program for Fizz Buzz Problem // by checking every integer individually import java.util.ArrayList; import java.util.List; class GfG { static ArrayList<String> fizzBuzz(int n){ ArrayList<String> res = new ArrayList<>(); for (int i = 1; i <= n; ++i) { // Check if i is divisible by both 3 and 5 if (i % 3 == 0 && i % 5 == 0) { // Add "FizzBuzz" to the result list res.add("FizzBuzz"); } // Check if i is divisible by 3 else if (i % 3 == 0) { // Add "Fizz" to the result list res.add("Fizz"); } // Check if i is divisible by 5 else if (i % 5 == 0) { // Add "Buzz" to the result list res.add("Buzz"); } else { // Add the current number as a string to the // result list res.add(Integer.toString(i)); } } return res; } public static void main(String[] args){ int n = 20; ArrayList<String> res = fizzBuzz(n); for (String s : res) { System.out.print(s + " "); } } }
Python # Python program for Fizz Buzz Problem # by checking every integer individually def fizzBuzz(n): res = [] for i in range(1, n + 1): # Check if i is divisible by both 3 and 5 if i % 3 == 0 and i % 5 == 0: # Add "FizzBuzz" to the result list res.append("FizzBuzz") # Check if i is divisible by 3 elif i % 3 == 0: # Add "Fizz" to the result list res.append("Fizz") # Check if i is divisible by 5 elif i % 5 == 0: # Add "Buzz" to the result list res.append("Buzz") else: # Add the current number as a string to the # result list res.append(str(i)) return res if __name__ == "__main__": n = 20 res = fizzBuzz(n) print(' '.join(res))
C# // C# program for Fizz Buzz Problem // by checking every integer individually using System; using System.Collections.Generic; class GfG { static List<string> fizzBuzz(int n) { List<string> res = new List<string>(); // Loop from 1 to n (inclusive) for (int i = 1; i <= n; ++i) { // Check if i is divisible by both 3 and 5 if (i % 3 == 0 && i % 5 == 0) { // Add "FizzBuzz" to the result list res.Add("FizzBuzz"); } // Check if i is divisible by 3 else if (i % 3 == 0) { // Add "Fizz" to the result list res.Add("Fizz"); } // Check if i is divisible by 5 else if (i % 5 == 0) { // Add "Buzz" to the result list res.Add("Buzz"); } else { // Add the current number as a string to the // result list res.Add(i.ToString()); } } return res; } static void Main(string[] args){ int n = 20; List<string> res = fizzBuzz(n); foreach(string s in res) Console.Write(s + " "); } }
JavaScript // JavaScript program for Fizz Buzz Problem // by checking every integer individually function fizzBuzz(n) { let res = []; for (let i = 1; i <= n; ++i) { // Check if i is divisible by both 3 and 5 if (i % 3 === 0 && i % 5 === 0) { // Add "FizzBuzz" to the result array res.push("FizzBuzz"); } // Check if i is divisible by 3 else if (i % 3 === 0) { // Add "Fizz" to the result array res.push("Fizz"); } // Check if i is divisible by 5 else if (i % 5 === 0) { // Add "Buzz" to the result array res.push("Buzz"); } else { // Add the current number as a string to the // result array res.push(i.toString()); } } return res; } // Driver code let n = 20; let res = fizzBuzz(n); console.log(res.join(' '));
Output1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz
Time Complexity: O(n), since we need to traverse the numbers from 1 to n in any condition.
Auxiliary Space: O(n), for storing the result
[Better Approach] By String Concatenation
While the naive approach works well for the basic FizzBuzz problem, it becomes very complicated if additional mappings comes under picture, such as "Jazz" for multiples of 7. The number of conditions for checking would increases.
Instead of checking every possible combination of divisors, we check each divisor separately and concatenate the corresponding strings if the number is divisible by them.
Step-by-step approach:
- For each number i <= n, start with an empty string s.
- Check if i is divisible by 3, append "Fizz" into s.
- Check if i is divisible by 5, append "Buzz" into s.
- If we add "Fizz" and "Buzz", the string s becomes "FizzBuzz" and we don't need extra comparisons to check divisibility of both.
- If nothing was added, just use the number.
- Finally, append this string s into our result array.
C++ // C++ program for Fizz Buzz Problem // by checking every integer individually // with string concatenation #include <iostream> #include <vector> using namespace std; vector<string> fizzBuzz(int n) { vector<string> res; for (int i = 1; i <= n; i++) { // Initialize an empty string for the current result string s = ""; // Divides by 3, add Fizz if (i % 3 == 0) s.append("Fizz"); // Divides by 5, add Buzz if (i % 5 == 0) s.append("Buzz"); // Not divisible by 3 or 5, add the number if (s.empty()) s.append(to_string(i)); // Append the current res to the result vector res.push_back(s); } return res; } int main() { int n = 20; vector<string> res = fizzBuzz(n); for (const string &s : res) cout << s << " "; return 0; }
C #include <stdio.h> #include <stdlib.h> void fizzBuzz(int n) { for (int i = 1; i <= n; i++) { // Initialize an empty string for the current result char s[10] = ""; // Divides by 3, add Fizz if (i % 3 == 0) strcat(s, "Fizz"); // Divides by 5, add Buzz if (i % 5 == 0) strcat(s, "Buzz"); // Not divisible by 3 or 5, add the number if (strlen(s) == 0) sprintf(s, "%d", i); // Print the current result printf("%s ", s); } } int main() { int n = 20; fizzBuzz(n); return 0; }
Java // Java program for Fizz Buzz Problem // by checking every integer individually // with string concatenation import java.util.ArrayList; class GfG { static ArrayList<String> fizzBuzz(int n) { ArrayList<String> res = new ArrayList<>(); for (int i = 1; i <= n; i++) { // Initialize an empty string for the current result String s = ""; // Divides by 3, add Fizz if (i % 3 == 0) s += "Fizz"; // Divides by 5, add Buzz if (i % 5 == 0) s += "Buzz"; // Not divisible by 3 or 5, add the number if (s.isEmpty()) s += i; // Append the current result to the list res.add(s); } return res; } public static void main(String[] args) { int n = 20; ArrayList<String> res = fizzBuzz(n); for (String s : res) { System.out.print(s + " "); } } }
Python # Python program for Fizz Buzz Problem # by checking every integer individually # with string concatenation def fizzBuzz(n): res = [] for i in range(1, n + 1): # Initialize an empty string for the current result s = "" # Divides by 3, add Fizz if i % 3 == 0: s += "Fizz" # Divides by 5, add Buzz if i % 5 == 0: s += "Buzz" # Not divisible by 3 or 5, add the number if not s: s += str(i) # Append the current result to the list res.append(s) return res if __name__ == "__main__": n = 20 res = fizzBuzz(n) for s in res: print(s, end=" ")
C# // C# program for Fizz Buzz Problem // by checking every integer individually // with string concatenation using System; using System.Collections.Generic; class GfG { static List<string> FizzBuzz(int n) { List<string> res = new List<string>(); for (int i = 1; i <= n; i++) { // Initialize an empty string for the current result string s = ""; // Divides by 3, add Fizz if (i % 3 == 0) s += "Fizz"; // Divides by 5, add Buzz if (i % 5 == 0) s += "Buzz"; // Not divisible by 3 or 5, add the number if (s == "") s += i.ToString(); // Append the current result to the list res.Add(s); } return res; } static void Main() { int n = 20; List<string> res = FizzBuzz(n); foreach (string str in res) { Console.Write(str + " "); } } }
JavaScript // JavaScript program for Fizz Buzz Problem // by checking every integer individually // with string concatenation function fizzBuzz(n) { const res = []; for (let i = 1; i <= n; i++) { // Initialize an empty string for the current result let s = ""; // Divides by 3, add Fizz if (i % 3 === 0) s += "Fizz"; // Divides by 5, add Buzz if (i % 5 === 0) s += "Buzz"; // Not divisible by 3 or 5, add the number if (s === "") s += i; // Append the current result to the array res.push(s); } return res; } // Driver code const n = 20; const res = fizzBuzz(n); console.log(res.join(" "));
Output1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz
Time Complexity: O(n), since we need to traverse the numbers from 1 to n in any condition.
Auxiliary Space: O(n), for storing the result
[Expected Approach] Using Hash Map or Dictionary
When we have many words to add like "Fizz", "Buzz", "Jazz" and more, the second method can still get complicated and lengthy. To make things cleaner, we can use something called a hash map. Initially, we can store the divisors and their corresponding words into hash map.
For this problem, we would map 3 to "Fizz" and 5 to "Buzz" and for each number, checks if it is divisible by 3 or 5, if so, appends the corresponding string from map to the result. If the number is not divisible by either, simply adds the number itself as a string.
C++ // C++ program for Fizz Buzz Problem // by checking every integer individually // with hashing #include <iostream> #include <vector> #include <unordered_map> using namespace std; vector<string> fizzBuzz(int n) { vector<string> res; // Hash map to store all fizzbuzz mappings. unordered_map<int, string> mp = {{3, "Fizz"}, {5, "Buzz"}}; // List of divisors which we will iterate over. vector<int> divisors = {3, 5}; for (int i = 1; i <= n; i++) { string s = ""; for (int d : divisors) { // If the i is divisible by d, add the // corresponding string mapped with d if (i % d == 0) s.append(mp[d]); } // Not divisible by 3 or 5, add the number if (s.empty()) s.append(to_string(i)); // Append the current answer str to the result vector res.push_back(s); } return res; } int main() { int n = 20; vector<string> res = fizzBuzz(n); for (const string &s : res) cout << s << " "; return 0; }
C #include <stdio.h> #include <stdlib.h> #include <string.h> char* fizzBuzz(int n) { char* res = (char*)malloc(n * 20 * sizeof(char)); char buffer[20]; int index = 0; // Hash map to store all fizzbuzz mappings. const char* fizz = "Fizz"; const char* buzz = "Buzz"; for (int i = 1; i <= n; i++) { char s[20] = ""; // Check divisibility and append corresponding strings if (i % 3 == 0) { strcat(s, fizz); } if (i % 5 == 0) { strcat(s, buzz); } // Not divisible by 3 or 5, add the number if (strlen(s) == 0) { sprintf(buffer, "%d", i); strcat(s, buffer); } // Append the current answer str to the result strcat(res, s); strcat(res, " "); } return res; } int main() { int n = 20; char* res = fizzBuzz(n); printf("%s\n", res); free(res); return 0; }
Java // Java program for Fizz Buzz Problem // by checking every integer individually // with hashing import java.util.ArrayList; import java.util.HashMap; class GfG { static ArrayList<String> fizzBuzz(int n) { ArrayList<String> res = new ArrayList<>(); // Hash map to store all FizzBuzz mappings. HashMap<Integer, String> mp = new HashMap<>(); mp.put(3, "Fizz"); mp.put(5, "Buzz"); // List of divisors which we will iterate over. int[] divisors = { 3, 5 }; for (int i = 1; i <= n; i++) { StringBuilder s = new StringBuilder(); for (int d : divisors) { // If the i is divisible by d, add the // corresponding string mapped with d if (i % d == 0) { s.append(mp.get(d)); } } // Not divisible by 3 or 5, add the number if (s.length() == 0) { s.append(i); } // Append the current answer to the result // list res.add(s.toString()); } return res; } public static void main(String[] args) { int n = 20; ArrayList<String> res = fizzBuzz(n); for (String s : res) { System.out.print(s + " "); } } }
Python # Python program for Fizz Buzz Problem # by checking every integer individually # with hashing def fizzBuzz(n): res = [] # Dictionary to store all FizzBuzz mappings. mp = {3: "Fizz", 5: "Buzz"} divisors = [3, 5] for i in range(1, n + 1): s = "" for d in divisors: # If the i is divisible by d, add the # corresponding string mapped with d if i % d == 0: s += mp[d] # Not divisible by 3 or 5, add the number if not s: s += str(i) # Append the current answer str to the result list res.append(s) return res if __name__ == "__main__": n = 20 res = fizzBuzz(n) for s in res: print(s, end=" ")
C# // C# program for Fizz Buzz Problem // by checking every integer individually // with hashing using System; using System.Collections.Generic; class GfG { static List<string> fizzBuzz(int n) { List<string> res = new List<string>(); // Hash map to store all FizzBuzz mappings. Dictionary<int, string> mp = new Dictionary<int, string>{ { 3, "Fizz" }, { 5, "Buzz" } }; // List of divisors which we will iterate over. int[] divisors = { 3, 5 }; for (int i = 1; i <= n; i++) { string s = ""; foreach(int d in divisors) { // If the i is divisible by d, add the // corresponding string mapped with d if (i % d == 0) { s += mp[d]; } } // Not divisible by 3 or 5, add the number if (s == "") { s += i.ToString(); } // Append the current answer str to the // result list res.Add(s); } return res; } static void Main() { int n = 20; List<string> res = fizzBuzz(n); foreach(string s in res) Console.Write(s + " "); } }
JavaScript // JavaScript program for Fizz Buzz Problem // by checking every integer individually // with hashing function fizzBuzz(n) { const res = []; // Hash map to store all FizzBuzz mappings. const mp = {3: "Fizz", 5: "Buzz"}; const divisors = [3, 5]; for (let i = 1; i <= n; i++) { let s = ""; for (let d of divisors) { // If the i is divisible by d, add the // corresponding string mapped with d if (i % d === 0) { s += mp[d]; } } // Not divisible by 3 or 5, add the number if (s === "") { s += i; } // Append the current answer str to the result array res.push(s); } return res; } // Driver code const n = 20; const res = fizzBuzz(n); console.log(res.join(" "));
Output1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz
Time Complexity: O(n), since we need to traverse the numbers from 1 to n in any condition.
Auxiliary Space: O(n), for storing the result
Similar Reads
Fizz Buzz in C++ Fizz Buzz problem states that given an integer n, for every integer i <= n, the task is to write a C++ program to print,'FizzBuzz' if i is divisible by 3 and 5, 'Fizz' if i is divisible by 3, 'Buzz' if i is divisible by 5'i' as a string, if none of the conditions are true.Example:Input: n = 3Outp
5 min read
Fizz Buzz in Python Fizz Buzz Problem involves that given an integer n, for every integer i <= n, the task is to write a Python program to print,'FizzBuzz' if i is divisible by 3 and 5, 'Fizz' if i is divisible by 3, 'Buzz' if i is divisible by 5'i' as a string, if none of the conditions are true.Example:Input: n =
5 min read
Fizz Buzz Implementation | Set 2 Given an integer N, the task is to print all the numbers from 1 to N replacing the multiples of 3, 5 and both 3 and 5 by âFizzâ, âBuzzâ and "Fizz Buzz" respectively. Examples: Input: N = 5Output: 1, 2, Fizz, 4, Buzz Input: N = 15Output: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14Fi
7 min read
The Magic of Fibonacci Numbers Fibonacci Series: The word sounds familiar, right? An Easy To Understand sequence represented as 0 1 1 2 3 5 8 13.... where each number is the sum of the preceding two numbers, with the series starting from 0, 1. But, did you ever realise how magical these numbers are? Let's get deeper into these nu
3 min read
Program to check whether the given number is Buzz Number or not A number is said to be Buzz Number if it ends with 7 OR is divisible by 7. The task is to check whether the given number is buzz number or not.Examples: Input : 63 Output : Buzz Number Explanation: 63 is divisible by 7, one of the condition is satisfied. Input : 72 Output : Not a Buzz Number Explana
4 min read