Tuesday, September 26, 2023

3 ways to swap two Numbers without using Temp or Third Variable in Java?

How to swap two numbers without using temp or third variable is a common interview question not just on Java interviews but also on C and C++ interviews. It is also a good programming question for freshers. This question was asked to me long back and didn't have any idea about how to approach this question without using temp or third variable, maybe lack of knowledge on bitwise operators in Java or maybe it didn't click at that time. Given some time and trial error, I eventually come out with a solution with just an arithmetic operator but the interviewer kept asking about other approaches of swapping two variables without using temp or third variable.

Personally, I liked this question and included in the list of my programming interview question because of its simplicity and some logical work, it forces you to do. 

When I learned bit-wise operation in Java I eventually find another way of swapping two variables without a third variable, which I am going to share with you guys.


1. Swapping two numbers without using temp variable in Java

If you have ever heard this question, then you must be familiar with this approach of swapping numbers without using the temp variable.

If you are hearing this question the very first time, then try it yourself, it's a good programming exercise for an absolute first-timer.

By the way, here is the code example of swapping two numbers without using temp variable and using the arithmetic operator in Java:

int a = 10;
int b = 20;

System.out.println("value of a and b before swapping, a: " + a +" b: " + b);

//swapping value of two numbers without using temp variable
a = a+ b; //now a is 30 and b is 20
b = a -b; //now a is 30 but b is 10 (original value of a)
a = a -b; //now a is 20 and b is 10, numbers are swapped

System.out.println("value of a and b after swapping, a: " + a +" b: " + b);

Output:
value of a and b before swapping, a: 10 b: 20
value of a and b after swapping, a: 20 b: 10





2.  Swapping two numbers without using temp variable in Java with the bitwise operator

Bitwise operators can also be used to swap two numbers without using a third variable. XOR bitwise operator returns zero if both operands are the same i.e. either  0 or 1 and return 1 if both operands are different e.g. one operand is zero and the other is one. 

By leveraging this property, we can swap two numbers in Java. 

Here is a code example of swapping two numbers without using temp variable in Java using XOR bitwise operand:

A       B       A^B (A XOR B)
0       0       0 (zero because operands are same)
0       1       1
1       0       1 (one because operands are different)
1       1       0

int a = 2; //0010 in binary
int b = 4; //0100 in binary
      
System.out.println("value of a and b before swapping, a: " + a +" b: " + b);
       
//swapping value of two numbers without using temp variable and XOR bitwise operator     
a = a^b; //now a is 6 and b is 4
b = a^b; //now a is 6 but b is 2 (original value of a)
a = a^b; //now a is 4 and b is 2, numbers are swapped
      
System.out.println("value of a and b after swapping using XOR bitwise operation, a: " + a +" b: " + b);

value of a and b before swapping, a: 2 b: 4
value of a and b after swapping using XOR bitwise operation, a: 4 b: 2


And, here is a nice diagram to remember how to swap two numbers in Java and Python:


How to swap two integers in Java and Python



3. Swapping two numbers without using temp variable in Java with division and multiplication

swap two numbers without using thrid or temp variable in Java programmingThere is another, third way of swapping two numbers without using a third variable, which involves multiplication and division operator. This is similar to the first approach, where we have used + and - operators for swapping values of two numbers. 

Here is the code example to swap two numbers without using a third variable with division and multiplication operators in Java :

int a = 6;
int b = 3;

System.out.println("value of a and b before swapping, a: " + a +" b: " + b);

//swapping value of two numbers without using temp variable using multiplication and division
a = a*b; //now a is 18 and b is 3
b = a/b; //now a is 18 but b is 6 (original value of a)
a = a/b; //now a is 3 and b is 6, numbers are swapped

System.out.println("value of a and b after swapping using multiplication and division, a: " + a +" b: " + b);

Output:
value of a and b before swapping, a: 6 b: 3
value of a and b after swapping using multiplication and division, a: 3 b: 6


That's all on 3 ways to swap two variables without using a third variable in Java. Its good to know multiple ways of swapping two variables without using temp or third variable to handle any follow-up question.

Swapping numbers using a bitwise operator is the fastest among the three because it involves a bitwise operation. 

It’s also a great way to show your knowledge of bitwise operators in Java and impress the interviewer, which then may ask some questions on a bitwise operation.

 A nice trick to drive interviews in your expert area.


Other Coding Problems to learn Programming in Java
  • How to check if two rectangles intersect with each other in Java? (solution)
  • How to implement iterative quicksort in Java? (solution)
  • How to implement the sieve of the Eratosthenes algorithm in Java? (solution)
  • How to reverse an ArrayList in place in Java? (solution)
  • How to add two numbers without using the plus operator in Java? (answer)
  • How to implement in-order traversal in Java? (solution)
  • How to remove duplicate characters from String in Java? (program)
  • How to implement post-order traversal in Java? (program)
  • How to implement a binary search tree in Java? (solution)
  • How to implement a binary search algorithm in Java? (solution)
  • How to reverse a singly linked list in Java? (program)
  • How to implement pre-order traversal of a binary tree in Java? (solution)
  • How to implement an insertion sort algorithm in Java? (answer)
  • Write a program to implement bubble sort in Java? (solution)
  • How to print all leaf nodes of a binary tree in Java? (solution)
  • How to find the square root of a given number in Java? (solution)

And, if you already solved this problem and looking for more challenging problems to really sharpen your coding and algorithm skills then you should try to solve problems given in the Algorithm Design Manual book by Steve Skiena. It's a great book to prepare for data structure and algorithms interview. 

And lastly one question for you? What was the last coding question asked to you? If you remember more than one then feel free to share but at least share one question 

51 comments:

  1. As I saw the first method you've explained the first time, I was absolutely amazed.

    Thanks for this article. I didn't know the other two ones.

    Are there any real world examples where somebody would want to use any of these solutions? Perhaps swapping register contents for context switches within the OS?

    ReplyDelete
  2. Won't there be problem of over-flow in methods 1 & 3 ?

    ReplyDelete
  3. @Hemanth: of course that's the potential problem. That's why better you come with method 2 in the first place, then you can show you know also about 1 & 3, but pointing out the risks.

    ReplyDelete
  4. @Hemanth and @Jozsef, Good point. That's a good thing to point out even during interviews, and probably a good follow up question.

    ReplyDelete
  5. Piece of cake in Python lol

    a,b=b,a

    ReplyDelete
  6. While these are neat for things like a programmer's interview question I would be very careful about actually using these in real code, for two reasons:

    1. It obfuscates the code for very little benefit. Readability suffers more than performance gains.

    The JVM could employ similar tricks under the covers for performance reasons if it detects that this is on the hot path.

    2. The code is sensitive to overflow, sign handling, Not-a-Number, and divide-by-zero.

    Both these points should be raised by an experienced programmer.

    ReplyDelete
  7. What if "b == 0"? Then "b = a/b" gives a division by zero exception...

    ReplyDelete
  8. "Are there any real world examples where somebody would want to use any of these solutions? "

    No, which is why it is a stupid interview question and if your interviewer asks it, you might think twice about taking the job there. Remember an interview is where you decide if you want to work there in addition to the company deciding if they want to hire you.

    ReplyDelete
  9. String a;
    String b;

    Now do it. Fail.

    ReplyDelete
    Replies
    1. The title of the article says NUMBERS not STRINGS.

      Delete
  10. @Asgeir Storesund Nilsen , I think you raised very important things regarding, overflow, sign handling, and divide by zero. Solution, which involves integer arithmetic always prone to overflow. I guess second solution still fits the bill, what's your thought?

    ReplyDelete
  11. @Anonymous, Yes that's an age case for third solution. Interviewer really likes if you can raise those concerns as well, but you need to back with solution. XOR may help there.

    ReplyDelete
  12. @Anonymous, In real world, I suggest to use temp variable. It's easy, readable and works perfectly.In my opinion, these kind of questions has there place, they make you to think and put your thought on code, point out edge cases, limitations etc. Don't you desire all those quality in anyone joining your team?

    ReplyDelete
  13. @Josef @Hemanth @Javin how could there be overflow in methods 1 & 3? I am new to computer science and just wondering.

    ReplyDelete
  14. @Anonymous1 :
    max value of int is 2,147,483,647 in java. So, when you do addition of two large numbers, you might get unexpected values because of over-flow.

    @Anonymous2 :
    This question was actually asked in my e-bay phone interview.

    ReplyDelete
  15. In Java you can use BigInteger to add extremely lager numbers.
    http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigInteger.html

    ReplyDelete
  16. ---------------
    String a;
    String b;

    Now do it. Fail.
    ---------------

    String a = "abc";
    String b = "def";

    System.out.println("\na: " + a + "\nb: " + b);
    b = a.length() + "_" + a + b;
    System.out.println("\na: " + a + "\nb: " + b);
    a = b.substring(Integer.parseInt(b.split("_")[0]) + b.indexOf("_") + 1);
    System.out.println("\na: " + a + "\nb: " + b);
    b = b.substring(b.indexOf("_") + 1, b.indexOf("_") + 1 + Integer.parseInt(b.split("_")[0]));
    System.out.println("\na: " + a + "\nb: " + b);

    ========
    Output:

    a: abc
    b: def

    a: abc
    b: 3_abcdef

    a: def
    b: 3_abcdef

    a: def
    b: abc

    Win.

    ReplyDelete
  17. @Hemanth, first method to swap two number is fine with Integer overflow, because overflow is clearly defined in Java and addition is cumulative operation. I did run with a case which overflow :

    //first method
    int a = Integer.MAX_VALUE;
    int b = 2;

    System.out.println("before, a: " + a+ " b: " + b);
    a = a + b;
    b = a - b;
    a = a - b;
    System.out.println("after a: " + a + " b: " + b);

    This is what I see :
    before, a: 2147483647 b: 2
    after a: 2 b: 2147483647

    On third method, there are couple of problems related to sign and divide by zero, which may come due to integer overflow.

    ReplyDelete
  18. @Anonymous, you can safely use 1st and 2nd code sample to swap two numbers in Java, they are free from Integer overflow. But, don't use this kind of swapping code to actually swap two values, It's not worth. In all cases temp variable should be used to swap numbers including integers, double or any floating point numbers.

    ReplyDelete
  19. Can I use these examples, to swap two numbers without using temp variable, in C, C++ or C#? Actually same question was asked but on C# interview.

    ReplyDelete
  20. What is the point of swapping two variables without temporary variable, making it unreadable, introducing new bugs and wasting CPU?

    ReplyDelete
  21. Another way ....
    --------------------------------
    import java.util.*;
    class StackEx {
    public static void main(String args[]) {
    int a=10,b=20;
    Stack st = new Stack();
    st.push(new Integer(a));
    st.push(new Integer(b));
    System.out.println("b value"+(Integer)st.pop());
    System.out.println("a value"+(Integer)st.pop());
    }
    }

    ReplyDelete
  22. Your Method #2 is one that I first used when doing assembly language progamming . . . in 1973. ;-)

    ReplyDelete
  23. You can achieve same with one liner:

    a = a + b - (b=a);

    ReplyDelete
  24. How to create a swap function for integers in java as there are no pointers in java and primitive data types are called value , not by reference

    ReplyDelete
  25. if one of the number is negative then what is the logic

    ReplyDelete
  26. guys, there is another alternative too :-
    int a = 10;
    int b = 20;
    a = ( a + b ) - ( b = a );

    P.S :- Taken from
    https://www.quora.com/Elegant-Code/What-is-the-most-elegant-line-of-code-youve-seen

    ReplyDelete
  27. @Ruks Shetty
    String a = "abcdefghijklmno";
    String b = "123456787654321";

    b = a + b;
    a = b.substring(a.length());
    b = b.substring(0, b.indexOf(a));

    ReplyDelete
  28. From a performance point of view, there is not much merit in doing a swap without using a third variable. If you study the bytecode that's generated for each of the methods, you will probably find that using a temporary variable generates the least number of bytecode instructions (6 as opposed to 12 or more). So, if you have something like this within a tight loop, use a third variable. While it's a cool idea, be sure to mention the downside to your interviewer.

    ReplyDelete
  29. If some interviewer asks me this question I will quit that interview and leave. This is so unreal and so academic if you are not hiring for some very specialised position, not to mention all that problems with overflow, performance etc...

    My brain is activelly refusing to waste precious time with problems like this and from my > 10 years programming experience this type of question will tell you nothing about your candidate and his programming skills and experience. And he is often to nervous to solve algorhitmical problems when sweatting in front of interviewer, if he will come up with absoluttely nothing, it doesnt mean he is very smart.

    Maybe that only thing you will learn if he will solve that right on place is that he is reading this blog regurally :)

    ReplyDelete
  30. As long as both String a & String b are not null. we can use the following to swap them:

    b = a + (a = b).substring(0, 0);

    ReplyDelete
  31. Method 2 is the best method. It uses very little space & is very fast. Method 3 will give a runtime error if b=0.

    ReplyDelete
  32. IIRC, while it's probably pointless on modern hardware, this used to be a way to save space when memory or registers were at a premium (ex. embedded systems, early computers with a few hundred bytes of RAM, etc.).

    ReplyDelete
  33. The purpose of these type of questions is only to test how you will perform when u r put in a situation that is outside your comfort zone !!! Will you panic? Will you revolt ? Will you remain indifferent ? or will you show leadership skills to address the situation ??? Thats about it dude ..

    ReplyDelete
  34. @Anonymous, you have summed it absolutely correct. I like one or two such interview question everytime, something which is new to candidate and gives him an opportunity to apply his knowledge in totally new problem.

    ReplyDelete
  35. how can we swap two characters without using 3rd variable?????

    ReplyDelete
  36. Does this work too?
    a^=b^=a^=b
    Sorry, i'm new to java.

    ReplyDelete
  37. I have a couple of questions on this:
    First : What's wrong in using temp for swapping? What's the advantage do we have without using temp?
    The question is about swapping two numbers; but the answers are given for integers. Except for the first one, would the others work for numbers of type float/double?

    ReplyDelete
    Replies
    1. They only work for integers, and the one that uses division fails for b=0. As someone noted, it also produces more code than a regular swap via temp variable, so it's useless.

      Delete
  38. Suppose I want to swap i and a[i] in an integer array
    temp=i
    i = a[i]
    a[i] = temp
    would work nicely.
    Would the following give the effect that I want to?
    =====
    a[i] = a[i] + i
    i = a[i] - i
    a[i] = a[i] - i
    =========

    Above All : I don't see any disadvantage in using temp that forms a universal solution to any primitive types.

    ReplyDelete
  39. Using bitwise operator(^) is better in performance wise. so go for bitwise operator

    ReplyDelete
  40. Toun, your logic will not work,
    As you said: a = b + 0 * (b = a);
    Let : a=2, b=3
    1st execute (b=a); //b=2
    then a = b + 0 * (b = a);
    a = 2 + 0 * 2;
    a=2;

    so here, value of "b" will bi swap but value of "a" remain as it is.

    ReplyDelete
    Replies
    1. Sir, then how is it that
      a=a+b-(b=a) works?
      Because, according to what you said, assignment happens first.

      a=2 b=3

      So, 1st execute (b=a); //b=2
      Then a=a+b-(b=a);
      a=2+2-2
      a=2
      Can you please explain?

      Delete
  41. I had this question asked in the first programming class I ever took - we weren't even learning a language, we just created flowcharts of a solution. The question as I heard it was output 2 values in ascending order without using a temp variable. The question is not about language skill, it is about thinking skill, so bitwise operators and multiplication and all the rest are not really the point.

    I think I ended up solving it by checking if the first number was larger than the second value, then output b, a otherwise output a, b.

    This was also asked in 3 different variants - first was output sorted values using 2 temp variables, next was output sorted values using one temp variable and the third was output sorted using no temp variables.

    ReplyDelete
  42. There is no way to judge a person based on this question. These type of questions are way too common and readily available on net. Its just chance and not skill. I got this swap integer question asked today. Had I looked in one of these interview guides, I would have easily answered it in a 3 to 4 mins spell. And the interviewer would have thought 'Oh this guy has good analytical skills'. Total bullshit. Interviewer should have asked or discussed some real-time scenario based questions, rather than picking some BS from the internet.

    ReplyDelete
  43. In bitwise swapping, if both values are equal, both values will become zero. so it should be handled.

    ReplyDelete
  44. @Javin.. Can you please explain what is the problem of overflow in method 1 & 3 and how can it be prevented using method 2?

    ReplyDelete
  45. int a = 10;
    int b = 20;
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("----------");
    b = b - a;
    a = a + b;

    System.out.println("a : " + a);
    System.out.println("b : " + b);

    ReplyDelete
  46. in multiplication and division process if we give any one of them value is zero(0) then it wont work

    ReplyDelete