Reputation: 444
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 ?
Upvotes: 1
Views: 233
Reputation: 15875
O(n ^ 2)
timeO(nlog n)
timeO(nlog n)
timeO(k * n)
time with some other overhead and additional space.O(n ^ 2)
time as its use native algorithm under the hoodYou 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.
Upvotes: 3