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 you can do to improve complexity is to use e.g., the Boyer-More algorithm to intelligently skip comparing logical parts of the string which cannot match the pattern.

Answer from Johan Sjöberg on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
July 21, 2026 - Java™ Platform Standard Ed. 8 ... The String class represents character strings.
🌐
W3Schools
w3schools.com › java › ref_string_indexof.asp
Java String indexOf() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A · ❮ String Methods · Search a string for the first occurrence of "planet": String myStr = "Hello planet earth, you are a great planet."; System.out.println(myStr.indexOf("planet")); Try it Yourself » ·
Discussions

algorithm - java indexof(String str) method complexity - Stack Overflow
Possible Duplicate: What is the cost / complexity of a String.indexof() function call What is the complexity of java indexof(String str) method. I mean there are String matching algorithms lik... More on stackoverflow.com
🌐 stackoverflow.com
java - indexOf to find all occurrences of a word in a String - Stack Overflow
I'm trying to use indexOf to find all occurrences of the characters 'the' in a sentence. For example, if the sentence were "The other day I went over there", it should return 3. I am able to do t... More on stackoverflow.com
🌐 stackoverflow.com
java - How to use substring and indexOf for a String with repeating characters? - Stack Overflow
You can use other version of String#indexOf(String str, int fromIndex) to specify from what position you would like to start searching ")". More on stackoverflow.com
🌐 stackoverflow.com
Java String.indexOf and empty Strings - Stack Overflow
I'm curious why the String.indexOf is returning a 0 (instead of -1) when asking for the index of an empty string within a string. The Javadocs only say this method returns the index in this string... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-indexof
Java String indexOf() Method - GeeksforGeeks
November 19, 2024 - In Java, the String indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.
🌐
CodingBat
codingbat.com › doc › java-string-indexof-parsing.html
Java String indexOf Parsing
int indexOf(String target, int fromIndex) -- searches left-to-right for the target as usual, but starts the search at the given fromIndex. The fromIndex does not actually need to be valid. If it is negative, the search happens from the start of the string.
🌐
CodeGym
codegym.cc › java blog › strings in java › java string indexof()
Java String indexOf()
December 26, 2024 - Position of 'programming' in the string is: 18 In the above code, we first declared a string "Java is a popular programming language" and then used the indexOf() method to find the position of the substring "programming" in the string.
🌐
Codecademy
codecademy.com › docs › java › strings › .indexof()
Java | Strings | .indexOf() | Codecademy
May 13, 2022 - Returns the zero-indexed position of the first occurrence of the given character(s) in a string.
Find elsewhere
Top answer
1 of 2
46

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 you can do to improve complexity is to use e.g., the Boyer-More algorithm to intelligently skip comparing logical parts of the string which cannot match the pattern.

2 of 2
26

java indexOf function complexity is O(n*m) where n is length of the text and m is a length of pattern
here is indexOf original code

   /**
     * Returns the index within this string of the first occurrence of the
     * specified substring. The integer returned is the smallest value
     * <i>k</i> such that:
     * <blockquote><pre>
     * this.startsWith(str, <i>k</i>)
     * </pre></blockquote>
     * is <code>true</code>.
     *
     * @param   str   any string.
     * @return  if the string argument occurs as a substring within this
     *          object, then the index of the first character of the first
     *          such substring is returned; if it does not occur as a
     *          substring, <code>-1</code> is returned.
     */
    public int indexOf(String str) {
    return indexOf(str, 0);
    }

    /**
     * Returns the index within this string of the first occurrence of the
     * specified substring, starting at the specified index.  The integer
     * returned is the smallest value <tt>k</tt> for which:
     * <blockquote><pre>
     *     k &gt;= Math.min(fromIndex, this.length()) && this.startsWith(str, k)
     * </pre></blockquote>
     * If no such value of <i>k</i> exists, then -1 is returned.
     *
     * @param   str         the substring for which to search.
     * @param   fromIndex   the index from which to start the search.
     * @return  the index within this string of the first occurrence of the
     *          specified substring, starting at the specified index.
     */
    public int indexOf(String str, int fromIndex) {
        return indexOf(value, offset, count,
                       str.value, str.offset, str.count, fromIndex);
    }

    /**
     * Code shared by String and StringBuffer to do searches. The
     * source is the character array being searched, and the target
     * is the string being searched for.
     *
     * @param   source       the characters being searched.
     * @param   sourceOffset offset of the source string.
     * @param   sourceCount  count of the source string.
     * @param   target       the characters being searched for.
     * @param   targetOffset offset of the target string.
     * @param   targetCount  count of the target string.
     * @param   fromIndex    the index to begin searching from.
     */
    static int indexOf(char[] source, int sourceOffset, int sourceCount,
                       char[] target, int targetOffset, int targetCount,
                       int fromIndex) {
    if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
    }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
    if (targetCount == 0) {
        return fromIndex;
    }

        char first  = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j] ==
                         target[k]; j++, k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

you can simply implements the KMP algorithm without using of indexOf Like this

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;


public class Main{
    int failure[];
    int i,j;
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out=new PrintWriter(System.out);
    String pat="",str="";
    public Main(){
            try{

            int patLength=Integer.parseInt(in.readLine());
            pat=in.readLine();
            str=in.readLine();
            fillFailure(pat,patLength);
            match(str,pat,str.length(),patLength);
            out.println();
            failure=null;}catch(Exception e){}

        out.flush();
    }
    public void fillFailure(String pat,int patLen){
        failure=new int[patLen];
        failure[0]=-1;
        for(i=1;i<patLen;i++){
            j=failure[i-1];
            while(j>=0&&pat.charAt(j+1)!=pat.charAt(i))
                j=failure[j];
            if(pat.charAt(j+1)==pat.charAt(i))
                failure[i]=j+1;
            else
                failure[i]=-1;
        }
    }
    public void match(String str,String pat,int strLen,int patLen){
        i=0;
        j=0;
        while(i<strLen){
            if(str.charAt(i)==pat.charAt(j)){
                i++;
                j++;
                if(j==patLen){
                    out.println(i-j);
                    j=failure[j-1]+1;
                }
            } else if (j==0){
                    i++;
            }else{
                j=failure[j-1]+1;
            }

        }
    }
    public static void main(String[] args) {
        new Main();
    }
}
🌐
FavTutor
favtutor.com › blogs › java-indexof
indexOf Method in Java (with Examples)
November 18, 2023 - The indexOf() method is a member of the String class in Java and is used to find the position of the first occurrence of a specified character or substring within a given string. It returns the index as an integer value, which represents the ...
🌐
freeCodeCamp
freecodecamp.org › news › indexof-in-java-how-to-find-the-index-of-a-string-in-java
indexOf in Java – How to Find the Index of a String in Java
March 24, 2022 - A string is a collection of characters nested in double quotes. The indexOf method returns the index position of a specified character or substring in a string. In this article, we'll see the syntax for the different indexOf methods.
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-indexof-method-example
Java String indexOf() Method
July 1, 2024 - public class StringIndexOfExample { public static void main(String[] args) { String str = "Hello, world!"; // Find the index of a character int index1 = str.indexOf('o'); System.out.println("Index of 'o': " + index1); // Output: 4 // Find the index of a character starting from the given index int index2 = str.indexOf('o', 5); System.out.println("Index of 'o' from position 5: " + index2); // Output: 8 // Find the index of a substring int index3 = str.indexOf("world"); System.out.println("Index of \"world\": " + index3); // Output: 7 // Find the index of a substring starting from the given index int index4 = str.indexOf("world", 8); System.out.println("Index of \"world\" from position 8: " + index4); // Output: -1 } }
🌐
Netjstech
netjstech.com › 2016 › 07 › searching-string-indexof-lastindexof-contains-java.html
Java String Search Using indexOf(), lastIndexOf() And contains() Methods | Tech Tutorials
String class in Java provides accessor ... and lastIndexOf(). indexOf()- This method searches forward from the beginning of the string and returns the index within this string of the first occurrence of the specified character/substring....
🌐
Studyopedia
studyopedia.com › home › string indexof (int ch, int fromindex) method in java
String indexOf (int ch, int fromIndex) method in Java - Studyopedia
August 19, 2020 - The indexOf (int ch, int fromIndex) method in Java returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › lang › String.html
String (Java SE 17 & JDK 17)
April 21, 2026 - The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
🌐
NAIS
nais.org
NAIS - Home
Join us March 3-5 in Baltimore at the premier event for independent school leaders. Gain critical insights, innovative strategies, and valuable connections to help you and your school thrive · Explore resources, events, and more to help you lead and manage your school with confidence and ...
🌐
Oracle
forums.oracle.com › ords › apexds › post › searching-a-string-with-indexof-3006
searching a string with indexOf( - Oracle Forums
May 5, 2007 - I have a string of text that I'm trying to locate the periods, so I do string.indexOf("."); to get the index value. It returns to correct position when the text looks like this: The cat is ...
🌐
BLACK+DECKER
blackanddecker.com
Tools, Outdoor Equipment and Home Products | BLACK+DECKER®
20V MAX* POWERCONNECT™ Cordless 12 Inch String Trimmer and Edger, Battery and Charger Included
🌐
CodingBat
codingbat.com › java
CodingBat Java
Java String indexOf and Parsing · Java If and Boolean Logic · If Boolean Logic Example Solution Code 1 (video) If Boolean Logic Example Solution Code 2 (video) Java For and While Loops · Java Arrays and Loops · Java Map Introduction · Java Map WordCount ·