Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Can it not be fixed by using simple hash map?
Start traversing from 0...to ...n elements and store the numbers in the hash map.Once you find the same element again just increment your count in the hashmap and do this step for all the elements.In the end just check the hasp map whose count matches the n/k.
Simple example:
hash[1]-count 1 input array[1]
hash[2]-count 1 input array[2]
hash[3]-count 1 input array[3]
hash[4]-count 1 input array[4]
hash[2]-count 2 input array[2]
In the end just scan the hash map looking for count == n/k
here is the algo for this....
1:Sort the array.
2:initialize iCounter = 0, Value = 0;
3:for i = 0 to n-1 ( to traverse all the elements)
if (value == SortedArray[i])
{
iCounter++;
}
else
{
if( iCounter >= n/k )
{
store the variable & counter value....
increase Total number of variables by one.....(At the top of loop, you should initialize by zero)
}
iCounter = 0;
value = SortedArray[i];
}
4:Print all the variables with occurs atleast n/k time.
here is the algo for this....
1:Sort the array.
2:initialize iCounter = 0, Value = 0;
3:for i = 0 to n-1 ( to traverse all the elements)
if (value == SortedArray[i])
{
iCounter++;
}
else
{
if( iCounter >= n/k )
{
store the variable & counter value....
increase Total number of variables by one.....(At the top of loop, you should initialize by zero)
}
iCounter = 0;
value = SortedArray[i];
}
4:Print all the variables with occurs atleast n/k time.
If we solve it using HashMap space complexity is O(n) and time complexity is O(n). If we don't use extra memory, Sort the array and linear traversal through the array to find the number. O(nLogn). Are there any other techniques which can allow the problem is solved in less than O(nLogn) without using extra space.
//n is the length, k is any number is array a, max is the max integer number in array a[]
int findNKtimesNumber(int a[], int k, int max, int n)
{
int *temp=NULL;
temp = (int *)malloc(sizeof(int)*(max+1));
memset(temp, 0, sizeof(int)*(max+1));
int i;
int rtimes = n/k;
for(i=0; i<n; i++)
{
temp[a[i]] = temp[a[i]] + 1;
}
for(i=1; i<=max; i++)
{
if(temp[i] == rtimes)
printf("%d appears %d times\n\r", i, rtimes);
}
}
Say if k = 3, then find elements that appear n/3 times in the array which means 1/3 of the size of the array. e.g 1,1,1,2,2,3,4,4,4,4,6,7 . So here 12 elements are there and 4 appears 4 times and that is what you need to print
- sowmya October 25, 2012