DEV Community

Cover image for How can you swap two variables without using a third?
Nick Karnik
Nick Karnik

Posted on • Updated on

How can you swap two variables without using a third?

Moore's law is just an observation and not a real law like the Law of Gravity.

Over the years, developers have taken the increasing CPU speeds and Memory sizes for granted. Here's a warm-up interview question that I ask every candidate.

Let's assume the working memory for your function is 8-Bytes. You are given two 32-Bit Integers and you need to swap them. In other words, how can you swap two variables without using a third?

Please take your time to solve this and refrain from looking up solutions online or for answers below. This is your first step in becoming a Computer Scientist!


If you accepted this challenge, ❤️ it and follow me on Twitter.

Latest comments (122)

Collapse
 
isenthil profile image
Senthil Kumar

Here's my code snippet showing how we can swap two numbers without using temporary variable at coderseditor.com/?id=185

using System;

namespace CodeSample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Swap Number Sample");
int number1, number2;
Console.WriteLine("Enter the First Number : ");
number1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Second Number : ");
number2 = int.Parse(Console.ReadLine());
number1 = number1 - number2;
number2 = number1 + number2;
number1 = number2 - number1;
Console.WriteLine("First Number is " + number1);
Console.WriteLine("Second Number is " + number2);
Console.Read();
}
}
}

Collapse
 
moopet profile image
Ben Sinclair • Edited

Here's a warm-up interview question that I ask every candidate.

I've seen this question come up a lot, along with fizzbuzz or "write a sorting function" and I'm not sure it's useful anymore.

It's a purely academic problem that touches on several different concepts, none of which are going to be used by 99% of programmers these days.

Why do you ask this question? What do people's different answers tell you, or are you more looking for how people attempt to solve it (if they've not heard it before) or how quickly they regurgitate a stock solution (if they have?)

If I asked this, and someone answered quickly (they already know why the dead man in the desert is lying next to an unopened pack...) then I'd follow up with something asking when they had ever had to do this in real life, or even if they could come up with three examples of situations where it would be a useful thing to do in real life. If they couldn't, then I don't think I would have learned anything useful about them.

What do you get out of it?

Collapse
 
theoutlander profile image
Nick Karnik

Good question! I used to ask this as a warm-up question back in the days at the beginning of an interview. (However, I've also used it in recent interviews after this post). I've never used this question to influence the outcome of the interview. It's merely conversational and a segue into academics to pique their interest into a deeper technical conversation.

If the candidate has heard the question before, I will follow up with a question around if the solution handles overflow when numbers are large and also dive a bit into perf. We may dive into when and if this solution might be needed for specific use-cases. The reality is that the compiler optimizes the code better when using a temporary variable.

If they haven't heard the question before, it gives me a chance to assess how they work through the problem and helps me find an appropriate role for them if the interview is somewhat generic. If they dislike that problem or find it difficult to solve it, they are most likely not going to enjoy working on hardware/firmware. Most people who solve it really enjoy the problem and in my experience have performed quite well on the job.

Recently, I observed that this question is part of the prep material online and most people have seen it, so there's not much value in asking it. I still do it for fun sometimes.

Anyway, I agree with your comment though.

Collapse
 
sivaiah587 profile image
sivaiah587

JAVA

int a=5;
int b=10;
a=a+b;
b=a-b;
a=a-b;
System.out.println(a);//10
System.out.println(b);//5
String s1="java1";
String s2="java2";
s1=s1+s2;
s2=s1.substring(0,(s1.length()-s2.length()));
s1=s1.substring(s2.length());
System.out.println(s1);//java2
System.out.println(s2);//java1

Collapse
 
dhilipkmr profile image
Dhilip kumar

If there are two variables a and b we could destructure them.

var a = 12;
var b = 21;
[a, b] = [b, a];

Values are interchanged :)

Collapse
 
siatwe profile image
Simon Weis • Edited

A = 00000000000000000000000000101010
B = 00000000000000000000000001111110

A = A or B = 00000000000000000000000001111110
B = A and B = 00000000000000000000000000101010

Collapse
 
andruallen profile image
AndruAllen

With non-blocking assignment to describe hardware in Verilog:

x <= y;
y <= x;

asic-world.com/tidbits/blocking.html

Collapse
 
liloow profile image
Tom

No need to go very far... and it will never cause overflow

x.__proto__.y = y
y.__proto__.x = x
x = x.y 
y = y.x
Collapse
 
suncheeze profile image
Alexander Parshin

Move data to upper and lower RAX then ROL by 32

Collapse
 
theoutlander profile image
Nick Karnik

Your comments appear incorrect.

y = y-x is basically the difference between y and x and not -x.

You might want to try this solution in code for correctness.

Collapse
 
eerk profile image
eerk

The Law of Gravity is also just an observation :)

Collapse
 
m242 profile image
m242

if (y > x){
x += (y-x)/2;
y = 2*(y-x)
x += x-y

}
else if (y < x){
y += (y-x)/2;
x = 2*(y-x)
y += x-y

}

Probably not the best way ...

Collapse
 
theoutlander profile image
Nick Karnik

You might want to try it in a language of your choice. If it works, it's a very good first step. Then, you can think of optimizing it.

Collapse
 
kodejuice profile image
Sochima Biereagu • Edited
x = y + x - (y = x)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
juanfrank77 profile image
Juan F Gonzalez

By using the ES6 destructuring assignment, that's how I would do it.

Collapse
 
theoutlander profile image
Nick Karnik

Does this solution meet memory constraints?

Collapse
 
juanfrank77 profile image
Juan F Gonzalez

In general, it does unless you're talking about very large ones.

Collapse
 
joelnet profile image
JavaScript Joel • Edited

You could use the K combinator to swap any value, not just numbers!

let a = "hello"
let b = "goodbye"

a = (x => () => x)(b)(b = a)

a // => "goodbye"
b // => "hello"
Collapse
 
idanarye profile image
Idan Arye
void swap(int* a, int* b) {
    write(open("swapfile", O_WRONLY | O_SYNC), a, sizeof(*a));
    *a = *b;
    read(open("swapfile", O_RDONLY), b, sizeof(*b));
}
Collapse
 
sriharsha32 profile image
SriHarsha Sreenath

Love your thinking. Nobody ever said you can't write to file and read it back :D

Some comments may only be visible to logged-in visitors. Sign in to view all comments.