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:
- A.
1
- B.
2
- C.
3
- D.
0
Attempted by 1354 students.
Show answer & explanation
Correct answer: D
Correct answer: 0 temporary variables.
Explanation: You can swap two variables without using any temporary variable by performing in-place operations. Two common approaches are:
Bitwise XOR method (works for integer types): a = a ^ b; b = a ^ b; a = a ^ b;
Arithmetic method (works for numeric types but can overflow): a = a + b; b = a - b; a = a - b;
Caveats:
These in-place methods apply mainly to numeric or bitwise-compatible types and are not generally applicable to all data types (for example, strings or complex objects).
The arithmetic method may suffer from integer overflow in some languages or environments.
The XOR method requires bitwise operations and careful handling if both variables reference the same memory location.
If in-place operations are not allowed or are unsafe for the data type, using one temporary variable is the practical and safe approach: temp = a; a = b; b = temp;