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.

Answer from John Kugelman on Stack Overflow
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.

Discussions

StringBuilder and Kotlin - Kotlin Discussions
I check some string concatenation bytecode outputs today and it looks like kotlin's internal handling of string concat is really nice, even better than explicitly using a StringBuilder with append calls. https://gist.github.com/jrenner/e074d009614df27fd950 Is it fair to say StringBuilder is ... More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
2
October 13, 2014
java - Space complexity of the "add two binary strings" challenge - Code Review Stack Exchange
I am trying to analyze its time and space complexity. While I was satisfied with its time complexity which is \$O(n)\$, I am not really sure about the space. I think the space complexity is \$O(n)\$ as well but I might be wrong because of the StringBuilder usage here. More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
January 31, 2018
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
Why Is StringBuilder O(n) In Java?
StringBuilder extends AbstractStringBuilder , which (at least in that implementation) uses an array of characters to store its data. If the storage size isn't big enough, it calls Arrays.copyOf to expand it, and that's an O(n) operation. It might be an interesting alternative implementation to have a list of partial strings, and then only concatenate them together when the final string is requested. That would make a lot of the other methods much more difficult to implement, however. More on reddit.com
🌐 r/learnprogramming
11
1
October 15, 2018
🌐
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 - This is because adding a character to a StringBuilder instance has a time complexity of O(1), making it significantly more efficient for iterative string manipulations.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › StringBuilder.html
StringBuilder (Java Platform SE 8 )
April 21, 2026 - The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder.
🌐
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.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › fundamentals › runtime-libraries › system-text-stringbuilder
StringBuilder Class (System.Text) | Microsoft Learn
January 8, 2024 - For routines that perform extensive string manipulation (such as apps that modify a string numerous times in a loop), modifying a string repeatedly can exert a significant performance penalty. The alternative is to use StringBuilder, which is a mutable string class. Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters.
Find elsewhere
🌐
Scribd
scribd.com › document › 879672319 › TCS-Compilation
StringBuilder Append Complexity | PDF | String (Computer Science) | Applied Mathematics
The document contains a list of 43 common programming questions related to arrays and strings, along with Java solutions for each problem. It covers a range of topics including finding minimum and maximum values, reversing arrays, counting frequencies, and string manipulations. Each question is accompanied by its respective time and space complexity analysis.Read more
🌐
GeeksforGeeks
geeksforgeeks.org › java › stringbuilder-class-in-java-with-examples
StringBuilder Class in Java - GeeksforGeeks
Unlike the String class (which is immutable), StringBuilder allows modification of character sequences without creating new objects, making it memory-efficient and faster for frequent string operations.
Published   May 8, 2026
🌐
Kotlin Discussions
discuss.kotlinlang.org › t › stringbuilder-and-kotlin › 441
StringBuilder and Kotlin - Kotlin Discussions
October 13, 2014 - I check some string concatenation bytecode outputs today and it looks like kotlin's internal handling of string concat is really nice, even better than explicitly using a StringBuilder with append calls. https://gist.github.com/jrenner/e074d009614df27fd950 Is it fair to say StringBuilder is ...
🌐
Medium
medium.com › @sharmarishabh417 › string-vs-stringbuilder-in-java-3da019d0a757
String vs StringBuilder in Java. Throughout my college days, I was… | by Sharmarishabh | Medium
July 1, 2024 - Efficient Append Operations: ... insert(), delete(), etc., which modify the internal character array without creating new objects. This reduces memory usage and improves performance. Dynamic Size: StringBuilder manages a dynamic array internally, which grows as needed. It pre-allocates extra space to accommodate future growth, minimizing the need for frequent reallocation and copying. Space Complexity: StringBuilder ...
🌐
Scribd
scribd.com › document › 865406729 › AAPS-Assignmentpdfsa
StringBuilder Time Complexity Explained | PDF | Time Complexity | String (Computer Science)
Time Complexity: O(L), where L is the number of nodes in the list. Space Complexity: O(1) 27. Find the node where two singly linked lists intersect. Write its algorithm, program. Find its time and space complexities. Explain with suitable example.
🌐
CopyProgramming
copyprogramming.com › howto › java-insert-string-at-beginning-of-stringbuilder-java
Java StringBuilder Insert String at Beginning: Complete Guide for 2026
November 10, 2025 - StringBuilder sb = new ... requires shifting all existing characters in the internal buffer one position forward, resulting in O(n) time complexity per insertion....
🌐
Scala Documentation
docs.scala-lang.org › overviews › collections › performance-characteristics.html
Performance Characteristics | Collections (Scala 2.8 - 2.12) | Scala Documentation
This page has a new version · The previous explanations have made it clear that different collection types have different performance characteristics. That’s often the primary reason for picking one collection type over another. You can see the performance characteristics of some common ...
🌐
Google Books
books.google.hu › books
Coding Interviews: Questions, Analysis & Solutions - Harry He - Google Books
This book is about coding interview questions from software and Internet companies. It covers five key factors which determine performance of candidates: (1) the basics of programming languages, data structures and algorithms, (2) approaches to writing code with high quality, (3) tips to solve ...
🌐
BellSoft
bell-sw.com › announcements › 2021 › 06 › 25 › efficient-code-vs-string-concatenation-solve-this-java-snippet
Efficient code vs string concatenation | BellSoft Java
June 25, 2021 - When ‘n’ grows by four times, the code variant where StringBuilder is reused slows down by 3.5x (close to linear), while the variant with re-created StringBuilder slows down by 7.3x. The exact quadratic slowdown would be 16-fold. However, there are additive costs and optimizations for data copying (see StubRoutines::jbyte_disjoint_arraycopy in the OpenJDK code). As an experiment, you can run the benchmarks on your hardware. Try playing with javac and JDKs and compare 7, 8, 11, and 16 bytecode running on JDK 7, 8, 11, and 16. ... The complexity will be quadratic — expressed as a sum of an arithmetic sequence to n terms — and it will be in the same proportion for both the number of operations and memory.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-optimize-string-concatenation-in-java
How to Optimize String Concatenation in Java? - GeeksforGeeks
July 23, 2025 - // Java program to concatenate string import java.lang.*; class GFG { public static void main(String[] args) { StringBuilder str = new StringBuilder(); long startTime = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { str.append(0); } long endTime = System.currentTimeMillis(); System.out.println( "Time taken to concatenate 100000 Strings using StringBuilder append : " + (endTime - startTime) + " ms"); } }
🌐
Saturn Cloud
saturncloud.io › blog › what-is-the-most-efficient-algorithm-for-reversing-a-string-in-java
Saturn Cloud | Saturn Cloud | The Control Plane for GPU Clouds
July 18, 2023 - Every GPU-hour is tagged with the owning user, project, and tenant at creation time. Contract terms, including committed use, on-demand, and reserved, are applied automatically.
Top answer
1 of 2
1

Here's some other points to consider.

Checking for empty string and null seems to be redundant. The compiler treats them the same.

Your check for null, only checks if both are null. For completion it would be better to also check if either is null.

I think it would be more performant to use a char array set to the longest length possible(length of longest string plus 1) and change the value at each index, rather than constantly appending to the StringBuilder.

You aren't checking for malformed strings.

You aren't handling strings of different lengths.

With all these taken into consideration your code could look something like this:

final static char ZERO_CHAR_VALUE = '0';
final static char ONE_CHAR_VALUE = '1';
final static char DEFAULT_CHAR_VALUE = '\0';

public static String AddBinary(String inValA, String inValB) {
    if (inValA == null) {
        if (inValB == null) {
            return null;
        }
        return inValB;
    }
    if (inValB == null) {
        return inValA;
    }
    int aIndex = inValA.length() - 1;
    int bIndex = inValB.length() - 1;
    int longestLength = Math.max(aIndex, bIndex) + 2;
    char[] tempOutVal = new char[longestLength];
    int tempOutIndex = tempOutVal.length - 1;
    char aTemp;
    char bTemp;
    for (; aIndex >= 0 && bIndex >= 0; aIndex--, bIndex--, tempOutIndex--) {
        aTemp = inValA.charAt(aIndex);
        BinaryCharValidator(aTemp, inValA);
        bTemp = inValB.charAt(bIndex);
        BinaryCharValidator(bTemp, inValB);
        SetValue(aTemp, bTemp, tempOutVal, tempOutIndex);
    }
    if (aIndex >= 0) {
        for (; aIndex >= 0; aIndex--, tempOutIndex--) {
            aTemp = inValA.charAt(aIndex);
            BinaryCharValidator(aTemp, inValA);
            bTemp = ZERO_CHAR_VALUE;
            SetValue(aTemp, bTemp, tempOutVal, tempOutIndex);
        }
    }
    if (bIndex >= 0) {
        for (; bIndex >= 0; bIndex--, tempOutIndex--) {
            aTemp = ZERO_CHAR_VALUE;
            bTemp = inValB.charAt(bIndex);
            BinaryCharValidator(bTemp, inValB);
            SetValue(aTemp, bTemp, tempOutVal, tempOutIndex);
        }
    }
    return new String(tempOutVal);
}

public static void SetValue(char aVal, char bVal, char[] outVal, int outIndex) {
    if (outVal[outIndex] == DEFAULT_CHAR_VALUE) {
        outVal[outIndex] = ZERO_CHAR_VALUE;
    }
    int aTemp = aVal - ZERO_CHAR_VALUE;
    int bTemp = bVal - ZERO_CHAR_VALUE;
    int outTemp = outVal[outIndex] - ZERO_CHAR_VALUE;
    int sum = aTemp + bTemp + outTemp;
    outVal[outIndex] = (char) ((sum % 2) + ZERO_CHAR_VALUE);
    if (sum > 1) {
        outVal[outIndex - 1] = ONE_CHAR_VALUE;
    } else {
        outVal[outIndex -1] = ZERO_CHAR_VALUE;
    }
}

public static void BinaryCharValidator(char toCheck, String input) {
    if (!(toCheck == ZERO_CHAR_VALUE || toCheck == ONE_CHAR_VALUE)) {
        throw new IllegalArgumentException(String.format("Malformed string(only 1's and 0's allowed).  The string is \"%s0\"", input));
    }
}
2 of 2
2

I agree with you, space complexity should be \$O(n)\$, using StringBuilder should not matter because, internally it would store char in an array which would expand / shrink as needed.

Now some code-reviews.

Error check:

  1. Null check? x or y could be null. This (x == null || y == null) looks better.

  2. Your code says "sumofbinary", but what if your string was "123" + "543"?

Name check:

  1. sb is not a professional name, call it sum.

Syntax check:

  1. while(i > = 0 || j >= 0) .. there is a space > = for i > = 0, but not for j.

Misc:

  1. StringBuilder can be marked final.

  2. You end for loop when both i & j are 0. This has a drawback, if i is longer than j, you would waste error checking if (j > 0).