Fizz Buzz solution and explanation
9 more videos on this problem
LeetCode Fizz Buzz Solution Explained - JavaNick White · 5:55 · 21K views
Fizz Buzz | LeetCode 412 | C++, Java, PythonKnowledge Center · 6:43 · 8K views
Fizz Buzz | Leet code 412 | Theory explained + Python codeSai Anish Malla · 3:49 · 4K views
FizzBuzz - LeetCode 412 - PythonDeepti Talesra · 5:10 · 4K views
Leetcode 412: Fizz Buzz in Java | Step-by-Step Solution for Coding InterviewsTechnosage · 6:25 · 2K views
LeetCode 412 Fizz Buzz | JavaScript Solution | Top Interview Questions EasySantamaria Code · 4:57 · 1K views
How to solve Fizz Buzz (412) on LeetCode? - JavascriptBecoming A Better Dev (with David) · 6:06 · 754 views
Fizz Buzz | LeetCode 412 (Easy)Destination FAANG · 8:34 · 538 views
LeetCode 412 : Fizz Buzz || EASY || JAVA || Detailed SolutionCodeGPT · 6:00 · 480 views
Leetcode 412 Fizz Buzz (Java)TheAnalyticGuy · 2:28 · 427 views
The problem
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz"ifiis divisible by3and5.answer[i] == "Fizz"ifiis divisible by3.answer[i] == "Buzz"ifiis divisible by5.answer[i] == i(as a string) if none of the above conditions are true.
Example 1:
Input: n = 3 Output: ["1","2","Fizz"]
Example 2:
Input: n = 5 Output: ["1","2","Fizz","4","Buzz"]
Example 3:
Input: n = 15 Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Constraints:
1 <= n <= 104
Approach overview
Problem Overview: Given an integer n, generate a list of strings representing numbers from 1 to n. Replace multiples of 3 with "Fizz", multiples of 5 with "Buzz", and numbers divisible by both with "FizzBuzz". Otherwise, append the number itself as a string.
Approach 1: Simple Iteration with Condition Checks (Time: O(n), Space: O(1) auxiliary)
The direct solution iterates from 1 to n and checks divisibility using the modulo operator. For each number, evaluate i % 3 and i % 5. If both are zero, append "FizzBuzz". If only divisible by 3, append "Fizz". If only divisible by 5, append "Buzz". Otherwise convert the number to a string. The algorithm touches every number exactly once, giving O(n) time complexity. Aside from the output list, it uses constant extra space, so auxiliary space is O(1). This approach relies on basic math operations and straightforward simulation of the rules.
The key detail is ordering the conditions correctly. Check divisibility by 15 or both 3 and 5 first. If you check 3 before the combined case, numbers like 15 would incorrectly return "Fizz". Most implementations either check i % 15 == 0 or concatenate strings when conditions match.
Approach 2: Hash Map Optimized Approach (Time: O(n), Space: O(1))
This version stores divisor–string pairs in a small hash map such as {3: "Fizz", 5: "Buzz"}. During iteration from 1 to n, check each key in the map and append its string when the number is divisible by that key. Build the result string dynamically. If nothing was appended, convert the number to a string and add it to the result list.
The hash map keeps the logic extensible. Adding new rules like 7 → "Bazz" only requires inserting another key-value pair without rewriting conditional chains. The iteration over divisors is constant because the map size is fixed, so total complexity remains O(n) time and O(1) extra space. The approach highlights how small lookup structures simplify repetitive condition checks, a common technique when combining rules in string generation problems.
Recommended for interviews: The simple iteration with condition checks is what interviewers typically expect. It demonstrates clean control flow and understanding of divisibility logic. The hash map variation shows extensibility and cleaner scaling when rules increase, but the classic conditional version proves you can translate problem rules directly into efficient code.
Approach 1: Simple Iteration with Condition Checks
This approach iterates through numbers from 1 to n and applies conditional logic using modulus operations to determine if a number should be represented as "Fizz", "Buzz", or "FizzBuzz". If none of these conditions are met, the number itself is returned as a string.
def fizzBuzz(n):
result = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return resultimport java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
result.add("FizzBuzz");
} else if (i % 3 == 0) {
result.add("Fizz");
} else if (i % 5 == 0) {
result.add("Buzz");
} else {
result.add(Integer.toString(i));
}
}
return result;
}
}#include <vector>
#include <string>
std::vector<std::string> fizzBuzz(int n) {
std::vector<std::string> result;
for (int i = 1; i <= n; ++i) {
if (i % 3 == 0 && i % 5 == 0) {
result.push_back("FizzBuzz");
} else if (i % 3 == 0) {
result.push_back("Fizz");
} else if (i % 5 == 0) {
result.push_back("Buzz");
} else {
result.push_back(std::to_string(i));
}
}
return result;
}var fizzBuzz = function(n) {
let result = [];
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
result.push("FizzBuzz");
} else if (i % 3 === 0) {
result.push("Fizz");
} else if (i % 5 === 0) {
result.push("Buzz");
} else {
result.push(i.toString());
}
}
return result;
};#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** fizzBuzz(int n, int* returnSize) {
char** result = (char**)malloc(n * sizeof(char*));
*returnSize = n;
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
result[i - 1] = strdup("FizzBuzz");
} else if (i % 3 == 0) {
result[i - 1] = strdup("Fizz");
} else if (i % 5 == 0) {
result[i - 1] = strdup("Buzz");
} else {
result[i - 1] = (char*)malloc(12 * sizeof(char));
sprintf(result[i - 1], "%d", i);
}
}
return result;
}using System;
using System.Collections.Generic;
public class Solution {
public IList<string> FizzBuzz(int n) {
IList<string> result = new List<string>();
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
result.Add("FizzBuzz");
} else if (i % 3 == 0) {
result.Add("Fizz");
} else if (i % 5 == 0) {
result.Add("Buzz");
} else {
result.Add(i.ToString());
}
}
return result;
}
}The Python solution utilizes a list to track results. A for loop checks divisibility and either appends Fizz, Buzz, or the number itself.
Time Complexity: O(n), iterating through numbers 1 to n.
Space Complexity: O(n) because of the list storing results.
Approach 2: Hash Map Optimized Approach
This approach uses a hash map to store possible outputs, simplifying conditional checks. By mapping integers to their respective Fizz or Buzz values, we consolidate decision logic, reducing redundancy in the code.
def fizzBuzz(n):
values = ['', 'Fizz', 'Buzz', 'FizzBuzz']
result = []
for i in range(1, n + 1):
index = 3 if i % 15 == 0 else 1 if i % 3 == 0 else 2 if i % 5 == 0 else 0
result.append(str(i) if index == 0 else values[index])
return resultimport java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> fizzBuzz(int n) {
String[] values = { "", "Fizz", "Buzz", "FizzBuzz" };
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
int index = (i % 15 == 0) ? 3 : (i % 3 == 0) ? 1 : (i % 5 == 0) ? 2 : 0;
result.add(index == 0 ? Integer.toString(i) : values[index]);
}
return result;
}
}#include <vector>
#include <string>
std::vector<std::string> fizzBuzz(int n) {
const std::string values[4] = { "", "Fizz", "Buzz", "FizzBuzz" };
std::vector<std::string> result(n);
for (int i = 1; i <= n; ++i) {
int index = (i % 15 == 0) ? 3 : (i % 3 == 0) ? 1 : (i % 5 == 0) ? 2 : 0;
result[i - 1] = (index == 0) ? std::to_string(i) : values[index];
}
return result;
}var fizzBuzz = function(n) {
const values = ['', 'Fizz', 'Buzz', 'FizzBuzz'];
let result = [];
for (let i = 1; i <= n; i++) {
let index = (i % 15 === 0) ? 3 : (i % 3 === 0) ? 1 : (i % 5 === 0) ? 2 : 0;
result.push(index === 0 ? i.toString() : values[index]);
}
return result;
};#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** fizzBuzz(int n, int* returnSize) {
char** result = (char**)malloc(n * sizeof(char*));
const char* values[] = { "", "Fizz", "Buzz", "FizzBuzz" };
*returnSize = n;
for (int i = 1; i <= n; i++) {
int index = (i % 15 == 0) ? 3 : (i % 3 == 0) ? 1 : (i % 5 == 0) ? 2 : 0;
if (index == 0) {
result[i - 1] = (char*)malloc(12 * sizeof(char));
sprintf(result[i - 1], "%d", i);
} else {
result[i - 1] = strdup(values[index]);
}
}
return result;
}using System;
using System.Collections.Generic;
public class Solution {
public IList<string> FizzBuzz(int n) {
string[] values = { "", "Fizz", "Buzz", "FizzBuzz" };
IList<string> result = new List<string>();
for (int i = 1; i <= n; i++) {
int index = (i % 15 == 0) ? 3 : (i % 3 == 0) ? 1 : (i % 5 == 0) ? 2 : 0;
result.Add(index == 0 ? i.ToString() : values[index]);
}
return result;
}
}In Python, an array of possible outputs simplifies decision-making by indexing, reducing levels of nested if-statements. This method enhances readability and reduces repeated conditions.
Time Complexity: O(n) linearly processes each range value.
Space Complexity: O(n), identical to storing result strings.
Approach 3: Simulation
We iterate through each integer from 1 to n. For each integer, we check whether it is a multiple of both 3 and 5, or just a multiple of 3, or just a multiple of 5. Based on the check result, we add the corresponding string to the answer array.
The time complexity is O(n), where n is the integer given in the problem. Ignoring the space consumption of the answer array, the space complexity is O(1).
func fizzBuzz(n int) []string {
ans := make([]string, 0, n)
for i := 1; i < n+1; i++ {
switch {
case i%15 == 0:
ans = append(ans, "FizzBuzz")
case i%3 == 0:
ans = append(ans, "Fizz")
case i%5 == 0:
ans = append(ans, "Buzz")
default:
ans = append(ans, strconv.Itoa(i))
}
}
return ans
}class Solution {
/**
* @param Integer $n
* @return String[]
*/
function fizzBuzz($n) {
$ans = [];
for ($i = 1; $i <= $n; ++$i) {
$s = '';
if ($i % 3 == 0) {
$s .= 'Fizz';
}
if ($i % 5 == 0) {
$s .= 'Buzz';
}
if (strlen($s) == 0) {
$s .= $i;
}
$ans[] = $s;
}
return $ans;
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Simple Iteration with Condition Checks | Time Complexity: |
| Hash Map Optimized Approach | Time Complexity: |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Simple Iteration with Condition Checks | O(n) | O(1) auxiliary | Standard interview solution when rules are fixed (3 and 5) |
| Hash Map Optimized Approach | O(n) | O(1) | When rules may expand or you want cleaner extensible logic |
Frequently asked questions
Is Fizz Buzz easy or hard?
Fizz Buzz is classified as an easy problem. The challenge focuses on implementing simple conditional logic and loops correctly rather than advanced algorithms or data structures.
How to solve Fizz Buzz in O(n)?
Loop through numbers from 1 to n and apply divisibility rules using modulo operations. If a number is divisible by both 3 and 5 output "FizzBuzz", if only by 3 output "Fizz", if only by 5 output "Buzz", otherwise output the number as a string. The single pass over the range guarantees O(n) time complexity.
Fizz Buzz Python or Java solution?
Both Python and Java solutions follow the same logic: iterate from 1 to n and check divisibility using the modulo operator. Python typically builds a list of strings, while Java uses an ArrayList<String>. Each implementation runs in O(n) time with constant auxiliary space.
What is the best approach for Fizz Buzz?
The standard solution is simple iteration with condition checks. Iterate from 1 to n and use modulo operations to test divisibility by 3 and 5. This runs in O(n) time with O(1) auxiliary space and is the approach most interviewers expect.
What data structure is used in Fizz Buzz?
Most implementations only use a result array or list to store the output strings. Some variations use a small hash map that maps divisors (like 3 and 5) to words ("Fizz", "Buzz") to make the rule system easier to extend.
What is the time complexity of Fizz Buzz?
Fizz Buzz runs in O(n) time because the algorithm processes each number from 1 through n exactly once. Each step performs constant-time modulo checks and string operations, so the total runtime scales linearly with n.
Is Fizz Buzz asked at Google, Amazon, or Meta?
Fizz Buzz itself is usually used as a screening or warm‑up question rather than a core interview problem. Companies like Google, Amazon, and Meta have historically used it to verify that candidates can write correct loops, conditions, and basic logic before moving to harder algorithm questions.
