# time O(N) space O(1)
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
res = []
for i in range(n):
i = i +1
if i %5 == 0 and i %3 == 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
solut2
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
# main idea: string contacnation. check for divisability for certain number instead of checking every combination
# time O(N) space O(1)
res = []
for num in range(1,n+1):
by_3 = (num % 3 == 0)
by_5 = (num % 5 == 0)
s = ""
if by_3:
s += "Fizz"
if by_5:
s += "Buzz"
if not s:
s = str(num)
res.append(s)
return res
optimize : to avoid to many contidions, use hashTable to store all the target number
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
# main idea: string contacnation. check for divisability for certain number instead of checking every combination
# time O(N) space O(1)
res = []
d = {3:"Fizz",5:"Buzz"}
for num in range(1,n+1):
s = ""
for k in d:
if num % k == 0:
s += d[k]
if not s:
s = str(num)
res.append(s)
return res