Placement Prep

Swap Two Numbers Without a Third Variable

Three ways to swap two numbers without a third variable, with C code: arithmetic, XOR, and multiply-divide. Covers trade-offs, overflow risk, and what interviewers ask.

By FACE Prep Team 5 min read
swap-without-third-variable bitwise-xor c-programming interview-prep placement-prep coding-interview space-complexity

Swapping two numbers without a third variable appears in aptitude tests, coding rounds, and on-site interviews at Indian IT firms. Three methods cover all the standard cases.

Why This Question Keeps Appearing

The question is not really about swapping. It tests whether a candidate understands trade-offs: when does a clever trick break, and what does overflow look like in practice? A candidate who explains the XOR method and then mentions the integer overflow limitation signals better systems thinking than one who stops at “it swaps the values.”

At companies running aptitude-plus-coding pipelines (common at Tier-2 college placement drives), this problem tests two things at once: arithmetic reasoning and bitwise operation knowledge. Getting both right, and knowing the failure modes, is the target.

The three methods below are ordered from simplest to most nuanced. Read all three before your next coding round.

Method 1: Arithmetic (Addition and Subtraction)

The idea is to encode both values into a using addition, then decode each one using subtraction.

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    printf("Before: a = %d, b = %d\n", a, b);

    a = a + b;   /* a = 15 */
    b = a - b;   /* b =  5 */
    a = a - b;   /* a = 10 */

    printf("After:  a = %d, b = %d\n", a, b);
    return 0;
}

Step-by-step trace for a = 5, b = 10:

  • Step 1: a = a + b → 5 + 10 = 15 (a now holds the sum of both values)
  • Step 2: b = a - b → 15 - 10 = 5 (b now holds the original value of a)
  • Step 3: a = a - b → 15 - 5 = 10 (a now holds the original value of b)

Limitation: Integer Overflow

If a and b are both close to the maximum value for the signed integer type, the addition in Step 1 overflows. The C standard defines this maximum as INT_MAX, which is 2,147,483,647 for a 32-bit signed int. Any pair where a + b exceeds that limit causes undefined behaviour, and the subsequent subtractions produce the wrong result.

In most placement tests, the given values are small and overflow is a theoretical concern. In a live interview, mention it anyway.

Method 2: Bitwise XOR

XOR swap avoids addition entirely. It works on the bit representations of both values and never overflows, because XOR on bits never generates a carry.

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    printf("Before: a = %d, b = %d\n", a, b);

    a = a ^ b;
    b = a ^ b;
    a = a ^ b;

    printf("After:  a = %d, b = %d\n", a, b);
    return 0;
}

Why XOR Works

Two XOR identities drive the whole approach:

  • x ^ x = 0 (any value XOR’d with itself is zero)
  • x ^ 0 = x (any value XOR’d with zero is itself)

Step-by-step trace for a = 5 (0101 in binary), b = 10 (1010 in binary):

  • Step 1: a = a ^ b0101 ^ 1010 = 1111 (a = 15, stores both values combined)
  • Step 2: b = a ^ b1111 ^ 1010 = 0101 (b = 5, which is the original a)
  • Step 3: a = a ^ b1111 ^ 0101 = 1010 (a = 10, which is the original b)

For a deeper walkthrough of the XOR algebra, GeeksForGeeks covers the bitwise mechanics with additional examples across data types.

The space complexity of XOR swap is O(1): no auxiliary variable, no array, no heap allocation. The arithmetic method is also O(1), but XOR gets there without the overflow risk.

Edge Case: Aliasing

XOR swap fails when both variables alias the same memory address. If you pass &a as both arguments to a swap function, a = a ^ a evaluates to 0 and the value is lost. The arithmetic and multiplication-division methods fail under the same aliasing condition. This edge case does not appear in standard placement tests, but interviewers at product companies do ask about it.

Method 3: Multiplication and Division

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    printf("Before: a = %d, b = %d\n", a, b);

    a = a * b;   /* a = 50 */
    b = a / b;   /* b =  5 */
    a = a / b;   /* a = 10 */

    printf("After:  a = %d, b = %d\n", a, b);
    return 0;
}

Step-by-step trace for a = 5, b = 10:

  • Step 1: a = a * b → 5 * 10 = 50 (a now holds the product)
  • Step 2: b = a / b → 50 / 10 = 5 (b now holds the original a)
  • Step 3: a = a / b → 50 / 5 = 10 (a now holds the original b)

Hard Limitation: Division by Zero

If either a or b is zero, the division step causes a runtime error. The arithmetic and XOR methods handle zero inputs correctly. For that reason, multiplication-division is rarely the preferred answer in an interview unless the problem explicitly guarantees non-zero inputs.

A secondary concern: for floating-point numbers, integer division truncates, so the result may be slightly off. Stick to integers if you use this method at all.

Comparison and When to Use Each

MethodOverflow riskHandles zeroSafe with aliasingBest for
ArithmeticYes (large values)YesNoAptitude papers; simple explanation
Bitwise XORNoneYesNoCoding rounds; memory-constrained code
Multiply-divideYes (large values)NoYesRarely — avoid by default

Modern C and C++ provide std::swap (cppreference), which internally uses a temporary variable but reads as a single, intention-revealing call. Production code uses std::swap. Interview questions specifically test the no-temp variants because they probe conceptual understanding, not code style.

Python handles this in one line: a, b = b, a. Python evaluates the right-hand side as a tuple before the assignment, so no aliasing risk exists and no intermediate variable is needed. Java and Kotlin use the same XOR or arithmetic logic as C; neither has a built-in tuple-swap syntax.

XOR is the default answer in a coding round. Arithmetic is the backup when the language or context makes bitwise operations awkward. Multiplication-division belongs in the “also possible, but avoid” column unless the interviewer specifically asks for it.

Practice Problems to Reinforce the Pattern

Swap-without-temp is a building block for a range of in-place manipulation problems. These sibling problems in the same cluster use the same kind of reasoning:

Knowing which of the three swap methods breaks on overflow, which breaks on zero, and which breaks on aliasing is exactly the kind of failure-mode reasoning that coding rounds are designed to test. That same discipline applies when writing AI applications: edge-case thinking is what separates code that passes the happy-path tests from code that ships to production. TinkerLLM at ₹299 is a practical entry point for applying that reasoning to real LLM projects.

Primary sources

Frequently asked questions

Does XOR swap fail if both variables alias the same memory address?

Yes. If a and b point to the same memory location, a = a ^ a evaluates to 0 and both variables are zeroed. The arithmetic and multiplication-division methods fail under the same aliasing condition. Placement tests always use distinct variables, but citing this edge case in an interview is a differentiator.

Why does the arithmetic method fail with large integers?

If a and b are both close to INT_MAX (2,147,483,647 on a 32-bit system), the addition step a + b overflows the signed integer range and wraps to a negative number. All subsequent subtractions then produce the wrong result. XOR operates on individual bits, so it never overflows.

Can I swap two numbers without a third variable in Python?

Python's tuple unpacking (a, b = b, a) swaps in one line. Python evaluates the right-hand side as a tuple before unpacking, so there is no aliasing risk. The three manual methods are still expected knowledge for C and Java rounds and for aptitude-paper questions.

Does the multiplication-division method work when one value is zero?

No. If a or b is zero, the division step causes a division-by-zero error at runtime. The arithmetic and XOR methods handle zero values correctly. For this reason, multiplication-division is rarely the right answer in an interview unless the problem explicitly guarantees non-zero inputs.

Which swap method appears most in Indian placement aptitude papers?

The arithmetic method (a = a+b; b = a-b; a = a-b) appears most often in aptitude papers because it tests basic algebraic reasoning. XOR appears in coding rounds that evaluate bitwise knowledge. Multiplication-division rarely appears in test papers from major IT recruiters.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF