Write a function (or method) to swap two numbers in place without using any temporary variables. So, you can not use a 3rd variable.

This is one of the most popular software interview questions asked. There are two popular solutions to this problem – we will take a look at both of them.

Clearly the challenge here is to not use a 3rd temporary variable – so we can only use the two variables that will actually hold the numbers that are passed in to the function or method. This is what the code would look like if we do actually use a temporary variable to hold one of the integers passed in – just so you know the exact solution that we would like to avoid:

Swapping the numbers using a temp variable:

public static void swapNumbers (int a, int b)
{
  int temp = a;  //temp holds a
  int a = b;  // a is now b
  b = temp; // and b is now a!
}

There’s no way we can just swap the numbers in one line of code – so there must be something that we can do. Clearly, we will have to use one of the variables to hold some meaningful information – we can’t use both variables to hold something other than the number itself because then we will lose that value.

What if we use subtraction and addition? Well, that actually gives us a solution – and here is what it looks like using a Java method:

Swapping the numbers without using a temp variable in Java:

public static void swapNumbers (int x, int y)
{
  x = y - x; 
  y = y - x; 
 x = x + y; 
}

Take some sample numbers to see if this actually works – say x is 7 and y is 4. Then, in the first line x will be set to -3. In the second line, y will be set to 4 – (-3), which is 7, so y will now have the value of x. And, finally x will be set to -3 + 7 in the third line, which is equal to 4. And now we can see that the values have been successfully swapped! Note that this function will also work for negative numbers.

Swap numbers without temp using XOR

There is an alternative solution that is probably more difficult to have come up with on your own. Here it is – it uses the XOR operator in Java. The XOR operator (which is short for exclusive-or) will take the binary representation of each of the numbers and perform an operation on the binary equivalent of those numbers. Here is what the solution looks like in a Java method:

Solution to swapping numbers without temp using XOR:

public static void swapNumbers (int x, int y)
{
  x = x^y; 
  y = x^y; 
  x = x^y; 
}

And there we have our two solutions to the problem.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

Leave a Reply

Your email address will not be published.