1

With reference to the question , I have found out the accepted answer used Java Collections API to get the index. My question is there are so many other methods to solve the given problem, which would be the optimal solution ?

  1. Use two loops
  2. Use sorting and binary search
  3. Use sorting and merging
  4. Use hashing
  5. Use Collections api
1
  • Try it out and benchmark them? Though I'd say the one requiring the least amount of code is often the best one. Commented Mar 25, 2017 at 11:36

1 Answer 1

3
  1. Use two loops will take O(n ^ 2) time
  2. Use sorting and binary search will take O(nlog n) time
  3. Use sorting and merging O(nlog n) time
  4. Use hashing will take O(k * n) time with some other overhead and additional space.
  5. Use Collections api will take O(n ^ 2) time as its use native algorithm under the hood

You can do it in optimal way along with the ways mentioned above by using Knuth–Morris–Pratt algorithm in linear O(n + m) time complexity where n and m are the lengths of the two arrays.

KMP algorithm is basically a pattern matching algorithm(finding the starting position of a needle in haystack) which works on character string. But you can easily use it for integer array.

You can do some benchmark test for all those implementations and choose which one is efficient enough to suit your requirement.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But it seems the given algorithm is for strings. Is it good for integer arrays ?
Yes, instead of comparing character array(string) str1[i] == str2[j] it will compare integer array arr1[i] == arr2[j]. Comparing character of string will compare one byte and for integer its four bytes. Nothing different than this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.