How to find the time complexity?

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

Was this solution helpful to you?

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:

Just Added Q & A:

Find solution

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.