Lecture 3 - Quantum Algorithm and State Preparation
1. Introduction
Quantum Algorithm
- A quantum algorithm is a circuit of quantum logic gates for manipulating qubit-based information to achieve desired computation.
Quantum algorithm like a electronic circuit, but it just only a program
-
- Preparation: convert input into quantum states, superpositions, and entanglement
-
- Computation: via state manipulation, conditions, loops, reflections, and phase estimation
-
- Measurement: measure the probability distribution for each quantum state
Caption — Figure 1: Overview of a quantum algorithm. A row of qubits, all initialized to , passes through a "STATE PREPARATION" block, then a "STEP-BY-STEP INSTRUCTIONS" (computation) block, and finally each wire ends at a Detector — the measurement stage.
💡 Analogy: Think of a quantum algorithm like a recipe with exactly three phases: (1) get your ingredients into the right starting mix (preparation), (2) follow the steps that transform them (computation), and (3) taste the final dish and report what you got (measurement) — except "tasting" here means sampling from a probability distribution, not reading off one guaranteed answer.
PennyLane
- Popular library for quantum computing in Python, developed by Xanadu
- Features:
- Easy to use with a low learning curve
- Support for CPU-based and GPU-based quantum simulation
- Plugins for actual QPUs, e.g. IBM Qiskit, Amazon Braket, and Xanadu
- Support for automatic JIT compilation of quantum algorithms in the entire quantum-classical workflow
- The URL is https://pennylane.ai/
Basic installation
pip install pennylaneOn a CUDA-enabled machine
pip install custatevec_cu12
pip install pennylane-lightning-gpuOn CUDA Tensor Networks
pip install cutensornet-cu12
pip install pennylane-lightning-tensorDocker
docker pull pennylaneai/pennylane:latest-lightning-qubitExample Code
import pennylane as qml # Quantum computing
from pennylane import numpy as np # Classical computing
# Quantum device with two wires (i.e. variables)
dev = qml.device('default.qubit', wires=[0, 1]) # connect to real quantum computer
dev = qml.device('default.qubit', wires=["q1", "google", "9arm", "3arm"])
# This is our simple quantum algorithm
@qml.qnode(dev)
def circuit(theta: float):
# State preparation
qml.H(wires=[0]) # Hadamard gate on qubit-0
# Computation
qml.RY(theta, wires=[0]) # Rotate qubit-0 on Axis-Y by theta
qml.CNOT(wires=[0,1]) # Controlled NOT on qubit-1 with control qubit-0
# Measurement
return qml.state()
# Let's run our quantum algorithm
print(circuit(np.pi / 6))Code Skeleton
Header
import pennylane as qml
from pennylane import numpy as npQuantum device
dev = qml.device('default.qubit', wires=...)Several quantum devices are also available.
default.qubit: Simple simulatordefault.mixed: Mixed-state simulatorlightning.qubit: C++-based simulatordefault.tensor: Tensor Networks
Quantum algorithm = quantum node
- Preparation = variable initialization
- Computation = sequence of logic gates
- Measurement = collapsing quantum states to a bitstring
@qml.qnode(dev)
def circuit(args):
# State preparation
......
# Computation
......
# Measurement
return ......2. Clifford Set/1
Related
Clifford Set of Quantum Logic Gates
These gates are very stable, we don’t need the big refrigerator to freeze them (room temperature is okay). Non-clifford needs refrigerator.
- A set of basic quantum logic gates
- Fault-tolerant: Hardware implementation of these gates can significantly tolerate noise and quantum decoherence
- Self-inversible: Applying a quantum operator twice on a state results in the original one
- Efficiently simulatable: They can be emulated in polynomial time by probabilistic classical computers
- The main purpose of the Clifford set is state preparation
- A quantum algorithm that consists of only Clifford gates is sometimes called a stabilizer circuit due to its stability
- In this chapter, we will divide them into three levels:
Table 1: Clifford set of quantum logic gates
| Level 1 | Level 2 | Level 3 |
|---|---|---|
| NOT | Pauli X | Swap |
| Hadamard | Pauli Y | Controlled Z |
| Phase shift | Pauli Z | |
| Controlled NOT |
💡 Analogy: "Fault-tolerant, self-inversible, efficiently simulatable" is basically physics' way of saying "sturdy, reversible, and cheap to double-check on a normal computer" — which is exactly why these particular gates are the trusted toolkit for the fiddly job of state preparation, before the "real," harder-to-simulate computation begins.
Level 1: NOT Gate
- NOT gate converts to and vice versa, similar to logical NOT

Circuit:

(Figure 2: NOT gate)
📝 Instructor's annotation:
The eigenvectors of directly under the "self-inversible" line: and bracketed the two together, labeled "computational basis and ." — i.e. 's own eigenvectors are nothing exotic, just the two states you already know.
- is self-inversible:
- is often used for preparing
qml.X(wires=…)

- อ่อ พอจะเริ่ม get ทุกอย่างแล้ว 5555, คือจริง ๆ แล้วตัวมันเป็น Matrix ที่ apply ไปแล้วจะได้ค่าออกมาเป็น output แต่การจะสร้างอันนี้ออกมาได้ก็จาก state mapping ไง ว่าเราต้องการอะไรออกมาเป็นอะไร
Level 1: Hadamard Gate
📝 Instructor's annotation: next to the slide title, wrote a phonetic pronunciation guide — [HAH-də-mar]— for "Hadamard."
- Hadamard gate converts pure states to superpositions and vice versa
📝 "State mapping:"
- is self-inversible:
- Hadamard gate is often used for preparing a superposition
qml.H(wires=…)- Let's define the superposition bases
📝 Instructor's annotation: bracketed both formulas together and labeled them "Eigenvectors of H."
Circuit:

(Figure 3: Hadamard gate)
ไอ่ตัว อันนี้ไงที่คือ Superposition เป็นสอง state ในเวลาเดียวกัน เรา define มันเป็นบวกกันไปเลย5555
💡 Analogy: is the quantum coin-flipper: feed it a definite or and it spreads the state into an even 50/50 superposition (with a sign on the term when starting from ). Do it twice and — like flipping a coin, then "un-flipping" it — you land back where you started.
This demonstrates that the Hadamard gate is unitary and self-inverse (), meaning applying it twice returns the qubit to its initial state.
Level 1: Phase Shift Gate
- Phase shift gate converts real numbers to imaginary numbers and vice versa
"State mapping:"
= (change the phase of ket 1, to become , 90°)
-
is equivalent to sign flipping: ,
-
qml.S(wires=…) -
Let's define the circular bases
📝 Instructor's annotation: bracketed both formulas together and labeled them "Eigenvectors of S."
Circuit:

(Figure 4: Phase shift gate)
Level 1: Controlled NOT
Meaning na krub: If the 1st qubit is one, you flip the 2nd qubit
(take first qubit 1st control)
- Controlled NOT is a condition tester, where the second qubit is bit-flipped if the first qubit is
"State mapping:"
#MidtermExam question, will look something like this

- CNOT is equivalent to logical XOR :
- CNOT combined with creates various forms of entanglement
- CNOT is also self-inversible:
qml.CNOT(wires=…)
Circuit: qubit (the control) passes through unchanged; qubit (the target) comes out as . (Figure 5: Controlled NOT gate)

dark circle mean control (if it’s 1), ส่วน oplus ข้างหลัง หมายถึง bit flip ซะ
On the #MidtermExam, he might put the control on the down, and bit flip on the above, don’t be fooled by that (he mentioned suspiciously, that it might actually end up on the actual exam)
Also one more notation is that above may have blank (white) circle means that control is zero

ก็คือถ้าเป็น 0 ให้เปลี่ยน Bit ต่อมาละ - มันก็กลับมุมมองอะไรงี้แหละ
💡 Analogy: CNOT is a quantum "if–then" switch — qubit is the control (left untouched), qubit is the target. If the control reads , flip the target; if it reads , leave it alone. Paired with a Hadamard on the control, it's the standard recipe for cooking up entanglement.

Summary of Level 1
Table 2: Basic Clifford gates
| Gates | Descriptions | Symbols = Formulae |
|---|---|---|
| NOT gate | Bit-flip the input qubit, similar to the logical NOT. | |
| Hadamard gate | Convert pure ↔ superposition on the input qubit. | |
| Phase shift gate | Convert real ↔ imaginary if the input qubit is 1. | |
| CNOT gate | Bit-flip the second qubit if the first one is 1. Create an entangled state when used with the Hadamard gate. |
Special Unitary Group
- Special unitary group : the set of complex matrices that are unitary and special
- Formal definition:
Table 3: Clifford set and their SU groups
| Quantum Gates | Groups |
|---|---|
| NOT gate | |
| Hadamard gate | |
| Phase shift gate | |
| CNOT gate |
- Why mentioning this?
- Unitary (): All of these matrices are quantum operators
- Special (): All of these matrices do not change the global phase
Quantum Algorithm: Example 1

Caption — Figure 6: "Just a quantum algorithm" — a 2-wire circuit ( on qubit 1, then and on qubit 2, then a CNOT joining both), with each intermediate state () labeled directly above the wires at the point in the circuit where it occurs.
- Step 0: The initial state is always .
- Step 1: Apply the Hadamard gate on the first qubit.
- Step 2: Apply the NOT gate on the second qubit.
- Step 3: Apply the phase shift gate on the second qubit; yields .
- Step 4: To apply CNOT, we first realize the tensor product of its inputs.
- Trick: if all quantum gates are single qubit, don’t have to expand
- But when muti-qubit showed up, you need to expand #MidtermExam (maybe this is the hard question he mentioned about)
- Step 4 (cont'd): Applying CNOT on yields
Note that the output now becomes an entangled state. The entanglement is denoted with a bidirectional arrow between the two qubits. (ถ้า reduce มาถึง bell state ขนาดนี้ก็สุดยอด แต่ติดไว้ข้างบนพอก็ได้)
Example 1 in PennyLane
import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit', wires=[0, 1])
@qml.qnode(dev)
def circuit():
# State preparation
qml.H(wires=[0])
qml.X(wires=[1])
qml.S(wires=[1])
qml.CNOT(wires=[0, 1])
# Measurement
return qml.state()
print(circuit())import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit', wires=['q1', 'q2'])
@qml.qnode(dev)
def circuit():
# State preparation
qml.H(wires=['q1'])
qml.X(wires=['q2'])
qml.S(wires=['q2'])
qml.CNOT(wires=['q1', 'q2'])
# Measurement
return qml.state()
print(circuit())Result:
[0.+0.j 0.+0.707j 0.+0.707j 0.+0.j]
Hadamard Gate and For-Loop
- Hadamard gate can be used as a for-loop
- is equivalent to iterations in classical computing

Caption — Figure 7: Quantum parallelism via superposition. Three qubits each pass through their own gate (staggered across the circuit) before all three feed into a general operator at the end, illustrating how produces an equal superposition over all basis states, so that applying once effectively applies it to all 8 candidates "in parallel."
We don’t actually need a for loop, we need H gate. We apply U in parallel without actually do threading. WOWWW! We need QPU - We can convert all classical program into quantum algorithm
💡 Analogy: This is the heart of quantum parallelism: instead of writing a classical for-loop that runs once per candidate ( separate runs), Hadamard gates create a superposition of all candidates simultaneously, and a single application of touches all of them at once — the loop happens "in superposition" rather than in time.
Exercise 3.1 — State Preparation
Design quantum algorithms that prepare the following states. Develop PennyLane code to verify each of them. This is what we’ll see in the exam #MidtermExam (He said 100%, pay mroe attention) - You’ll be asked to create a quantum algorithm that prepares these states.
- #Important

Operator Augmentation
- If we have a quantum operator
we can augment with trivial qubits by
- This is useful for accommodating all entangled qubits, some of which are not involved with the operator
- Examples:
💡 Analogy: Augmentation is just "padding" an operator with identity wires it doesn't act on — like writing a function that only touches variables
yandzbut still has to passxthrough untouched so the whole tuple(x, y, z)stays well-formed.
Operator Augmentation and Tensor Product
- Important property of tensor product

It applies backward เห็นป้ะ ๆ B ก่อน A นะ เพราะเวลาเราเขียนเนี่ยสุดท้าย จะมาวางท้ายสุด ดังนั้นเราจะ applies ก่อน ถูกป้ะ
-
Examples
-
This property is useful for Pauli decomposition (decomposing a large matrix into Pauli axes: X, Y, Z) and computing the Hamiltonian matrix (taught in Chapter 7 afterward)
Quantum Algorithm: Example 2
#MidtermExam Example of the midterm exam question!! And you have to write a python program to validate or something as well.

Caption — Figure 8: "Another quantum algorithm" — a 3-wire circuit ( then CNOT on qubits 1–2, on qubit 2, CNOT on qubits 2–3, on qubit 3), with each intermediate state labeled above the wires: .
- Step 0: The initial state is .
- Step 1: Apply the Hadamard gate on the first qubit.
- Step 2: Apply the CNOT gate on the first and second qubits. The result is an entangled state, so a bidirectional arrow is shown.
- Step 3: Apply the NOT gate on the second qubit. Since it is entangled with the first qubit, we have to augment the NOT gate. Note that the first qubit is preserved while the second one is flipped.
- Step 4: Apply the CNOT gate on the second and third qubits. Since the second qubit is entangled with the first one, we augment the CNOT gate. Note that the first qubit is preserved. Note that it results in another entangled state — that is why it's marked with a bidirectional arrow across all three qubits.
- Step 5: Apply the phase shift gate on the third qubit. Since it is entangled with the first and second ones, we have to augment the gate. Note that the first and second qubits are preserved.
Example 2 in PennyLane
import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit', wires=[0,1,2])
@qml.qnode(dev)
def circuit():
# State preparation
qml.H(wires=[0])
qml.CNOT(wires=[0,1])
qml.X(wires=[1])
qml.CNOT(wires=[1,2])
qml.S(wires=[2])
# Measurement
return qml.state()
print(circuit())Result:
[0. 0. 0. 0.707j 0.707 0. 0. 0.]
Creating GHZ State
Caption — Figure 9: Hadamard gate and a series of CNOT gates can be used to create the GHZ state. Qubit 1 passes through , then a chain of CNOTs runs from qubit 1 as control into qubit 2 as target, qubit 2 as control into qubit 3 as target, and so on down to qubit — each CNOT propagating the superposition one qubit further along the chain.
📝 Instructor's annotation: the printed formula under the figure rendered as a broken/garbled string in the PDF; the instructor rewrote it clearly by hand:
- He explicitly we should try creating , maybe on #MidtermExam???
Exercise 3.2 — Entanglement Preparation
Design quantum algorithms that prepare the following states. Develop PennyLane code to verify each of them.
Answer the following questions.
- Let's define the adjoint shift gate Show that for any quantum state .
- Show that where is the identity matrix.
3. Clifford Set/2
Level 2: Pauli-X Gate
- Pauli gate rotates the qubit for phase on one of the axes: X, Y, and Z
- Pauli X flips the qubit
which is equivalent to rotation on Axis X
- is self-inversible:
qml.X(wires=…)

Caption — Figures 10–12: Pauli X, Y, and Z shown as rotations by on the phase circle (axes labeled pos real , neg real , pos img , neg img , with Bit 0 at top and Bit 1 at bottom): Pauli X rotates around the real axis (swapping Bit 0 ↔ Bit 1), Pauli Y rotates around the imaginary axis (swapping bits and flipping through ), Pauli Z rotates in place around the vertical bit-axis (keeping the bit but flipping its sign).
Level 2: Pauli-Y Gate
- Pauli Y flips the qubit, flips the sign, and flips the phase
- Flip แม่งทุกอย่างเลย
which is equivalent to rotation on Axis Y
- is self-inversible:
qml.Y(wires=…)

💡 Analogy: flips which basis state you're in. flips the sign but leaves you in the same basis state. does both at once, and picks up a factor of along the way — it's genuinely " and combined" (you'll prove in Exercise 3.3).
Level 2: Pauli-Z Gate
- Pauli Z keeps the qubit and flips the sign
which is equivalent to rotation on Axis Z
- is self-inversible:
qml.Z(wires=…)

Summary of Level 2
Table 4: Pauli gates. All of them belong to the group.
| Gates | Flip qubit? | Flip sign? | Flip phase? | ||
|---|---|---|---|---|---|
| X | Y | N | N | ||
| Y | Y | Y | Y | ||
| Z | N | Y | N |
Circuits:
(Figures 13, 14, 15: Pauli X, Y, Z)
Generalized Operator Augmentation
- For any quantum operator , we can augment it with trivial qubits by
where the output mixed state is specified by the indices , i.e.
while the remaining input qubits are unchanged, i.e. for all indices
📝 Instructor's annotation: drew an arrow from the superscript to the note **"→ qubits in total,"**and an arrow from the subscript to the note "only apply to these qubits" — a compact key for reading the notation: the superscript is the total system size, the subscript is which qubits the operator actually touches.
- Examples:
💡 Analogy: This is a more precise version of the "augmentation" from Clifford Set/1: instead of always padding identities on the outside (left/right), lets the operator reach into any subset of positions in an -qubit register — like indexing directly into specific array slots instead of only ever operating on a fixed prefix or suffix.
Quantum Algorithm: Example 3
- Step 0: The initial state is .
- Step 1: We recognize two entangled states caused by the Hadamard and CNOT gates.
- Step 2: We apply the X and Z gates on the first and latter pairs of qubits.
- Step 2 (cont'd): We expand the tensor product of
- Step 3: The CNOT gate for the 2nd and 4th qubits is simply a CNOT gate with the 1st and 3rd qubits augmented to it. Observe that and are introduced as dummy variables.
- Step 3 (cont'd): Applying this gate on yields which is no longer entangled.
Caption — Figure 16: "Yet another quantum algorithm" — a 4-wire circuit: + CNOT create a Bell pair on qubits 1–2, another + CNOT create a second Bell pair on qubits 3–4, then acts on qubit 2 and on qubit 4, and finally a CNOT links qubit 2 (control) to qubit 4 (target) — the step that disentangles the whole system back into a product state.
Exercise 3.3 — Pauli Gates
Design quantum algorithms that prepare the following states. Develop PennyLane code to verify each of them. #MidtermExam (In the midterm exam, you’ll see something like this)
- More of #MidtermExam
- quantum algorithm, show me step by step, the quantum state in each step.
- given a quantum state, created with a quantum algorithm.
- [Use Y.]
- [Use Z.]
- [Use Y.]
- [Use X, Y, Z.]
- [Use Y and Z.]
Answer the following questions.
-
Show that . It means that can be emulated by the Hadamard gate and the NOT gate.
-
Show that .
💡 This one's description on the slide reuses the wording from Q9 ("emulated by the Hadamard gate and the NOT gate"), but the actual formula uses and — so read it as: can be emulated by the and gates (up to the factor of ).
-
Show that .
-
Show that for any single-qubit quantum operator ,
4. Clifford Set/3
Level 3: SWAP Gate
- Swap: We can trivially swap the places of two qubits for ease of processing
"State mapping:"
- This is useful for rearranging the qubits before passing them to a quantum gate
qml.SWAP(wires=…)- Example:
- SWAP is self-inversible:
Circuit: qubit and qubit simply trade places.

(Figure 17: Swap gate)
Level 3: Controlled Z Gate
- Controlled Z gate keeps the qubit and flips the sign if the control qubit is
"State mapping:"
- CZ is self-inversible:
qml.CZ(wires=…)- Example:
Circuit: control qubit passes through unchanged; target qubit comes out as .

(Figure 18: Controlled Z gate)
Exercise 3.4 — Swap and Controlled Z
Answer the following questions.
- Let's define the Controlled Y gate from the following state mapping: Explain why is not self-inversible.
- Compute , where
- Create , where , using only and .
- Show that . It means that CZ can be emulated by the and CNOT gates.
- Show that It means that SWAP can be emulated only by the CNOT gate.
- Design a quantum operator that rotates a mixed state of qubits to the left by one bit. E.g. . Then convert to a quantum algorithm.
5. Circuit Visualization
Related
- We can visualize a quantum circuit in two formats: text and graphics
Text Format
qml.draw(circuit)(params)- This instruction displays the given circuit after applying the given parameters on it
@qml.qnode(dev)
def circuit(theta: float):
qml.H(wires=[0])
qml.RY(theta, wires=[0])
qml.CNOT(wires=[0,1])
return qml.state()
print(qml.draw(circuit)(np.pi / 6))(Figure 19: String representation of a quantum circuit)
0: ──H──RY(0.52)─╭●─┤ State
1: ──────────────╰X─┤ State
Graphical Format
qml.draw_mpl(circuit)(params)
@qml.qnode(dev)
def circuit(theta: float):
qml.H(wires=[0])
qml.RY(theta, wires=[0])
qml.CNOT(wires=[0,1])
return qml.state()
fig, ax = qml.draw_mpl(circuit)(np.pi / 6)
fig.savefig('circuit.png')(Figure 20: Graphical representation of a quantum circuit — the same circuit as above, rendered as a matplotlib figure with boxed gate symbols and a measurement icon on each wire, and saved to circuit.png.)
Conclusion
Table 5: Single-qubit gates
| Gates | Symbols | From | From |
|---|---|---|---|
| NOT | X | | |
| Hadamard | H | | |
| Phase shift | S | | |
| Pauli-X | X | | |
| Pauli-Y | Y | | |
| Pauli-Z | Z | | |
Two-qubit gates (Figure 21)
| Gates | Symbols | Descriptions |
|---|---|---|
| CNOT | CNOT | $ |
| Swap | SWAP | $ |
| CZ | CZ | $ |
- Quantum algorithm = a circuit of Clifford (and other) gates for state preparation, computation, and measurement
- Operator augmentation (, , and the generalized ) lets a gate defined on a few qubits act correctly inside a larger, possibly entangled register — see Operator Augmentation and Generalized Operator Augmentation above for the full definitions and worked examples.
Target Learning Outcomes
Conceptual Understanding of Quantum Circuits
- Define the three primary stages of a quantum algorithm: state preparation, computation through gate manipulation, and measurement.
- Explain the characteristics of the Clifford gate set, including fault-tolerance, self-inversibility, and efficient classical simulability.
Quantum Gate Mastery
- Apply Level 1 and 2 gates (Hadamard, Phase Shift, and Pauli X, Y, Z) to transform pure states into superpositions or modify quantum phases.
- Differentiate between the effects of Pauli X, Y, and Z gates in terms of qubit flipping, sign flipping, and phase changes.
- Utilize multi-qubit gates (CNOT, SWAP, CZ) to create entanglement or rearrange qubit order for processing.
Mathematical and Algebraic Application
- Calculate the state of a quantum system after a series of gate applications using tensor products and matrix multiplication.
- Perform operator augmentation to describe the action of a gate on specific indices within an N-qubit state.
- Prove gate equivalencies through algebraic manipulation.
Computational Implementation
- Construct functional quantum circuits using the PennyLane library, including device initialization and QNode definition.
- Visualize quantum circuits in both text and graphical formats to verify algorithm structure.
- Develop algorithms to prepare specific quantum states, such as Bell states or GHZ states.