Bernstein–Vazirani: finding a hidden string

A single quantum query recovers a hidden three-bit string that classical methods find one bit at a time.

Intermediate · 4 qubits · 10 gates · 2 two-qubit · depth 5 · reviewed November 2026

Open in the Circuit Builder

What is happening

The oracle computes the inner product of the input with a secret string s, modulo 2. A classical program must query once for each bit of s. The quantum circuit extracts the whole string in one query.

The secret here is 101, encoded by CNOTs from q0 and q2 to the helper qubit. The measurement of the three input qubits returns 101.

Step by step

  1. 1. Set up

    The helper q3 goes to |−⟩, and the three inputs go into superposition.

  2. 2. Oracle

    One CNOT for each 1 in the secret string. Bits that are 0 get no gate.

  3. 3. Read the answer

    H on the inputs and measurement reveal the secret string directly.

Expected result

Measured bits: 101 with 100% probability.

Qubit 0 is the leftmost bit. In Qiskit, bitstrings are printed in the reverse order.

Qiskit code

from qiskit import QuantumCircuit
from math import pi

qc = QuantumCircuit(4, 3)
qc.x(3)
qc.barrier()
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.barrier()
qc.cx(0, 3)
qc.barrier()
qc.cx(2, 3)
qc.barrier()
qc.h(0)
qc.h(1)
qc.h(2)
qc.barrier()
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)

# Qiskit prints bit strings with qubit 0 on the RIGHT; this site writes qubit 0 on the LEFT.

Try this

  • Change the secret to 110 by moving the second CNOT to q1.
  • Make the secret 111.
  • Count the gates for a 5-bit secret.

Gates used

Related reading

Questions

How does it differ from Deutsch–Jozsa?

It uses the same circuit shape with a different oracle, and it recovers a whole string, not just a yes-or-no property.