Talentd
FleetCode
Make and follow sheets.Sign in

Fizz Buzz solution and explanation

EasyMathSimulationString5 min read75.9% acceptanceUpdated 9 Apr 2026
LeetCode Fizz Buzz Solution Explained - JavaNick White · 5:55 · 21K viewsWatch on YouTube
9 more videos on this problem
  1. LeetCode Fizz Buzz Solution Explained - JavaNick White · 5:55 · 21K views
  2. Fizz Buzz | LeetCode 412 | C++, Java, PythonKnowledge Center · 6:43 · 8K views
  3. Fizz Buzz | Leet code 412 | Theory explained + Python codeSai Anish Malla · 3:49 · 4K views
  4. FizzBuzz - LeetCode 412 - PythonDeepti Talesra · 5:10 · 4K views
  5. Leetcode 412: Fizz Buzz in Java | Step-by-Step Solution for Coding InterviewsTechnosage · 6:25 · 2K views
  6. LeetCode 412 Fizz Buzz | JavaScript Solution | Top Interview Questions EasySantamaria Code · 4:57 · 1K views
  7. How to solve Fizz Buzz (412) on LeetCode? - JavascriptBecoming A Better Dev (with David) · 6:06 · 754 views
  8. Fizz Buzz | LeetCode 412 (Easy)Destination FAANG · 8:34 · 538 views
  9. LeetCode 412 : Fizz Buzz || EASY || JAVA || Detailed SolutionCodeGPT · 6:00 · 480 views
  10. 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" if i is divisible by 3 and 5.
  • answer[i] == "Fizz" if i is divisible by 3.
  • answer[i] == "Buzz" if i is divisible by 5.
  • 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 result
import 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.

Complexity

Time Complexity: O(n), iterating through numbers 1 to n.
Space Complexity: O(n) because of the list storing results.

Try this approach in the editor

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 result
import 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.

Complexity

Time Complexity: O(n) linearly processes each range value.
Space Complexity: O(n), identical to storing result strings.

Try this approach in the editor

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;
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Simple Iteration with Condition Checks

Time Complexity: O(n), iterating through numbers 1 to n.
Space Complexity: O(n) because of the list storing results.

Hash Map Optimized Approach

Time Complexity: O(n) linearly processes each range value.
Space Complexity: O(n), identical to storing result strings.

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Simple Iteration with Condition ChecksO(n)O(1) auxiliaryStandard interview solution when rules are fixed (3 and 5)
Hash Map Optimized ApproachO(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.

Comments

Now write it yourselfClose this page and solve Fizz Buzz in the editor, without looking.
Practise Fizz Buzz