Approach: The solution uses arithmetic operations to exchange the values of two numbers. First, both numbers are added and stored in the first variable. The second variable is then updated by subtracting its value from the first variable, resulting in the original value of the first variable. Finally, the first variable is updated by subtracting the new value of the second variable, resulting in the original value of the second variable.
This approach avoids the use of an additional variable while performing the swap in-place.
Java Solution:
public class SwapNumbers {
public static void main(String[] args) {
int firstNumber = 10;
int secondNumber = 20;
System.out.println("Before Swapping:");
System.out.println("First Number: " + firstNumber);
System.out.println("Second Number: " + secondNumber);
firstNumber = firstNumber + secondNumber;
secondNumber = firstNumber - secondNumber;
firstNumber = firstNumber - secondNumber;
System.out.println("After Swapping:");
System.out.println("First Number: " + firstNumber);
System.out.println("Second Number: " + secondNumber);
}
}Output: Before Swapping: First Number: 10 Second Number: 20
After Swapping: First Number: 20 Second Number: 10
Time Complexity: O(1), as the swap operation requires a fixed number of arithmetic operations.
Space Complexity: O(1), since no additional memory is used apart from the existing variables.
Key Interview Points: • This approach performs the swap without using an extra variable. • The arithmetic method may cause integer overflow when dealing with very large values. • An alternative approach uses the XOR bitwise operator to swap values without overflow and without an additional variable.