Bloomberg LP Interview Question
Software Engineer / DevelopersIf someone could explain, Hows does the Hashtable / Hashset method work in O(n)?
Is this the correct implementation for that?
import java.util.*;
public class hash
{
public static void main( String[] args )
{
HashSet<String> set1 = new HashSet<String>();
set1.add( "ape" );
set1.add( "cat" );
set1.add( "bat" );
HashSet<String> set2 = new HashSet<String>();
set2.add( "bat" );
set2.add( "fox" );
set2.add( "ape" );
System.out.println( "1 = " + set1 + ", 2 = " + set2 );
set1.retainAll(set2); //Keep entries which exist in both
System.out.println( "Intersection = " + set1);
}
}
Why not use the generic algorithms for set in STL?
- STL Answer February 21, 2008const int SET_SZ = 12;
const int iArray1 [12] = { 100, 150, 200, 250, 225, 300,
325, 125, 400, 175, 600, 50 };
const int iArray2 [12] = { 275, 300, 325, 350, 375, 400,
75, 25, 450, 575, 600, 550 };
set<int> s1( iArray1, iArray1 + SET_SZ );
set<int> s2( iArray2, iArray2 + SET_SZ );
set<int> sr;
cout << "Computed intersection: " << endl;
set_intersection( s1.begin(), s1.end(),
s2.begin(), s2.end(),
ostream_iterator<int>(cout, ",") );
cout << endl << "Computed Union: " << endl;
set_union( s1.begin(), s1.end(),
s2.begin(), s2.end(),
ostream_iterator<int>(cout, ",") );
cout << endl << "Computed Difference: " << endl;
set_difference( s1.begin(), s1.end(),
s2.begin(), s2.end(),
ostream_iterator<int>(cout, ",") );