Swap Number Without Temporary Variable

Posted: 21 Nov, 2020
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

Given two variables ‘X’ and ‘Y’. Your task is to swap the number without using a temporary variable or third variable.

Swap means the value of ‘X’ and ‘Y’ must be interchanged. Take an example ‘X’ is 10 and ‘Y’ is 20 so your function must return ‘X’ as a 20 and ‘Y’ as a 10.

Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

Next ‘T’ lines contain two space-separated integers ‘X’ and ‘Y’ which represent the next ‘T’ test cases. 
Output Format
For each test case, return an array/vector that contains two integers ‘X’ and ‘Y’ with a swapped value.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 2*10^5
-10^9 <= X,Y <= 10^9

Where ‘T’ is the total number of test cases, ‘X’ and ‘Y’ denotes two given integer variables.

Time limit: 1 second
Approach 1
  • Idea is to get the sum of given two-variable ‘X’ and ‘Y’ in an ‘X’ = ‘X’ + ‘Y’.
  • Value of swapped ‘Y’ can get by ‘X’ - ‘Y’ = (‘X’ + ‘Y’) - ‘Y’ = ‘X’
  • Value of swapped ‘X’ can get by ‘X’ - ‘Y’ = (‘X’ + ‘Y’) - ‘Y’ = (‘X’ + ‘Y’) - ‘X’ = ‘Y’
  • The current value of ‘Y’ is the initial value of ‘X’
  • Suppose ‘X’ is 10 and ‘Y’ is 20 then
    • ‘X’ = ‘X’ + ‘Y’ = 20+10’
    • Swapped value of ‘Y’ is ‘X’- ‘Y’ = 30-20 = 10’
    • And the swapped value of ‘X’ is ‘X’ - ‘Y’ = 30-10 = 20’
    • So ‘X’ is 20 and ‘Y’ is 10
  • Return swapped ‘X’ and ‘Y’.
Try Problem