Amazon Interview Question


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
3
of 3 vote

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)

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.

import java.util.TreeMap;
public class PrimeSum {

    TreeMap<Integer, Integer> sums;

    public PrimeSum(int n) { //input the upper limit for all Ns
        sums = new TreeMap<>();
        // init an array to track prime numbers
        boolean[] primes = new boolean[n + 1];
        for (int i = 2; i < n; i++)
            primes[i] = true;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (primes[i]) {
                for (int j = i + i; j < n; j += i)
                    primes[j] = false;
            }
        }
        // insert sums into cache
        int sum = 0;
        for(int i = 2; i <= n; i++) {
            if(primes[i]) {
                sums.put(i - 1, sum);
                sum += i;
            }
        }
        if(primes[n]) {
            sums.put(n, sum);
        }
    }

    public int primeSum(int N) {
        Integer ceiling = sums.ceilingKey(N);
        //if(ceiling == null) {
            //Exception("input value overflows");
        //}
        return sums.get(ceiling);
    }

}

- aonecoding4 January 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

With O(Max_N) preprocessing time and O(Max_N) storage with subsequent queries in O(1) time -

class Primes:
    __primeUptoN = [0, 0]
    __primeSum = [0]

    def __init__(self):
        self.__generatePrimesIfNotGeneratedBefore()

    def primeSum(self, N):
        return self.__primeSum[self.__primeUptoN[N]]

    @classmethod
    def __generatePrimesIfNotGeneratedBefore(Primes):
        if len(Primes.__primeSum) > 1:
            return
        MAX_N = 10 ** 6
        non_primes = set()
        for i in range(2, MAX_N + 1):
            if i not in non_primes:
                Primes.__primeSum.append(Primes.__primeSum[-1] + i)
                j = i + i
                while j <= MAX_N:
                    non_primes.add(j)
                    j += i
            Primes.__primeUptoN.append(len(Primes.__primeSum) - 1)

- tarptaeya January 14, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package general;

import java.util.Arrays;
import java.util.TreeMap;

public class SieveOfEratosthenese {

	public static void getPrimesBySeieveOfEraosthenes(int n, boolean primes[]) {

		for(int i=2; i<= Math.sqrt(n); i++){
			if(primes[i]){
				for(int j=i*i;j<=n; j+=i){
					primes[j] = false;
				}
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int n = 16;
		boolean[] primes = new boolean[n+1];
		Arrays.fill(primes, true);
		getPrimesBySeieveOfEraosthenes(n, primes);
		
		for (int i = 2; i <= n; i++) {
			if (primes[i])
				System.out.print((i) + " ");
		}
		
		TreeMap <Integer, Integer> sums = new TreeMap<>();
		
		int sum =0;
		
		
		for (int i = 2; i <= n; i++) {
			if (primes[i]){
				sums.put(i-1, sum);
				sum +=i;
			}
			
		}
		
		if(primes[n]){
			sums.put(n,sum);
		}
		
		System.out.println( "\n"+  sums.get(sums.ceilingKey(4)));
	}

}

- him4211 January 23, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class SumOfPrimeNumbers {
    static List<Integer> cachePrime = new ArrayList<>();
    static List<Integer> cacheSumPrime = new ArrayList<>();
    static {
        add(2,2);
        add(3,5);
    }

    static private void add(int n, int sum) {
        cachePrime.add(n);
        cacheSumPrime.add(sum);
    }

    static private int nextPrime(int prime) {
        while( true ) {
            ++prime;
            int i = 0;
            for(  ; i < cachePrime.size() ; ++i )
                if( prime % cachePrime.get(i) == 0 )
                    break;
            if( i == cachePrime.size() )
                return prime;
        }
    }

    static public int sumPrime(int n) {
        if( cachePrime.contains(n) ) {
            return cacheSumPrime.get( cachePrime.indexOf(n) );
        }

        int lastPrime = cachePrime.size()-1;
        if( cachePrime.get(lastPrime) > n ) {
            while (cachePrime.get(lastPrime) > n) {
                --lastPrime;
            }
        }
        else {
            int nextPrime = nextPrime(cachePrime.get(lastPrime));
            while (cachePrime.get(lastPrime) < n && nextPrime < n) {
                add(nextPrime, nextPrime + cacheSumPrime.get(lastPrime));
                lastPrime = cachePrime.size() - 1;
                nextPrime = nextPrime(cachePrime.get(lastPrime));
            }
        }
        return cacheSumPrime.get(lastPrime);
    }
}

- DevilDeepu February 08, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;
public class Primes {

	Map<Integer, Integer> cache = new HashMap<Integer, Integer>();
	public static void main(String[] args) {
		Primes primes = new Primes();
		primes.allPrimesTo(20);		
		System.out.println(primes.cache.get(13));
		System.out.println(primes.cache.get(5));
	}
	
	int allPrimesTo(int n) {
		int sum = 0;
		for(int i=2; i<=n; i++) {
			if(isPrime(i)) {
				sum+=i;
				cache.put(i, sum);
			}
		}
		return sum;
	}
	
	boolean isPrime(int n) {
		if(n ==2 ) return false;
		for(int i=2; i<n; i++) {
			if(n%i==0) return false;
		}
		return true;
	}

}

- spiroso February 24, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More