The Challenge

You have two numeric variables

e.g.

let a = 1;

let b = 2;

They need to be swapped, so that:

a === 2

b === 1

 

Simple Swap – No Restrictions

Solution Strategy

Since there are no restrictions, why not just introduce a third variable as temporary storage?

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”LrMvWo” default_tab=”js,result” user=”gilst” preview=”true” data-preview=”true”]See the Pen <a href=’https://codepen.io/gilst/pen/LrMvWo/’>Simple Swap</a> by Gil (<a href=’https://codepen.io/gilst’>@gilst</a>) on <a href=’https://codepen.io’>CodePen</a>.[/codepen_embed]

Easy peasy. Moving on.

Numeric Swap – Using only A and B

Solution Strategy

The variables serve as storage and you don’t have any storage, so one will need to contain both somehow with the ability to extract the original values.

Hint

What happens when you combine both values? You’re left with the combined value on the one hand and one part of the combined value on the other. Can that be served to determine both values in reverse?

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”KeJwvy” default_tab=”js,result” user=”gilst” preview=”true” data-preview=”true”]See the Pen <a href=’https://codepen.io/gilst/pen/KeJwvy/’>Numeric Swap</a> by Gil (<a href=’https://codepen.io/gilst’>@gilst</a>) on <a href=’https://codepen.io’>CodePen</a>.[/codepen_embed]

Note: this solution is very likely to appear in code interviews. Want to make the interviewer feel a bit less confident? Ask to check this using a=0.1 and b=0.2 and prepare yourself for a good laugh on the interviewer’s expense…

String Swap – Using only A and B

Solution Strategy

Again we’ll need to store the combined value of both vars inside one of them and then extract the information somehow. This time we’ll need to employ some string related functions.

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”WyPbdE” default_tab=”js,result” user=”gilst” preview=”true” data-preview=”true”]See the Pen <a href=’https://codepen.io/gilst/pen/WyPbdE/’>String Swap</a> by Gil (<a href=’https://codepen.io/gilst’>@gilst</a>) on <a href=’https://codepen.io’>CodePen</a>.[/codepen_embed]

 

Any Swap – Swap Any Two Variables

Solution Strategy

You can’t assume anything, so combining the vars is out of the question. At least not directly…

Hint

Would it be possible to convert the var types without losing their original values?

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”mKvyXP” default_tab=”js,result” user=”gilst” preview=”true” data-preview=”true”]See the Pen <a href=’https://codepen.io/gilst/pen/mKvyXP/’>Any Swap</a> by Gil (<a href=’https://codepen.io/gilst’>@gilst</a>) on <a href=’https://codepen.io’>CodePen</a>.[/codepen_embed]

Categories: Algorithms

Leave a Reply

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