This was one of the interview questions, and I was wondering if I did it right, and want to know if my solution is the most efficient one. O(n log n)
Given a bag of nuts and a bag of bolts, each having a different size within a bag but exactly one match in the other bag, give a fast algorithm to find all matches.
Since there is always a match between 2 bags, I said there will be same number of nuts and same number of bolts. Let the number be n.
I would first sort components in each bag each component's weight, and it is possible to do that because they all have different size within a bag. Using merge sort, it will have O(n log n) time complexity.
Next, it would be just easy process of matching each component in 2 bags from lightest to heaviest.
I want to know if this is the right solution, and also if there is any other interesting way to solve this problem.
There is a solution to this problem in O(nlgn) that works even if you can't compare two nuts or two bolts directly. That is without using a scale, or if the differences in weight are too small to observe.
It works by applying a small variation of randomised quicksort as follows:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With