WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Coding Interview Essentials · Bit Manipulation Problems · question 83 of 120

How would you swap the values of two integers without using any additional variables?

📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

Swapping the values of two integers without using any additional variables can be achieved using mathematical operations. Here’s how you do it.

Let’s say you are given two integers ‘a‘ and ‘b‘.

The first step is to store the sum of ‘a‘ and ‘b‘ in ‘a‘. This makes ‘a‘ carry both the information of ‘a‘ and ‘b‘.


a = a + b

Now, ‘a‘ is equivalent to ‘a+b‘. To get ‘b‘ from ‘a‘, subtract the original ‘b‘ from ‘a‘:


b = a − b

Given that ‘a‘ was ‘a+b‘, ‘b‘ now becomes ‘a‘.

Finally, to get ‘a‘, subtract the new ‘b‘ (previously ‘a‘) from ‘a‘:


a = a − b

This series of operations effectively swaps ‘a‘ and ‘b‘ without using any temporary variables.

Here’s a sample code that demonstrates this procedure:

def swap(a,b):
    a = a+b
    b = a-b
    a = a-b
    return a,b

print(swap(3,4))

This code swaps ‘a‘ and ‘b‘ in place without creating additional variables. Please note that this is really more of a programming puzzle solution and may not be the best solution when taking considerations of performance, potential Overflow risk and readability in real-world cases.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview — then scores it.
📞 Practice Coding Interview Essentials — free 15 min
📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

All 120 Coding Interview Essentials questions · All topics