What is really brilliant here, aside of the naive (yet perfect) answer, is the ordering of the results in columns that highlights the pattern of this algorithm
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.
The problem does have an input, the range of numbers that the results will be printed for. It's just that everyone only asks for a specific example of the FizzBuzz problem.
View all comments
128
u/zebishop Jan 16 '14
What is really brilliant here, aside of the naive (yet perfect) answer, is the ordering of the results in columns that highlights the pattern of this algorithm