← PayPal bank

PayPal · Question 22 · Strings

Add Binary

StringsJavacode⏱ O(n)💾 O(max(m,n))
Product-based

Problem

Add two binary strings and return their sum as a binary string.

Approach

Use two pointers from end and add with carry.

Time O(n)Space O(max(m,n))

How it works

  1. 1Add bits right to left with carry.
  2. 2Reverse the accumulated result.

Sample input / output

Input:
a = "1010", b = "1011"
Output:
10101

Constraints

1 <= lengths <= 10^4; binary strings only.

Solution — read it, then walk it

Time O(n)Space O(max(m,n))Loops 1Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static StringaddBinary(String a, Stringb)StringBuilder sb = newStringBuilder()DEFINE i = a.length() - 1,j = b.length() - 1, carry =0while (i >= 0 || j >=0 || carry == 1)DEFINE sum = carryif (i >= 0) sum +=a.charAt(i--) - '0'if (j >= 0) sum +=b.charAt(j--) - '0'sb.append(sum % 2)carry = sum / 2RETURNsb.reverse().toString()DEFINE static voidmain(String[] args)System.out.println(addBinary("1010","1011"))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/15

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits