The minimum number of temporary variables needed to swap the contents of two…

2018

The minimum number of temporary variables needed to swap the contents of two variables is:

Answer: D. 0Concept: A swap of two variables does not, in principle, require a separate holding (temporary) variable -- it only requires operations on the pair (a, b)…

  1. A.

    1

  2. B.

    2

  3. C.

    3

  4. D.

    0

Attempted by 1722 students.

Show answer & explanation

Correct answer: D

Concept: A swap of two variables does not, in principle, require a separate holding (temporary) variable -- it only requires operations on the pair (a, b) that are invertible, meaning each original value can be reconstructed step-by-step from a combined result. Bitwise XOR and the addition/subtraction identity are two such operations, so the exchange can be done in place using zero extra variables.

Applying it here: Trace it with a = 5, b = 9 using the XOR-swap sequence:

  1. a = a ^ b -> a becomes 5 ^ 9 = 12; b is unchanged at 9.

  2. b = a ^ b -> b becomes 12 ^ 9 = 5, which is the ORIGINAL value of a.

  3. a = a ^ b -> a becomes 12 ^ 5 = 9, which is the ORIGINAL value of b.

At no point was a third location written to -- only a and b were ever used, so this exchange needed zero temporary variables. An additive/subtractive sequence works the same way: a = a + b; b = a - b; a = a - b; -- each line recovers one original value from the combined sum.

Cross-check: A count of variables can never be negative, so zero is the smallest value it is even meaningful to ask for -- and the trace above shows zero is actually achievable, not merely a theoretical floor. This is also why the familiar one-temp method (temp = a; a = b; b = temp;) is a valid technique but not a minimal one: it works, but a strictly smaller count also works.

Answer: The minimum number of temporary variables required is 0.

Caveats:

  • These in-place methods apply mainly to numeric or bitwise-compatible types and do not generalize to all data types (for example, strings or composite objects).

  • The additive/subtractive method can overflow in fixed-width integer types.

  • The XOR method needs care if both names refer to the same memory location, since XOR-ing a value with itself zeroes it out.

  • When in-place operations are unsafe or unsupported for the data type, using one temporary variable remains the practical, safe fallback.

Explore the full course: Up Lt Grade Assistant Teacher 2025

Loading lesson…