Dark Mode On/Off

Posted in Tricks
LAST UPDATED: AUGUST 27, 2021

Suppose we have been given three variables, and we have been asked to swap them, with a condition that any temporary variable shouldn't be used, what would your approach be?

We will show you a few approaches which can be used to achieve the same.

__ Sample input:__ a = 3, b = 7, c = 0

__ Sample output:__ a = 0, b=3, c = 7

The idea is to sum two numbers and store them in one variable. The other variable can be found by subtracting the value to be found from the sum.

Let's see this with help of an example,

```
a = 11
b = 89
c = 37
print("Before swapping a = ",a,", b = ",b,", c = ",c)
a = a + b + c
b = a - (b+c)
c = a - (b+c)
a = a - (b+c)
print("After swapping a = ",a,", b = ",b,", c = ",c)
```

**Output:**

Before swapping a = 11 , b = 89 , c = 37 After swapping a = 37 , b = 11 , c = 89

__ Note:__ An important point to note here is that when the variables hold large values, the above method causes the stack to overflow. The solution to this is to use a different method when encountering large values.

The only catch here is to store every integer value as a list data structure since every bit needs to be manipulated.

```
a = [11]
b = [89]
c = [37]
print("Before swapping a = ",a,", b = ",b,", c = ",c)
a[0] = a[0] ^ b[0] ^ c[0]
b[0] = a[0] ^ b[0] ^ c[0]
c[0] = a[0] ^ b[0] ^ c[0]
a[0] = a[0] ^ b[0] ^ c[0]
print("After swapping a = ",a,", b = ",b,", c = ",c)
```

**Output:**

Before swapping a = [11] , b = [89] , c = [37] After swapping a = [37] , b = [11] , c = [89]

Also, this technique works for integer values. If you add more than one integer value in the list only the first integer value will be swapped.

In this post, we understood how three variables can be swapped without the usage of a temporary variable in Python. This is quite a frequent trick question in interviews. Do let us know in the comment section below about your method.

Tags:**Python**

Try out our __Interactive Courses__ for Free 🥳 😯 🤩

RECENT POSTS

Make your Docker images slimmer!

How to install PHP Redis extension in macOS or Macbook?

[SOLVED] Failed to parse URI options: Failed to look up SRV record - MAMP Server

[SOLVED] fatal error: 'pcre2.h' file not found - macOS/Macbook (M1/M2 chip)

Best Web Development Tools to Use in 2023

Best Full Stack Web Development Courses [Free & Paid]