algoadvance

Leetcode 412. Fizz Buzz

Problem Statement

The problem “Fizz Buzz” asks you to write a program that outputs a string representation of numbers from 1 to n. For multiples of three, it should output “Fizz” instead of the number and for the multiples of five, output “Buzz”. For numbers which are multiples of both three and five, output “FizzBuzz”.

Clarifying Questions

  1. Input Range: What is the range of n we should consider?
    • Generally, let’s assume n to be a positive integer in a reasonable range (e.g., 1 to 10,000).
  2. Output Format: Should the output be in a list, array, or just printed?
    • The typical approach is to return a list of strings.

Strategy

  1. Iteration:
    • We’ll iterate through each number from 1 to n.
  2. Condition Check:
    • Use modulo operation to determine if a number is divisible by 3, 5, or both.
  3. Output based on Condition:
    • If divisible by both 3 and 5, add “FizzBuzz”.
    • If divisible by only 3, add “Fizz”.
    • If divisible by only 5, add “Buzz”.
    • Otherwise, add the number itself in string format.

Code

#include <iostream>
#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 % 15 == 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;
}

// Sample usage
int main() {
    int n = 15; // example input
    std::vector<std::string> result = fizzBuzz(n);

    for (const std::string& s : result) {
        std::cout << s << std::endl;
    }
    
    return 0;
}

Time Complexity

This solution is efficient and straightforward, working within the constraints typically set for such problems.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI