Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cost / complexity of a String.indexOf() function call

Tags:

java

string

What is the cost / complexity of a String.indexOf() function call?

like image 581
Jim Avatar asked Aug 25 '10 04:08

Jim


People also ask

What is the time complexity of string indexOf?

indexOf() – also runs in linear time. It iterates through the internal array and checks each element one by one, so the time complexity for this operation always requires O(n) time.

What is the complexity of indexOf in Java?

The complexity of Java's implementation of indexOf is O(m*n) where n and m are the length of the search string and pattern respectively.

What does the indexOf () function do?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

What is the time complexity of string contains method Java?

. contains() definitely uses naive approach and equivalent to O(nm) time complexity.


1 Answers

IIRC Java's implementation of .indexOf() is just the naive string matching algorithm, which is O(n+m) average and O(n*m) worst case.

In practice this is fast enough; I tested it for relatively large needle (>500 char) and haystack (few MB) strings and it would do the matching in under a second (in an average household computer). Mind you I forced it to go through the whole haystack.

like image 92
NullUserException Avatar answered Oct 21 '22 05:10

NullUserException