Count max points on a line
April 10, 2020
Max Distance between two occurrences of the same element
April 15, 2020

Swapping two variables without using third variable

This is a very common interview question, esp. at the junior level. Let us first write a function that swap two integers using a third variable.

void swap(int *a, int *b){
   int temp = *a;
   *a = *b;
   *b = temp;
}

It must receive int* and not int, because we want to change the variables in calling function. In C++ variables can be passed by reference also,

// C++ Code. Won’t compile for C language.
void swap(int &a, int &b)
{
  int temp = a; a = b; b = temp;
}

But C language does not permit pass-by-reference. It is easier to answer when the question is about swapping two integers. The question here is to swap two variables. A variable can be of any data type, either pre-defined or user-defined.

Before getting into these details, let us try to dissect popular answers,

Method-1: Using XOR Method

Using bit-wise XOR operator, two integral variables can be swapped without using third variable as shown below:

  X = X ^ Y;
  Y = X ^ Y;
  X = X ^ Y; 

But XOR operator can only be used with integral data types. We cannot use this method to swap two floating point numbers of either single precession or double precession. Let us look at the next method:

Method-2: Add-subtract method

The second method is using a combination of addition and subtraction operators, as shown below

  X = X + Y; 
  Y = X - Y; 
  X = X - Y;

This method can swap two numbers of any type, but it is worse than previous method. If values of x and y are so large that their sum exceeds upper limit of their data type, then overflow happens. How C language handles overflow and underflow is not defined.

You may replace combination of add-subtract with multiply-divide, but problem of overflow is still there.

One limitation with both the methods is that they can only be used with predefined data types. They cannot swap two strings or even two pointers. In fact, even a code similar to Code 3.5 fails to swap two string. To swap two strings, we have to write a custom swap method as given in Code below:

// str1 AND str2 ARE OF EQUAL LENGTH
void swap(char* str1, char* str2)
{
  int len = strlen(str1);
  for(int i=0; i<len; i++)
  {
    char temp = str1[i];
    str1[i] = str2[i];
    str2[i] = temp; 
  }
}

Similarly, to swap two arrays or two objects of user-defined struct type, we have to write custom methods. While swapping user defined types, the complications of shallow-copy and deep-copy may also arise. There is no generic swap method that can swap two variables.

Now, you know what to answer, when interviewer asks you to swap two variables without using third variable. With your answer, you may end up educating the interviewer.


1 Comment

  1. Panja Bharath says:

    X = X * Y;
    Y = X / Y;
    X = X / Y;

Leave a Reply

Your email address will not be published. Required fields are marked *