I was recently asked this question in an interview:
There are two arrays of size ‘n’ each. One array has nuts, the other one has bolts. Each nut fits exactly one bolt and vice-versa. When you compare a nut with a bolt, you get one of the 3 results: tight,loose,fits.
How do you efficiently find the unique mapping?
Sorting is not possible on either of the sets. You never know if b1 is smaller than b2 or
n1 is smaller than n2. Where n1,n2 are nuts and b1,b2 are bolts. Only thing you can do is compare a nut with a bolt and get a result: tight,fits,loose.
The quicksort like algorithm does the job:
nand use it as pivot to partition the set of boltsBinto three sets: tight (B1), loose (B2), fits.b. Now you use this bolt as pivot to partition the nuts setN\ninto two set: tight (N1) or loose (N2).N1andB1,nandb,N2andB2. All of them are of the same size. You can do the same partitioning recursively on (N1,B2) and (N2,B1) and you can get the final answer.It is obvious the complexity is
O(N log N), the same as quicksort.