Quantum Builders ClubQiskit tutorials

Free Qiskit tutorial · Beginner

The Deutsch-Jozsa algorithm in Qiskit, step by step

Is a hidden function constant or balanced? A classical computer may have to check half its inputs plus one. Deutsch-Jozsa answers with a single query.

Start my 7-day free trialJump to the code

To work through
15 min
Level
Beginner
Tested on
Qiskit 2.6
Runs on your laptop
Free

The idea

Deutsch-Jozsa, in plain words

You're handed a black box, an oracle, that takes n bits and returns 0 or 1. You're promised it's either constant (the same answer for every input) or balanced (0 for exactly half the inputs, 1 for the other half). Which is it?

Classically you query inputs one by one, and in the worst case you need 2ⁿ⁻¹ + 1 of them. The quantum version queries every input at once in superposition. The oracle writes its answer into the phase of each input (phase kickback), and a last row of Hadamards turns those phases into one clear reading: all zeros means constant, anything else means balanced.

The code

The whole script, ready to run

Install Qiskit and its simulator once, save the script as deutsch_jozsa.py and run it with python deutsch_jozsa.py. It runs on Qiskit's free simulator, so you don't need an account or a quantum computer.

Install onceTerminal

pip install qiskit qiskit-aer

deutsch_jozsa.pyPython · Qiskit

from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator

n = 3   # input bits

def oracle(kind):
    """The black box f(x), on n input qubits and one output qubit."""
    qc = QuantumCircuit(n + 1)
    if kind == "constant":
        qc.x(n)              # f(x) = 1 for every input
    else:
        for q in range(n):   # balanced: f(x) = x0 XOR x1 XOR x2
            qc.cx(q, n)
    return qc

def deutsch_jozsa(kind):
    qc = QuantumCircuit(n + 1, n)
    qc.x(n)
    qc.h(range(n + 1))       # inputs into superposition, output into |->
    qc.compose(oracle(kind), inplace=True)
    qc.h(range(n))           # turn the phases back into bits
    qc.measure(range(n), range(n))
    return qc

sim = AerSimulator(seed_simulator=7)
for kind in ("constant", "balanced"):
    counts = sim.run(transpile(deutsch_jozsa(kind), sim), shots=1000).result().get_counts()
    verdict = "constant" if set(counts) == {"0" * n} else "balanced"
    print(f"{kind} oracle: {counts} -> {verdict}")

What it printedSeed 7 · 1,000 shots

constant oracle: {'000': 1000} -> constant
balanced oracle: {'111': 1000} -> balanced
Run on Qiskit 2.6 and Qiskit Aer 0.18. The simulator's seed is fixed, so on the same versions you'll see the same numbers.

What happened

What the output shows

The constant oracle gives 000 on every one of the 1,000 shots, and the balanced one gives 111 every time, never 000. One run of the circuit settles it, with certainty, where a classical program might need 5 of the 8 inputs.

The trick is the output qubit in |−⟩. When the oracle flips it, the state picks up a minus sign instead of changing, and that sign lands on the input that caused it. A constant oracle puts the same sign on every input, so the final Hadamards rebuild 000. A balanced one cancels 000 out entirely.

Deutsch-Jozsa solves a made-up problem, but its moves, superposition, an oracle, phase kickback and interference, are the same ones Grover's search and Shor's algorithm use.

Try next

Three things to try next

  • Write a different balanced oracle, say f(x) = x1 alone (qc.cx(1, n)), and check you still never see 000.
  • Raise n to 5 and see that it still takes one query, where the classical worst case grows to 17.
  • Print deutsch_jozsa('balanced').draw() and follow the minus signs gate by gate.

Take it further · Project 05

Build Grover's Search for real

Grover's search takes the same oracle and phase kickback and uses them to find a marked item in about √N tries instead of N. The project builds it from scratch, with tests.

Start my 7-day free trialSee the Grover's Search project

Questions

Deutsch-Jozsa in Qiskit

What does the Deutsch-Jozsa algorithm do?

It decides whether a function on n bits is constant or balanced with one query to the function. A deterministic classical algorithm needs up to 2ⁿ⁻¹ + 1 queries.

What is phase kickback?

When a controlled operation acts on a target in an eigenstate, such as |−⟩ for a NOT, the target stays the same and the phase lands on the control instead. Deutsch-Jozsa reads the function from those phases.

Is Deutsch-Jozsa useful in practice?

Not on its own: it solves a problem built to show a quantum speed-up. Its techniques are the foundation of useful algorithms like Grover's and Shor's.

Your first circuit is 10 minutes away

Stop watching quantum. Start shipping it.

Start my 7-day free trial

$0 today. 7 days free, then $7.99 a week or $190 a year. Cancel any time.

Detail C · A qubit's state