How to SWAP values of two variables without using a third variable (integer) ?

Many times I asked this particular question in the interview session and many people failed to answer. This is just to see the analytic ability of a candidate and how dynamic thinking they have. The logic is same for all programming language, so if you have the logic right then you can answer it for any particular language such as PHP, JAVA, C++, C etc. but in this tutorial We will use PHP πŸ™‚

What if we can use the third variable:

$a = 100;

$b = 200;

now we need to swap the values so that $a becomes 2oo and $b becomes 1oo.

the basic technique is to introduce a third variable $tmp

$tmp = $a;

$a = $b;

$b = $tmp;

isn’t it straight forward. introducing a third variable it is so easy. but what will be our approach if there is no third variable? is it possible?

The answer is a big YES. There are several ways and they fall in two types of solution.

1. Arithmetic operation

2. Bitwise operation.

Arithmetic Operation:

we can use addition-deduction and multiply-division method to solve the problem.

let’s see how addition – deduction method works.

<?php

$x = 10;

$y = 20;
$x = $x+$y;
$y = $x – $y;
$x = $x – $y;
?>

it is also very simple, isn’t it. first we are adding the two numbers and keeping the result in one of the variable. in the above example its $x and it contains $x+$y. in the second operation, we are deducting $y from $x and assigning it to $y. now lets break the equation logically

$y = $x – $y => $x + $y – $y => $xΒ  // [ since $x = $x+$y ]

cool, we swapped one of the variable. and following the same operation we are swapping the second one in the third line. so that’s it. It is so easy but just requires some logical thinking. do not try to memorize it rather than understand the simple logic here.

now the multiply-division method:

<?php

$x = 10;

$y = 20;
$x = $x*$y;
$y = $x / $y;
$x = $x / $y;
?>

it is same as the addition-deduction method and logic is similar.

now do we see any problem in the above logic? that is the question i ask if someone can answer the question correctly and show me the above solution. πŸ™‚

the answer for that is very simple, it is the number overflow as we always have upper limit for integers. so when we add or multiply two big numbers then the result can cause overflow and might not show desired results.

so what can be a good solution with keeping the overflow fact in mind? the answer is bitwise operation

Bitwise operation:

in order to swap two values we can use the XOR bitwise operator.

Note: A bitwise exclusive or takes two bit patterns of equal length and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if the two bits are different, and 0 if they are the same

the algorithm is

x = x XOR y

y = x XOR y

x = x XOR y

if we write them in computer language using caret (^) then it will look like

x = x ^ y

y = x ^ y

x = x ^ y

in shorter version:

x ^= y

y ^= x

x ^= y

in one line

x ^= y ^= x ^= y

so here is the command in php:

$x ^= $y ^= $x ^= $y

now how it works:

so now we know how to swap two values without using a third variable. ask me any questions you have πŸ™‚

Posted in: PHP

68 thoughts on “How to SWAP values of two variables without using a third variable (integer) ?

  1. hasin says:

    here’s another one

    list($a, $b) = array($b, $a)

    it will also swap values of two variables without using a third one πŸ™‚ – the php way!

  2. Shuvo says:

    A cunning question to be asked in an interview. Are you familiar with something called ‘Principle of least astonishment’? In any job interview, I believe, an interviewer should only assess a person’s interest and skills. By the way, I am aware of this trick since 2000/2001 and I don’t earn my living writing code.

  3. mizan says:

    Hi Shuvo
    For developers who earn their living writing codes, these type of questions are very common. we have to face so many different type of questions which are outside of our interest. I completely agree with you that interview should assess only person’s interest and skills but in programming basic is also very important and this question is a basic one πŸ˜‰

  4. Tarek Mahmud apu says:

    Thanks for the post.. i just want to add more…

    Using Arithmetic Operation it just can swap int or float type data.

    But if we use Bitwise operation it can swap both number and string.

    But it cannot swap any array, class; But if we use List it can swap everything. It can swap number, string, array and also can swap a class 

    Array swap sample :
    ‘one’);
    $y = array(‘b’ => ‘two’);

    list($x,$y) = array($y,$x);

    echo ‘X : ‘;
    print_r($x);
    echo ‘Y : ‘;
    print_r($y);
    ?>

    Output:
    X :
    Array
    (
    [b] => two
    )
    Y :
    Array
    (
    [a] => one
    )

    Class swap :
    <?php

    class a
    {
    public $name = ‘alu’;
    }
    class b
    {
    public $name = ‘begun’;
    }

    $x = new a();
    $y = new b();

    list($x,$y) = array($y,$x);

    echo ‘X : ‘;
    var_dump($x);
    echo ‘Y : ‘;
    var_dump($y);
    ?>

    so list is better … πŸ™‚

  5. rune_kg says:

    And please notice that on 32bit boxes it will only work for numbers smaller than 2 in the power 31 minus 1:

    2147483647

    see this code as example:

    <?
    $a=pow(2,31);
    $b=pow(2,31)-1;
    echo “$a $bn”;
    $a^=$b^=$a^=$b;
    echo “$a $bn”;

  6. sabuz85 says:

    Mizan Bhai,I always monitor your bolg.When u post anything then i read this & get idea various terms in PHP.This is very nice post.

    Thanks Mizan Bhai.

  7. sumesh says:

    hai miza,

    thanks for your code, please give me a solution for studying linked list easily.
    loving friend,
    sumesh

  8. eshae says:

    thanks bhaya ………a lot actually i have studied pre-med , nw i am fcing a little bt prblem in prgraming my teachr had given me thies question and i was searching for it from many days …………….thanks …

  9. recipesmela says:

    dear friends i am new learner kindly see my method of equation

    <?php
    $a ='100';
    $b='200';
    $c= $a + $b;
    $b= $c-$a;
    echo "a is equal to $b “;
    $b= $c-$b;
    echo “b is equal to $b”;
    ?>

  10. Algo says:

    Yesterday,in a job interview they asked me same question to swap values without usind a third variable, even though I was very close I couldn’t come up with correct solution. And now I see how it is easy… I wish I knew the solution before.NΔ°CE AND NEAT

  11. Amit Vaishnava says:

    now you had seen this example with 2 – 3 statements
    so i give you optimum sol by solving in 1 line statement
    are-
    a=a+b-(b=a);

    or

    a=a*b/(b=a);

    amitvaishnava

Leave a Reply to Tarek Mahmud apu Cancel reply

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