Actually, this is not too dissimilar from one of the most optimal FizzBuzz algorithms:
Create the following lookup list:
[ "", "", "Fizz", "", "Buzz", "Fizz", "", "", "Fizz", "Buzz", "", "Fizz", "", "", "FizzBuzz" ]
For all numbers n from 1 to 100:
Take the string in the lookup list at the index (n-1 mod 15), call it s
If s is the empty string, print the number n
Otherwise, print s
End for
Convert to the required language as needed. For bonus interviewer points, dynamically generate the lookup list (not hard).
a = [ "", "", "Fizz", "", "Buzz", "Fizz", "", "", "Fizz", "Buzz", "", "Fizz", "", "", "FizzBuzz" ]
for i in range(1, 101):
s = a[(i-1) % 15]
if len(s) == 0:
print i
else:
print s
a = [ None, None, "Fizz", None, "Buzz", "Fizz", None, None, "Fizz", "Buzz", None, "Fizz", None, None, "FizzBuzz" ]
for i in range(1, 101):
s = a[(i-1) % 15]
print (s if s else i)
It's from 1 to 100 (a constant), so it'll be really hard to have a finite yet non-O(1) algorithm for fizzbuzz. I'm sure someone will manage though.
EDIT: Well, technically, it's impossible, because O(1) refers to the time complexity with respect to the input, but fizzbuzz doesn't have an input, so that doesn't work.
View all comments
Show parent comment
38
u/atrain728 Jan 16 '14
As someone that interviews, I'd like to say I'd give credit for cleverness, but I think I'd mostly see this as being a smartass.
I don't think it'd go well from there.