Skip to content

Volume ITechnology

4.0.1 — Swap Two Variables Without a Third ​

Classic · Easy · the most common opening question in service-company rounds

The problem ​

You have a = 5 and b = 9. Swap them, so a becomes 9 and b becomes 5. You are not allowed to use a third variable.

Why this is even a question ​

The normal way to swap uses a temporary variable.

python
a, b = 5, 9
temp = a     # temp = 5. Save a before we lose it.
a = b        # a = 9. The old 5 would be gone without temp.
b = temp     # b = 5
print(a, b)  # → 9 5

Why ban temp? The interviewer wants to see if you know one simple fact. If you keep the sum of two numbers, you can always get either number back, as long as you still have the other one. For example, if the sum is 14 and one number is 9, the other number must be 5.

Method 1 — Python's own way ​

python
a, b = 5, 9
a, b = b, a
print(a, b)  # → 9 5

Python builds the right side first. It makes a pair holding the two current values, (9, 5). Only after that does it assign the pair's first value to a and the second to b. Nothing is overwritten while it is still needed.

Does this secretly use a third variable? A little. Python makes a small pair for a moment, then throws it away. You can say this in the interview. Then show the two methods below, because those are what most interviewers expect.

Method 2 — Addition and subtraction ​

python
a, b = 5, 9
a = a + b   # (1) a = 14, b = 9
b = a - b   # (2) a = 14, b = 5
a = a - b   # (3) a = 9,  b = 5
print(a, b)  # → 9 5

(1) Store the sum in a. The old value of a is now gone as a separate number. But it is not lost, because a holds the sum and b still holds 9. Anyone holding the sum and one of the numbers can work out the other.

(2) Sum minus the original b leaves the original a. Put that in b. Now b is 5.

(3) Sum minus the original a (which now lives in b) leaves the original b. Put that in a. Now a is 9.

Where this breaks. In Python it never breaks, because Python integers grow as large as needed. In C, C++ or Java, an int holds only 32 bits, so its largest value is 2,147,483,647. If a and b are both around 2 billion, a + b does not fit. The value wraps around to a negative number. This is called overflow. Mention it in an interview, because integers in Java and C have a size limit and Python's do not.

A multiplication version also exists: a = a * b; b = a // b; a = a // b. It fails completely when either number is 0, because you cannot divide by 0. It also overflows faster. Avoid it, and say why.

Method 3 — XOR ​

This is the method most interviewers expect. It uses one new operator.

XOR (written ^ in Python) compares two numbers bit by bit. A bit is one binary digit, 0 or 1. For each position, XOR gives 1 if the two bits are different and 0 if they are the same.

  5 = 0101
  9 = 1001
5^9 = 1100  = 12

Three facts about XOR make the swap work. Each is easy to check bit by bit.

  1. x ^ x = 0. Every bit is the same as itself, so every result bit is 0.
  2. x ^ 0 = x. XOR with 0 changes nothing.
  3. Order does not matter, and grouping does not matter. x ^ y equals y ^ x.

From these three, one useful rule follows. If you XOR a number in twice, it cancels out. For example (a ^ b) ^ b becomes a ^ (b ^ b), which is a ^ 0, which is a.

python
a, b = 5, 9
a = a ^ b   # (1) a = 5^9
b = a ^ b   # (2) b = (5^9)^9 = 5
a = a ^ b   # (3) a = (5^9)^5 = 9
print(a, b)  # → 9 5

(1) a now holds the combined value, 5 ^ 9, which is 12. This is just like the sum in Method 2.

(2) XOR the combined value with 9. The 9 appears twice, so it cancels. What is left is 5. Store it in b.

(3) XOR the combined value with 5, which now sits in b. The 5 cancels. What is left is 9. Store it in a.

The table traces the bits.

Stepa (binary)b (binary)
start0101 (5)1001 (9)
after (1)1100 (12)1001 (9)
after (2)1100 (12)0101 (5)
after (3)1001 (9)0101 (5)

XOR never overflows. Each bit is handled on its own, with no carry into the next bit, so the result never needs more bits than the inputs had.

A mistake almost everyone makes ​

Suppose you write a swap function for two positions of a list, using XOR.

python
def xor_swap(arr, i, j):
    arr[i] = arr[i] ^ arr[j]
    arr[j] = arr[i] ^ arr[j]
    arr[i] = arr[i] ^ arr[j]

nums = [7, 3]
xor_swap(nums, 0, 0)   # swap position 0 with itself
print(nums)            # → [0, 3]

The 7 became 0. Why? When i and j are the same position, the first line computes 7 ^ 7, which is 0. It stores that 0 in the one place both names refer to. The original 7 is now destroyed, and nothing can bring it back. The same bug hits the addition method: arr[i] = arr[i] + arr[i] then arr[i] - arr[i] gives 0.

This really happens. Sorting and shuffling code often ends up swapping a position with itself. The fix is a guard: if i != j: before the three lines. If you mention this case yourself, the interviewer will know you really understand the method.

Complexity ​

Every method is O(1) time and O(1) memory. Three fixed operations, no matter what the numbers are.

Which one to use in real code ​

Use a, b = b, a in Python. Use a temporary variable in other languages. The XOR swap is not faster on modern processors. The three steps each depend on the one before, so the processor cannot do them at the same time. A temporary variable usually lives in a register, which is free. The XOR swap is an interview idea and a lesson about bits, not a speed trick.

What the interviewer will push on ​

These are the questions that usually come right after you solve it. Each one has a short, plain answer you can say out loud.

"Does a, b = b, a use any extra memory?" A tiny bit. Python first makes a small pair, (b, a), and then unpacks it into a and b. The pair is thrown away straight after. So it is not "zero memory", but it is a fixed, tiny amount.

"What goes wrong with the addition method in Java or C?" The sum a + b can be too big to fit. A Java int holds numbers only up to about 2.1 billion. If both numbers are around 2 billion, the sum does not fit. This is called overflow. Python never has this problem, because its integers grow as big as needed.

"Why does the XOR method work?" Because XOR-ing the same number twice cancels it out. x ^ x is 0, and x ^ 0 is x. So (a ^ b) ^ b gives back a. The three XOR lines use this to pull each number back out.

"You wrote a function that swaps two positions of a list with XOR. When does it break?" It breaks when both positions are the same, like xor_swap(nums, 2, 2). The first line does x ^ x, which is 0. That 0 is written into the only copy of the number. The number is lost. The fix is to check if i != j before swapping.

"Is the XOR swap faster than using a temporary variable?" No. On modern computers the temporary-variable swap is as fast or faster. The XOR swap is a puzzle that teaches how bits work. It is not a speed trick.

One thing to volunteer: "In real Python code I would always write a, b = b, a. The XOR version is useful to understand bits, but it is slower and it breaks when you swap a value with itself."

Next: 4.0.2 First Warm-Ups. Even or odd, leap year, the largest of three, and FizzBuzz. All four are quick, but each has one detail people get wrong.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet