- Use two loops will take
O(n ^ 2)
time
- Use sorting and binary search will take
O(nlog n)
time
- Use sorting and merging
O(nlog n)
time
- Use hashing will take
O(k * n)
time with some other overhead and additional space.
- 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.