Interview Question
Country: United States
public static void countFrequencies(int[] arr){
Map<Integer,Integer> frequencies = new HashMap<>();
for (int n :arr){
if(frequencies.get(n) !=null) frequencies.put(n,frequencies.get(n)+1);
else frequencies.put(n,1);
}
for (int n : frequencies.keySet()) System.out.println(n+" ->"+ frequencies.get(n));
}
#include <stdio.h>
#define MAXSIZE 5
int main(int argc, char *argv[]) {
int array[MAXSIZE],i=0 , result[MAXSIZE], k=0,j,count=0,iterator=0;
result[MAXSIZE-1]=0;
printf("Enter the array elements in ascending order\n");
for ( i =0; i<=MAXSIZE-1;i++)
scanf ("%d",&array[i]);
printf("You entered \n");
for ( i =0; i<=MAXSIZE-1;i++)
printf("%d\t",array[i]);
printf("\n");
for ( i =0; i<=MAXSIZE-1;i++)
result[i]= 1;
for( i= 0; i<=MAXSIZE-1;){
//for( j= i+1; j<=MAXSIZE-1;){
j = i+1;
count =0;
iterator =0;
if( array[i]==array[j]){
while((array[i]==array[j]) && (j <= MAXSIZE-1)){
result[k]++;
j++;
count++;
//j++;
}
i = i+j+1;
while ( iterator < count){
k++;
result[k] = result[k-1];
iterator++;
}
}
else{
i++;
k++;
//j++;
}
//}
}
for ( i =0; i<=MAXSIZE-1;i++)
printf("%d\t",result[i]);
}
public static void countFrequencies(int[] array){
HashMap<Integer, Integer> frequencies = new HashMap<>();
for(int num : array){
if(!frequencies.containsKey(num)){
frequencies.put(num, 1);
}
else{
frequencies.put(num, frequencies.get(num) + 1);
}
}
for(int num: frequencies.keySet()){
System.out.println("Number: " + num + " Frequency: " + frequencies.get(num));
}
}
#!/usr/bin/env python3
class Frequency(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return 0
def solution(array):
frequency = Frequency()
for element in array:
frequency[element] += 1
return frequency
frequency = solution([1, 1, 7, 2, 1, 2, 9])
assert frequency[0] == 0
assert frequency[1] == 3
assert frequency[2] == 2
assert frequency[7] == 1
assert frequency[9] == 1
using hashtable.
- zr.roman January 05, 2016