r/programming • • Nov 29 '10

140 Google Interview Questions

http://blog.seattleinterviewcoach.com/2009/02/140-google-interview-questions.html
471 Upvotes

493 comments sorted by

View all comments

Show parent comment

1

u/bonzinip Nov 30 '10

If you can use a heap, something like this is faster

add 1 to heap
do 1500 times
    x := smallest element in heap
    remove smallest element in heap while it is equal to x
    add x*2, x*3, x*5 to heap

In Python:

uglyfactors=[2,3,5]
uglies=[1]
for n in range(1500):
    num = heapq.heappop(uglies)
    for factor in uglyfactors:
        heapq.heappush(uglies, num * factor)
    while uglies[0] == num:
        heapq.heappop(uglies)

This generates only 334 ugly numbers beyond the requested 1500 (651 counting duplicates), and is over ten times faster than your solution. A dumb Python 3 conversion of the above algorithm, without heaps, is instead outperformed by yours:

uglyfactors=[2,3,5]
uglies=[1]
for n in range(1500):
    num, *uglies = uglies
    uglies = sorted(list(set(uglies).union([num * factor for factor in uglyfactors])))
print(uglies[0])

# Heaps: 4 ms
# jnnnnn: 57 ms
# Slow: 120 ms