DEV Community

Cover image for Swapping two numbers, w/o a temp variable

Swapping two numbers, w/o a temp variable

Morten Olsrud on October 14, 2019

Todays post will be a short one, but one that covers a really simple algorithm that still might stump you in an interview setting if you don't have...
Collapse
 
philnash profile image
Phil Nash

What if summing a and b leads to a number that is larger than the maximum integer? This would cause an overflow.

I’d hate for an interview trick like this to lead to real world problems. This is the same issue that was present in every incorrect binary search function (see “implementation issues”).

Collapse
 
peledzohar profile image
Zohar Peled

Totally agree. Interview tricks should never find their way into production code. In fact, I think that's one of the worst problems in software development technical interviews today - the fact that the problems asked and the solutions expected are in no way applicable in real world situations.

Collapse
 
hakash profile image
Morten Olsrud

Couldn't agree more, but because they do, and because we love Code Wars and similar code quiz sites, discussing these tricks are still needed, and for me at least, fun 😊

Thread Thread
 
peledzohar profile image
Zohar Peled

Yeah, it is fun.

Collapse
 
kebby profile image
Tammo 'kb' Hinrichs • Edited

That's why you usually use XOR for the swap trick :)

a^=b;  // a' = (a^b)
b^=a;  // b' = b ^ (a') = b ^(a^b) = a
a^=b;  // a'' = a' ^ b' = (a^b)^a = b
Collapse
 
philnash profile image
Phil Nash

Yeah, but not in real code! I'd prefer it were readable over assigning one extra variable. You've got to find some specific conditions to make this the better code to use!

Thread Thread
 
kebby profile image
Tammo 'kb' Hinrichs

I actually used this in real code once, in an assembly inner loop where I was really running out of registers :), but you're right of course.

Related question: Did anyone here ever have to reverse a string? :D

Thread Thread
 
hakash profile image
Morten Olsrud

Not in an interview, but in a quiz somewhere. It was an entry level one so only restriction was to not use the built in functions.

Collapse
 
marcoslooten profile image
Marco Slooten

Cool way of doing that 🙂

I was immediately thinking about this in JavaScript specifically. You could also use array destructuring to get the same result:

[a, b] = [b, a];
Collapse
 
thepeoplesbourgeois profile image
Josh

Ruby, too! It's been possible at least since 1.8

a, b = b, a
Collapse
 
donut87 profile image
Christian Baer

Oh dear...
The task was to do this "without extra space" and not "don't use an extra variable". Both your solutions fail that. Constructing two arrays is definitely extra space used, you just won't see it in your code.
I don't know what Ruby does, but I can imagine, that this will create some variable 'behind the scene' or will also have to arrays constructed.
I am very sorry, but you both failed the test.
This is not very bad though. In real life you only need to know this kind of 'tricks' when you have very limited hardware like small chips in small devices such as smart lamps or smoke detectors. Also in most applications you probably won't need to switch the values of two variables.

Thread Thread
 
thepeoplesbourgeois profile image
Josh

As always, this is why it's important to understand what the language is doing before calling somebody wrong 🙂

Y'see, no variable in Ruby ever holds the object in question, but instead holds a reference to the object. a, b = b, a tells Ruby to place a reference to whatever is referenced by b at the time of invocation inside of the reference a, and whatever is referenced by a at the time of invocation inside of the reference b. No array construction, no invisible intermediary variable, just happy-go-lucky references, reassigning themselves to the underlying addressed memory locations.

Thx 4 the patronization tho! 💖💖😘

Thread Thread
 
donut87 profile image
Christian Baer

As I said, I am not sure what Ruby does and how this parallel assignment really works under the hood.
For the python example (and this was the main focus), my statement holds :-). It's a construction of an array (list), that is assigned to another list and afterwards deconstructed.

Thread Thread
 
thepeoplesbourgeois profile image
Josh

Good try, but no. "You both fail" is geared quite equally toward two intended audiences. Again, understand what the language is doing before you call someone wrong 😊

Collapse
 
clavinjune profile image
Clavin June • Edited

Why don't u use XOR operator?
a = a XOR b
b = a XOR b
a = a XOR b

Collapse
 
hakash profile image
Morten Olsrud

Cool trick!

Collapse
 
mateiadrielrafael profile image
Matei Adriel

In js u can use ^ as xor

Collapse
 
joelnet profile image
JavaScript Joel

Swapping two objects, w/o a temp variable

const K = a => b => a

let a = 'A'
let b = 'B'

a = K(b)(b = a)

a //=> 'B'
b //=> 'A'
Collapse
 
glyphcat profile image
GlyphCat

Hmm… what if the variables are of other data types? Just making a guess tho, do people convert those data into bytes then perform the same math?

Collapse
 
hakash profile image
Morten Olsrud

I wouldn't expect people to actually do this, it's more of a puzzle to see if you are able to think outide the box I think.

Collapse
 
mateiadrielrafael profile image
Matei Adriel

To be honest we were teached this in the first week of high school in our c++ class:)

Collapse
 
hakash profile image
Morten Olsrud

Well, I guess it varies from country to country, and school to school, plus, a lot of us does not have a Bachelor or better in anything 😊 We still lovez us some codez tho! 😉

Collapse
 
mateiadrielrafael profile image
Matei Adriel

Yeah, i said it as a fun fact:)

Collapse
 
moopet profile image
Ben Sinclair

If someone asked me this in an interview, I'd ask them for an example of where they used it in their production code.

Collapse
 
thejoezack profile image
Joe Zack

Nice trick!

Collapse
 
hakash profile image
Morten Olsrud

Thanks!

Collapse
 
harinsimhadri profile image
Something Unusual

Python
a, b = b, a

Collapse
 
hakash profile image
Morten Olsrud

Cool!

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
nyc4m profile image
Baptiste Prunot

Seems to work perfectly fine 🤔