Swap Number Without Temporary Variable

Easy
0/40
Average time to solve is 15m
21 upvotes
Asked in companies
MicrosoftOracleDell Technologies

Problem statement

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.

Detailed explanation ( Input/output format, Notes, Images )
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
Sample Input 1:
2
10 12 
-4 -5   
Sample Output 1:
12 10
-5 -4
Explanation of sample input 1:
Test Case 1:
Given β€˜X’ is 10 and β€˜Y’ is 12. After swapping β€˜X’ will be 12 and β€˜Y’ will be 10.

Test Case 2:
Given β€˜X’ is -1 and β€˜Y’ is -5. After swapping β€˜X’ will be -5 and β€˜Y’ will be -4.
Sample Input 2:
2
1 2 
0 -5   
Sample Output 2:
2 1
-5 0
Hint

Try with arithmetic operations (addition and subtraction)

Approaches (4)
Addition Approach
  • 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’.
Time Complexity

O(1), We are taking only constant time 

Space Complexity

O(1), We are using constant space 

Code Solution
(100% EXP penalty)
Swap Number Without Temporary Variable
Full screen
Console