Amazon Interview Question for Computer Scientists


Country: India
Interview Type: In-Person




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

O(n) time and O(n) space algorithm:

- Maintain a hashmap (Number -> count)
- Iterate through the array and fill the hashmap. If the element is present, increase the count
- Iterate through the map to find 3 most repeated elements.

- Chander Shivdasani September 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Would you please elaborate the last step i.e.
- Iterate through the map to find 3 most repeated elements.

- guptasunny158 September 23, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@guptasunny158 : After populating the hashmap the task is to count the 3 most repeated number. For the you have to iterate the hashmap once.

- Psycho October 02, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

In Java using 3 length array

public void findThreeMostRepeated(int[] ints) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < ints.length; i++) {
            int curr = ints[i];
            Integer count = 1;
            if (map.containsKey(curr)) {
                count = map.get(curr);
                count++;
            }
            map.put(curr, count);
        }

        int[] rep = new int[3];
        for (Integer key:map.keySet()) {
            Integer count = map.get(key);
            if (count > rep[0]) {
                rep[0] = key;
                Arrays.sort(rep);
            }
        }

        System.out.println(Arrays.toString(rep));
    }

- Alice September 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Since "3" is fixed and small, using a 3 element array should be perfect.

- bigphatkdawg September 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Can you detail your solution? How will a 3 element array suffice, there can be n different elements rite?

- Anonymonk September 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@guptasunny158,,,, this is subbu2637 here,,I read ur comment..

Why u r making so discomfort to urself and to others by writting a whole code with some difficulties..

here look at this.According to ques..
1)tak 1 array ; int a[]={2,1,3,1,8,8,7,6,8,1,2,5,4,1,9,1,2,2,1,8,8,8,8}
2)tak 2 loops i and j fr iterating(traversing) purpose in array.[[[[it s also done wth one loop.fr better understaning i used 2 loops...]]]]
3)get the count of each element of array
4)declare the 3 elements whose and all are havng TOP(MORE) COUNT..

CODE:
int a[]={2,1,3,1,8,8,7,6,8,1,2,5,4,1,9,1,2,2,1,8,8,8,8};
n=a[].length-1;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])//checking for duplicates in array
{
count++;
} //tat s it u r done..
if(count>maxcount) //checking for maxcount..
{
count=maxcount;
}
//do ths fr all elements count..get the most three repeating elements in array..

OUTPUT:
ELEMENT 8=7 counts
ELEMENT 1=6 counts
ELEMENT 2=4 counts.
All other elements other than this are havng count 1(check the count of elements once again in array ,,because i fastly typed and counted all of ths..Sry for any errs.But the concept is fine.If anyone encounter any prob reg this ..feel easy to contact me and reply the post...Sry for err OR COMMENT ME IS THS REALLY USEFUL....

- subbu2637 September 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Since you only need the top 3 entries in the HashMap you dont need to sort the whole hashmap. Just iterate thorough the whole set of keys and keep track of the topmost 3 counts. This will reduce the average complexity from O(nlogn) to O(n).

- Anonymous September 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Sorry, I meant with my earlier comment:
* 3 element array for the final sweep of the count-hashTable.

What I meant was, no need for any fancy data structures or algorithms to get the top three frequencies in the final sweep. Some people might try to do a sort or take the counts and put it in a max-heap and then extract-max 3 times or some other priority queue-ing at the end.

- bigphatkdawg September 23, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Anonymous
"This will reduce the average complexity from O(nlogn) to O(n)"

I'd try to express O-notation in terms of the worst case.

I express operations on original list in terms of n, and operations in HashMap in terms of m.

Under the scenario of a really big list (10+ millions) where all numbers are different.

If I use sort, I'd have O(n log m), but since all numbers are different, then n = m, so I'd have O(n log n).

On the other hand, if I keep track of the top three, I'd need to iterate HashMap and compare with top three each time, and in the worst case, let's suppose we always compare each item with all three, so I'd have O(n + m*k) where k is the number of items I want to keep track, then because of n = m, we have O (n + n*k).

If I want to keep track of all numbers =) ... (remember we want the worst case), so it'll be O(n + n^2) which reduces to O(n^2).

In a summary, we have O(n log n) vs O(n^2).

In the worst case, it's better to use sort. Maybe in the average (or realistic case), it's better keep track of top 3.

I'm just starting with Algorithms Analysis and I will really appreciate if somebody with more experience give a though about what I just said. Am I drunk? =)

- Anonymous September 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use a min heap and throw the first 3 elements into it. From then on, compare the next element with the root. If its greater, replace the root with it and call heapify on the new root

- Confused September 23, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Why not using Priority queues with MAX HEAP,,insert the element in PQ if new,,else increment the count+ Heapify !! that's it!!Does everything in O(n),,+ its an Online Method ..

- Dale Steyn September 23, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

package com.techighost.card;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class FindWordCount {

	public static void main(String[] args) {
		int[] inputArray = { 3, 8, 2, 4, 6, 65, 34, 3, 8, 4, 98, 23, 54, 3, 8,
				65, 3 };
		int[] output = new FindWordCount()
				.findThreeMaxRepetitiveWords(inputArray);
		for (int i = 0; i < output.length; i++) {
			System.out.println(output[i]);
		}

	}

	public int[] findThreeMaxRepetitiveWords(int[] inputArray) {
		int[] ouput = new int[3];
		Map<Integer, Integer> numberFrqMap = new HashMap<Integer, Integer>();
		for (int i = 0; i < inputArray.length; i++) {
			if (numberFrqMap.containsKey(inputArray[i])) {
				int count = numberFrqMap.get(inputArray[i]);
				numberFrqMap.put(inputArray[i], ++count);
			} else {
				numberFrqMap.put(inputArray[i], 1);
			}
		}

		Set<Map.Entry<Integer, Integer>> set = numberFrqMap.entrySet();
		Iterator<Map.Entry<Integer, Integer>> iterator = set.iterator();
		List<Map.Entry<Integer, Integer>> entries = new ArrayList<Map.Entry<Integer, Integer>>();
		while (iterator.hasNext()) {
			Map.Entry<java.lang.Integer, java.lang.Integer> entry = (Map.Entry<java.lang.Integer, java.lang.Integer>) iterator
					.next();
			entry.getKey();
			entries.add(entry);
		}
		Collections.sort(entries, new ValueComparator());
		int k = 0;
		for (Entry<Integer, Integer> entry : entries) {
			ouput[k] = entry.getKey();
			if (k == 2) {
				break;
			}
			k++;
		}
		return ouput;
	}

	class ValueComparator implements Comparator<Map.Entry<Integer, Integer>> {
		@Override
		public int compare(Entry<Integer, Integer> o1,
				Entry<Integer, Integer> o2) {
			return o2.getValue() - o1.getValue();
		}
	}
}

- guptasunny158 September 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The code above I have written to solve this problem, Anybody with a better solution than this..Or Anybody help me improving my code.

- guptasunny158 September 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

sort is not a good idea. for 3 biggest number you do not need to sort all elements!

- ehsan September 22, 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