Amazon Interview Question for Interns


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
2
of 4 vote

Here is a simple optimization explained using an example.

Lets say we need to find factors of 18

We create a set containing factors. Initially insert 1 to the set

Now we check if 18%2 == 0

If yes, we check if 2 exists in the set. It does not, so we insert 2 in the set.
Also, we check if 9 exists in the set (2X9==18) , it does not so we add 9 to the set

Similarly, while checking for 3, we add 3 and 6 to the set.

18%4!=0 and also 18%5!=0, so we dont add 4 and 5 to the set

Now while checking for 6 we notice that 6 already exists in the set. We terminate the process here since the set now contains all the factors.

Finally add n to the set.

Set : 1,2,9,3,6,18

- mandeep March 31, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is correct and most optimal... i think.

- BlackMath April 01, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

just a addon , we can stop at n/2+1 .

- scofield April 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think this problem is not strictly defined. The algorithm above returns all *divisors* of a given number.

if we are talking about factorization of a number into pairwise coprime irreducible factors then we should take into account that some factors can appear multiple times,

e.g. in the above example: 18 = 2 * 3^2 hence 3 has multiplicity 2 as a factor of 18

- Anonymous April 03, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Well you just need to find the factors till sqrt(number). If you have a factor before sqrt(number) then you first do modulus and if modulus is 0 then find the number/i where i is some number between 1 and sqrt(number). In this way you won't do a linear traversal

- Jinal April 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This ain't most optimal I mean worst case for this method is till 0(n^2) since 0(n) to find every time in set and 0(n) while traversing in case the given number is like 19 we end up traversing all the numbers.

- shalinshah1993 June 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

void findfactors_rec(int n, int m)
{
    m = m - 1;

    if(m == 0)
        return;
    if(n % m == 0)
        printf("%d\n", m);

    findfactors_rec(n,m);
}

void findfactors_rec_wrapper(int n)
{
    findfactors_rec(n,n);
}

int main()
{
    findfactors_rec_wrapper(24);
}

- Varun March 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Again use tail recursion. Linear recursion does not have the stack unwinding phase as large

- Anonymous March 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

that is only true in some languages, not all. Java, for example, is not tail-recursion optimized.

- Anonymous April 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

dont get question correctly ??
is it all factor of a given number ??

- abhi March 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

yes, first, write function that returns all factorials of a given number. then how we can enhance this solution

- test222 March 29, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

sorry, factors, not factorials

- test222 March 29, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

What do you mean by "linear traversing"?

- eugene.yarovoi March 30, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def prime_factors(n):
	i = 2
	limit = n**0.5
	while i <= limit:
		if n % i == 0:
		  yield i
		  n = n / i
		  limit = n**0.5
		else:
		  i += 1
	if n > 1:
		yield n

def all_factors(n):
	from itertools import combinations
	pfs = tuple(prime_factors(n))
	for i in xrange(1,len(pfs)):
		for j in combinations(pfs,i):
			yield reduce(int.__mul__,j)

- Oni March 30, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Hi oni ,
Can you please explain the logic.

- shridhar March 30, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. Find all the prime factors
2. Find the all multiplication combinations for all factors using recursion

public class AllFactors {
    
    public static void main(String [] args) {
        int number = 15;
        List<Long> primeFactors = getUniquePrimes(number);
        List<Long> allFactors = new AllFactors().getAllFactors(primeFactors);
        System.out.println(allFactors);
    }
    
    List<Long> allFactorsBuffer = Lists.newArrayList();
    public List<Long> getAllFactors(List<Long> primeFactors) {
        recursiveGrouping(primeFactors, 0, 1);
        return Lists.newArrayList(allFactorsBuffer);
    }
    
    private void recursiveGrouping(List<Long> primeFactors, int position, long startValue) {
        if(position == primeFactors.size()) {
            allFactorsBuffer.add(startValue);
        }
        else {
            recursiveGrouping(primeFactors, position + 1, startValue * primeFactors.get(position));
            recursiveGrouping(primeFactors, position + 1, startValue);
        }
    }
    public static List<Long> getUniquePrimes(long number) {
        List<Long> uniquePrimes = new ArrayList<Long>();
        long primeDivisor = 0;
        long numberCopy = number;
        do {
            primeDivisor = getLeastPrimeDivisor(numberCopy, new ArrayList<Long>());
            if(primeDivisor != -1) {
                numberCopy = numberCopy/primeDivisor;
            }
            if(primeDivisor != -1) {
                uniquePrimes.add(primeDivisor);
            }
            if(primeDivisor == -1) {
                uniquePrimes.add(numberCopy);
            }
        } while(primeDivisor != -1);
        return uniquePrimes;
    }

    private static long getLeastPrimeDivisor(long number, List<Long> primeNumbers) {
        long halfNumber = number/2;
        for(long i = 2; i<= halfNumber; i++) {
            if(isPrime(i, primeNumbers)) {
                if(number%i == 0) {
                    return i;
                }
                else {
                    primeNumbers.add(i);
                }
            }
        }
        return -1;
    }

    private static boolean isPrime(long number, List<Long> primeNumbers) {
        long halfNumber = number/2;
        for(long prime: primeNumbers) {
            if(prime >= halfNumber) break;
            if(number%prime == 0) {
                return false;
            }
        }
        return true;
    }
}

- nandkarthik April 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Use Set<Long>allFactorsBuffer instead of List<Long>allFactorsBuffer for unique factorials.

- nandkarthik April 01, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void foo(int n,vector<int>& vv)
{
int lim=n;
for (int i=1; i<=lim; i++) {
if (n%i==0) {
vv.push_back(i);
if (i!=n/i)
vv.push_back(n/i);
}
lim=n/i;
}
}

- mirandaxu789 April 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

factor of 18 = 1,2,9,3,6,18
factorials of 18 = 1*2*3*4*5*6.......*18
why you guys are concentrating on divisors?

- rohit March 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Isn't divisor synonymous with factor?

- anonymous May 29, 2013 | Flag


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