Amazon Interview Question
Software EngineersCountry: United States
Interview Type: Phone Interview
#!/usr/bin/python
"""
This is Sieve Of Eratosthenes Algorithm
"""
def main():
n = 30
print "Sum of prime numbers up to {0} is : {1}".format(n, prime_numbers_SieveOfEratosthenes(n))
def prime_numbers_SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
p = 2
while(p*p <= n):
if prime[p] == True:
for i in range(p*2, n+1, p):
prime[i] = False
p += 1
result = []
sum = 0
for p in range(2, n):
if prime[p]:
sum += p
return sum
if __name__ == '__main__':
main()
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
I. At first find found all primes <= N (sieve of Eratosthenes). Getting the sum will be easy then.
Follow-up:
Cache the sums for any given N to save time. {N:SUM}
Optimization: Don't have to store sums for every N.
When N = 7, N = 8, N = 9, N = 10, the prime sum remains 17.
For N between 11 to 12, the prime sum is 28.
For N between 13 to 16, the sum is 41.
Use a BST structure as the cache. For N = 16, cache:
{2:3, 4:6, 6:11, 10:17, 12:28, 16:41}
For a given N, call cache.ceilingKey(N) to find the bucket for N.
N/log(n) * log(N)
Complexity
Time:
sieve of Eratosthenes takes O(NloglogN) time.
Insert an element into BST takes O(logN), there are N/logN primes in total to be added.
So building the cache takes logN * N / LogN = O(N) time
requesting primeSum(N) takes O(logN)
Space:
sieve of Eratosthenes takes O(N) extra space which will later be release after the cache is created.
Cache: O(N/logN)
- aonecoding July 28, 2017