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
🌐
LeetCode
leetcode.com › discuss › interview-question › 5498326 › Java-Time-Complexities-of-All-Built-in-Methods-(String-StringBuilder-List-Set-Map-Queue-Stack)
Java Time Complexities of All Built-in Methods (String, StringBuilder, List, Set, Map, Queue, Stack) - Discuss - LeetCode
July 18, 2024 - Worst-case time complexities of all Java built-in methods including String, StringBuilder, List classes, Set classes, Map classes, Queue classes, Stack, Arrays, and Collections classes: String · new String("str") instantiation with value -> O(n) "str1" + "str2" concatenation -> O(n), better solution is String concat(String str) with O(n) int length() -> O(1) char charAt(int index) -> O(1) int indexOf(int ch), int indexOf(int ch, int fromIndex), int indexOf(String str), int indexOf(String str, int fromIndex), int lastIndexOf(int ch), int lastIndexOf(int ch, int fromIndex), int lastIndexOf(Stri
🌐
GitHub
github.com › rootusercop › TimeComplexityOfPredefinedMethodsInJava › blob › master › String, StringBuilder and StringBuffer class methods
TimeComplexityOfPredefinedMethodsInJava/String, StringBuilder and StringBuffer class methods at master · rootusercop/TimeComplexityOfPredefinedMethodsInJava
The complexity of Java's implementation of indexOf is O(m*n) where n and m are the length of the search string ... What you can do to improve complexity is to use e.g., the Boyer-More algorithm to intelligently skip comparing · logical parts ...
Author   rootusercop
Discussions

java - Why StringBuilder.append time complexity is O(1) - Stack Overflow
By amortized analysis, we know that N insertions with StringBuilder#append method take O(N) time. But here is where I get lost. Consider this where inputString is an input string from a user. for ... More on stackoverflow.com
🌐 stackoverflow.com
java - What is the cost / complexity of a String.indexOf() function call - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
August 25, 2010
string - What is the time complexity of Java StringBuilder.substring() method? If it is linear, is there a constant time complexity method to get a substring? - Stack Overflow
If this is true, how can I get a substring within a constant time complexity? ... You cannot possibly create a String from a StringBuilder in constant time and have its immutability maintained. More on stackoverflow.com
🌐 stackoverflow.com
Appending character at the front in the StringBuilder

just do a .reverse on the sb.toString() at the end.. surely that's 10x more readable

More on reddit.com
🌐 r/javahelp
5
3
October 14, 2016
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();
    }
}
🌐
GitHub
github.com › bhatia-di › Cracking_The_Coding_Interview › blob › 4d4bb4db024a991bd78a2187b6f59202c8877db6 › StringBuilder_TimeComplexity.md
Cracking_The_Coding_Interview/StringBuilder_TimeComplexity.md at 4d4bb4db024a991bd78a2187b6f59202c8877db6 · bhatia-di/Cracking_The_Coding_Interview
indexOf · O(m*n) where n and m are the length of the search string and pattern respectively. charAt · O(1) deleteCharAt · O(N) cause if a random character is deleted, it ll shift the characters by that 1 space and the best case scenario is deleteing the last character that would be O(1) equals ·
Author   bhatia-di
Top answer
1 of 3
25

Should this have time complexity of O(inputString.length * N) since append() copies the input string to the end of the StringBuilder N times?

Yes.

Why do we consider that append() takes O(1) time complexity whereas it should be considered as O(inputString.length)?

It is O(1) when appending single characters. A StringBuilder is like an ArrayList. When you append a single item the cost is O(1). Appending a string is like calling addAll()--the cost is proportional to the length of the string / the number of items being added.

It appears you understand everything correctly. The problem is people are often sloppy when discussing Big-O performance. It's endemic.

2 of 3
0

I guess we are talking about appending single characters. Appending a string of length N would have an O(N).

Answer: Because with increasing length, copying becomes less frequent by the same factor by which it becomes more expensive.

Let's assume the capacity doubles when full. Doesn't matter, could be a factor of 1.1, 3, or whatever, but it's easier to talk about.

Doubling 1 needs to copy 1000 chars, which on average over these first 1000 means 1 char to copy per char appended.

Doubling 2 needs to copy 2000 chars, which on average over the past 1000 after the first copy means 2 chars to copy per char appended.

Doubling 3 needs to copy 4000 chars, which on average over the past 2000 means 2 chars to copy per char appended.

Doubling 4 needs to copy 8000 chars, which on average over the past 4000 means 2 chars to copy per char appended.

&c.

So before the first doubling, it's free, then you pay half the price, and the the price settles at 2 chars per char appended on average.

🌐
DEV Community
dev.to › taosif7 › optimise-your-string-algorithms-in-java-17ef
Optimise your String Algorithms in Java - DEV Community
September 10, 2022 - Example: Lets say you concatenate "abc + "def" Under the hood, Java is performing these operations: • Construct copy of "abc" with additional length; • Copy "d" to new array • Construct copy of "abcd" • Copy "e" to new array • Construct copy of "abcde" • Copy "f" to new array So O(m) called n times, thus time complexity is O(mn) Use StringBuilder with .append() method, It creates internal buffer that expands only on demand.
Find elsewhere
🌐
Utkarsh1504
utkarsh1504.github.io › DSA-Java › string-builder
StringBuilder in Java – Strings In Depth – Data Structures & Algorithms
public class SB { public static void main(String[] args) { StringBuilder builder=new StringBuilder(); for(int i = 0;i<26;i++){ char ch=(char) ('a'+i); builder.append(ch); } System.out.println(builder.toString()); } } This is a simple code which demonstrates the use of String Builder class to print all alphabets from a-z, and to show how efficient it is in space and time complexity.
🌐
Stackademic
blog.stackademic.com › optimise-your-string-algorithms-in-java-ce88b8152311
Optimise your String Algorithms in Java | by Taosif Jamal | Stackademic
November 6, 2024 - Its time complexity is almost O(m+n). String.concat is another approach, but slower than StringBuilder.
🌐
Medium
firattonak.medium.com › oop-and-c-string-and-stringbuilder-with-leetcode-questions-2eec3a3a7572
String vs. StringBuilder: Analyzing Performance with a LeetCode Question in C# | by Firat Tonak | Medium
January 9, 2024 - The use of StringBuilder in C# allows for more efficient handling of string operations, as it avoids the costly process of creating new string instances for every modification, which is the case with immutable strings. As a result, StringBuilder significantly reduces the time complexity and improves performance, particularly in algorithmic and computation-heavy applications.
🌐
Baeldung
baeldung.com › home › java › java string › string performance hints
String Performance Hints | Baeldung
March 7, 2025 - Taking into account that resizing doesn’t occur very often, we can consider each append() operation as O(1) constant time. Taking this into account, the whole process has O(n) complexity...
🌐
Scribd
scribd.com › document › 865406729 › AAPS-Assignmentpdfsa
StringBuilder Time Complexity Explained | PDF | Time Complexity | String (Computer Science)
Types: 1. Singly Linked List – each node points to the next node only 2. Doubly Linked List – each node points to both the next and previous nodes 3. Circular Linked List – the last node links back to the first node Operation Time Complexity · Search O(n) 31. Use a deque to find the maximum in every sliding window of size K. Write its algorithm, program. Find its time and space complexities.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › fundamentals › runtime-libraries › system-text-stringbuilder
StringBuilder Class (System.Text) | Microsoft Learn
January 8, 2024 - Imports System.Text Module Example8 Public Sub Main() Dim value As String = "An ordinary string" Dim index As Integer = value.IndexOf("An ") + 3 Dim capacity As Integer = &HFFFF ' Instantiate a StringBuilder from a string. Dim sb1 As New StringBuilder(value) ShowSBInfo(sb1) ' Instantiate a StringBuilder from string and define a capacity.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › StringBuilder.html
StringBuilder (Java Platform SE 8 )
April 21, 2026 - public StringBuilder insert(int index, char[] str, int offset, int len)
🌐
DEV Community
dev.to › asswin_07 › string-builder-2dja
String Builder - DEV Community
December 26, 2021 - So inside the main function, we create a StringBuilder using "new" keyword, just like how we use to create for Strings. Now inside the for loop we take ASCII value of a and add it to the iterating variable i and finally typecast the ASCII value to a character and assign it to ch . * In next step we add( append ) each character to the builder and finally print it after converting them to String format by calling toString() Method. 1.Now if we analyze the Time Complexity of using Strings for the above example: