HCL Interview Question
Java DevelopersCountry: India
Interview Type: In-Person
Get keys from hash_table_1.
Get keys from hash_table_2.
Get keys from hash_table_3.
Create hash_table_4 with chaining.
For each keys in hash_table_1:
value = hash_table_1[key]
hash_table_4[val]
For each keys in hash_table_2:
value = hash_table_2[key]
hash_table_4[val] = 2
For each keys in hash_table_3:
value = hash_table_3[key]
hash_table_4[val] = 3
Get keys from hash_table_4:
count = 0
while hash_table_4[key].pop != NULL
count++
if count == 3
print Common value! Print value here.
count = 0
here's the algorithm:
----
For each key in Hashtable1 do following
Insert in Hashtable4
// now hashtable is same as hashtable1
For each key in Hashtable4 do following
if key is not present in Hashtable2 Delete key from hashtable4
// now you have elements in hashtable4 which are common in hashtable1 and 2
For each key in Hashtable4 do following
if key is not present in Hashtable3 Delete key from hashtable4
// now you have elements in hashtable4 which are common in hashtable1, hashtable2 and hashtable3.
public Hashtable<Integer,Integer> commonHashTable(Hashtable<Integer,Integer> t1, Hashtable<Integer,Integer> t2 , Hashtable<Integer,Integer> t3){
Hashtable<Integer,Integer> t4 = new Hashtable<Integer,Integer>(t1);
Set<Integer> s = t4.keySet();
Iterator<Integer> itr = s.iterator();
while(itr.hasNext()){
Integer t = itr.next();
if(!t2.containsKey(t) || !t3.containsKey(t))
itr.remove();
}
return t4;
}
This requirement looks like to have the intersection for three hash table. Use Java Set can get it.
public static Set<Integer> threeSetIntersection(Set<Integer> set1, Set<Integer> set2, Set<Integer> set3) {
Set<Integer> tempSet1 = new HashSet<Integer>(set1);
Set<Integer> tempSet2 = new HashSet<Integer>(set1);
tempSet1.retainAll(set2);
tempSet2.retainAll(set3);
tempSet1.retainAll(tempSet2);
return tempSet1;
}
1. Find the first two smallest of the three tables.
2. Search the elements of the smallest table in the smaller table of the two and save the common values between the two -> O(Size_Of_Smallest_array)
3. Search the saved values in the largest table and print those that are found in this last table -> O(Size_Of_Array_Common_Between_Two_Smallest_Tables).
How are hash tables compared. Is it values with the same keys or what?
- DashDash May 19, 2013