How do I find the lowest common duplicate in two large integer arrays with minimum time complexity?
-
-
Answer:
This can be done in O(n) time and space: - iterate over the first array, inserting each integer as a key in a hashset. - iterate over the second array, and for each value in the array that is in our hashset, add it to a list (of integers in both arrays). - find the min of the list by iterating over it once. It is impossible to do better because the input is of size O(n) and has no structure (e.g. ordering gaurantees) - so every integer in the input must be processed, which will take at least O(n) time.
David Goldstein at Quora Visit the source
Other answers
Just adding an optimization to David's answer. 1) Iterate over the first array "a" and put all the elements in an hash set "s" 2) Now iterate over the 2nd array "b", maintain a commonMin, if the element is found in "s", then compare it with commonMin , if its less than commonMin , then set that element as commonMin. Set<Integer> s = new HashSet<Integer>(); for (int i=0; i<a.length; i++) { s.add(a[i]); } int commonMin = Integer.MAX_INTEGER; for (int i=0; i<b.length; i++) { if (s.contains(b[i])) { if (b[i] < commonMin){ commonMin = b[i]; } } } return commonMin;
Sourabh Bansod
Related Q & A:
- How can I find the minimum number of open rectangles in a grid?Best solution by Stack Overflow
- How can I find out the time of sunrise?Best solution by Yahoo! Answers
- How can I find out how many points i have on my license?Best solution by Yahoo! Answers
- How do I find great shopping in Providence R.I?Best solution by downtownprovidence.com
- How can I send a message to all my friends on facebook at the same time?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.