Space complexity of the "add two binary strings" challenge I was solving this problem of "adding two string binary numbers" and came up with the following algorithm. 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.

public String sumOfBinary(String x, String y) {
    if((x.length == 0 &amp;&amp; y.length == 0) || (x == null &amp;&amp; y == null)) 
       return;

    int i = x.length - 1, j = y.length - 1, carry = 0;
    StringBuilder sb = new StringBuilder();

    while(i &gt; = 0 || j &gt;= 0) {
     int sum = carry;
     if(i &gt;= 0) {
       sum+= x.charAt(i--) - '0';
     }
     if(j&gt;=0) {
       sum+=y.charAt(j--) - '0';
     }

     sb.append(sum%2);
     carry = sum/2;

    }
    if(carry!=0) {
      sb.append(carry);
    }
   return sb.reverse().toString();
}


It would be awesome if someone could review the code and let me know if there is any other better way to do this, along with what the space complexity is in the algorithm.
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:


Null check? x or y could be null. This (x == null || y == null) looks better.
Your code says "sumofbinary", but what if your string was "123" + "543"?


Name check:


sb is not a professional name, call it sum.


Syntax check:


while(i &gt; = 0 || j &gt;= 0) .. there is a space &gt; = for i &gt; = 0, but not for j. 


Misc:


StringBuilder can be marked final.
You end for loop when both i &amp; j are 0. This has a drawback, if i is longer than j, you would waste error checking if (j > 0).