|q⟩ Bad Qubits

beginner · Programming · Controlled Gates: CNOT, CZ, SWAP

SWAP from Three CNOTs

The SWAP gate exchanges the states of two qubits:

SWAP00=00,SWAP01=10,SWAP10=01,SWAP11=11.\text{SWAP}\,|00\rangle = |00\rangle, \quad \text{SWAP}\,|01\rangle = |10\rangle, \quad \text{SWAP}\,|10\rangle = |01\rangle, \quad \text{SWAP}\,|11\rangle = |11\rangle.

Its 4×44\times 4 matrix in the computational basis {00,01,10,11}\{|00\rangle, |01\rangle, |10\rangle, |11\rangle\} is

SWAP=(1000001001000001).\text{SWAP} = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix}.

Many hardware architectures only provide the CNOT (CX) as their native two-qubit gate, so it is essential to know how to build SWAP from CNOTs.

The three-CNOT decomposition

The recipe is three CNOTs with alternating control and target:

SWAP01=CNOT(01)CNOT(10)CNOT(01).\text{SWAP}_{01} = \text{CNOT}(0\to1)\cdot\text{CNOT}(1\to0)\cdot\text{CNOT}(0\to1).

To see why this works, track an arbitrary computational basis state ab|ab\rangle through the three steps:

  1. CNOT(0→1): target qubit 1 is XORed with control qubit 0. ab    a,ba|ab\rangle \;\to\; |a,\, b\oplus a\rangle

  2. CNOT(1→0): target qubit 0 is XORed with qubit 1 (which now holds bab\oplus a). a,ba    a(ba),ba=b,ba|a,\, b\oplus a\rangle \;\to\; |a\oplus(b\oplus a),\, b\oplus a\rangle = |b,\, b\oplus a\rangle

  3. CNOT(0→1): target qubit 1 is XORed with the new qubit 0 (which is bb). b,ba    b,(ba)b=b,a|b,\, b\oplus a\rangle \;\to\; |b,\, (b\oplus a)\oplus b\rangle = |b,\, a\rangle

The final state is ba|ba\rangle — exactly the inputs swapped. Since the reasoning holds for all four basis states, and a unitary is completely determined by its action on a basis, the product of the three CNOTs is SWAP.

Try it

Build the SWAP gate by applying three CNOTs. The grader compares the full unitary matrix of your circuit against the SWAP matrix, so an empty or wrong circuit will fail.

Run your code to see the quantum state.

Sign in on the full site to ask questions and join the discussion.