Great Interview Question
So, how this for an interesting interview question:
You have two variables with integer values, without creating a third variable exchange their values.
At first it sounds fairly simple, but then it hits you that it’s actually not… there’s no simple ‘exchange value’ function. Here’s how I solved it:
list($a, $b) = array($b, $a);
My answer provoked a surprised (if not bemused) Yeah, that’d work… I’ve never heard that one before look. After a little conversation it turned out that the answer they were expecting but rarely got was:
$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
My answer is of course better, because it works with any type of variable, but what they were actually testing for was a logical brain that would solve the problem with simple maths… The fact that most candidates don’t even try answering the question goes to show how dastardly it is!
Comments
3 Responses to “Great Interview Question”
Leave a Reply
In Ruby:
a = 1
b = 2
a,b = b,a
puts a
puts b
Cheers
You can also use the XOR operation instead of addition subtraction.
a = a XOR b
b = a XOR b
a = a XOR b
done.
list($a, $b) = array($b, $a);
This is not valid answer. The PHP interpreter uses internal temporary variables to perform the “swap” operation shown.