Swap Two Integers Without Extra Storage

Use either arithmetic or XOR to swap i and j without a temporary variable.

Try your own values
Current values
Start
Step 0 / 3
i
5
j
9
Operation
Initial state

We want i = 9 and j = 5 without creating a temporary variable.

The pattern
i = i + j j = i - j i = i - j

Idea: first store both original values inside i. The next two subtraction steps recover them in reverse order.

Interview answer i = i + j j = i - j i = i - j

Or, for integers, use XOR to avoid arithmetic overflow: i ^= j; j ^= i; i ^= j;