↓Skip to main content
  1. LeetCode/

LeetCode 412: Fizz Buzz

·1 min· ·
LeetCode Easy Math String Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Wrong Answer ×4 → Accepted

Approach
#

Go from 1 to n: test i % 15 == 0 first (or 3 or 5 would claim it), then % 3 and % 5, and otherwise output str(i).

My Attempts
#

The first four submissions were WAs:

  • Attempt 1 used // to test multiples (i // 15 == 0 means “less than 15”) and looped only over range(3).
  • The next ones hard-coded ["1", "2"] and started at 3; until // was fixed everything became FizzBuzz, and after switching to %, n = 1 still returned two elements. Dropping the hard-coded start passed.

Solution
#

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        res = []
        for i in range(1, n + 1):
            if i % 15 == 0:
                res.append("FizzBuzz")
            elif i % 3 == 0:
                res.append("Fizz")
            elif i % 5 == 0:
                res.append("Buzz")
            else:
                res.append(str(i))
        return res

Complexity
#

Time O(n), space O(n) (output).

Mistakes to Avoid
#

  • Test multiples with %.
  • The range is 1..n; do not hard-code the first elements.
  • Convert numbers to strings.

Interview Explanation
#

For 1 to n I check 15 first, then 3 and 5, and otherwise output the number as a string. Time O(n).

Related

LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 258: Add Digits
·1 min
LeetCode Easy Math Simulation Number-Theory
LeetCode 258 note: sum the digits repeatedly until one remains; the O(1) answer is the digital root 1 + (n - 1) % 9
LeetCode 171: Excel Sheet Column Number
·1 min
LeetCode Easy Math String
LeetCode 171 note: scan left to right with res = res × 26 + letter value (A = 1)
LeetCode 168: Excel Sheet Column Title
·2 mins
LeetCode Easy Math String
LeetCode 168 note: Excel columns are base 26 without a zero digit; take (n - 1) % 26 as the letter, then n = (n - 1) // 26
LeetCode 13: Roman to Integer
·1 min
LeetCode Easy Hash-Table Math String
LeetCode 13 note: add each symbol’s value left to right, subtracting instead when it is smaller than the symbol to its right