Is roll 104 registered?line 1
  1. target = 104
  2. rolls = [101, 102, 103, 104]
  3. for r in rolls:
  4. if r == target:
  5. break
  6. fast = set(rolls)
  7. print(target in fast)

Variables

target
104 (just changed)

The roll number to look for in the placement list.

Step 1 of 13
Try another target

The list was walked one roll at a time, but the set went straight to the answer. Same data, same question: only the way it was arranged changed.

Quick check

Quick check: Use the target slider under the code and set it to 105, a roll that is not in the list. How many checks does the list make?

What a data structure is#

A set files each item by its value, so Python can jump straight to it. A dict works the same way, but each key, like a roll number, points to a value, like a name. Both show the main idea of this page: a data structure is a way of arranging data in memory so that the operations you need are fast.

rolls, in a list: found by position
101
102
103
104
by_roll, a dict: found by key
KeyValue
101Asha
102Ravi
103Meena
104Arjun

No structure is fast at everything. You pick one by asking which operations you will do most.

Arrays#

An array keeps items side by side in memory, so the computer can work out where index i is and jump there in one step. A Python list is an array underneath.

10110210310410501234
rolls

rolls[3] is 104, in one step. The catch shows up when you insert.

Quick check

Quick check: Insert roll 100 at the front of rolls. How many existing values must move one cell to the right?

Linked lists#

A linked list keeps each value in a node that also holds a link to the next node. The nodes can sit anywhere in memory. The first node is the head, and the last one links to nothing (None in Python).

rolls as a linked list

Adding a node at the front is one step: link the new node to the old head, and it becomes the new head. Nothing shifts. The price is that there is no index.

Quick check

Quick check: You hold only the head (101). How many links do you follow to reach 104?

Stacks: the code walkthrough#

A stack lets you add and remove only at the top: last in, first out. That is exactly undo. Ctrl+Z should undo your latest action first. In Python, append puts an item on top (a push) and pop() takes the top item off, both in one step.

Use the n slider under the code and set it to 0. Popping an empty Python list crashes with an IndexError, so the code checks first.

Undo history as a stackline 1
Try another n
  1. n = 3
  2. acts = ["type", "bold", "cut"]
  3. history = []
  4. for a in acts[:n]:
  5. history.append(a)
  6. if history:
  7. print("Undo:", history.pop())
  8. else:
  9. print("Nothing to undo")
  10. print("Left:", history)

Variables

n
3 (just changed)

How many actions the user does before pressing Ctrl+Z.

Step 1 of 13

The browser's back button works the same way: the latest page comes off first.

Quick check

Quick check: With n = 3, you press undo once more. What comes off the stack?

Queues#

A queue is the canteen line: join at the back, get served from the front. First in, first out.

Canteen line, Rahul at the front
← FRONT
Rahul
Priya
Kiran
BACK →

Quick check

Quick check: Sneha joins the line, then one person is served. Who is at the front now?

Hash maps#

A hash map stores key and value pairs. A Python dict is one, and a set is one that keeps keys only. A hash function turns the key, like 104, into a slot number (a slot is one numbered box in memory), and the lookup goes straight to that slot. That is why the opener's set needed no walk.

by_roll
KeyValue
101Asha
102Ravi
103Meena
104Arjun

Quick check

Quick check: by_roll now holds 10 lakh students. Roughly how many steps does by_roll[104] take?

Trees and graphs#

A tree holds a hierarchy: one root, and each item has children below it. A graph is any web of connections, with no top and no fixed order.

CollegeCSEECEABADelhiJaipurAgraBhopalTreeGraph
A tree (college to branches to sections) and a graph (cities joined by train routes)

Trees fit folders on your laptop and a college's branches. A tree kept sorted and balanced can skip about half the items at each step; a later step shows how. Graphs fit train routes on IRCTC and friends on Instagram, where the question is "how do I get from here to there?"

Picking the right one#

Linear structures keep items in one line: array, linked list, stack, queue. Non-linear ones do not: tree, graph and hash map (some books give the hash map its own family, hash-based).

StructureGood atBad at
Array (list)Reading any index in one stepInserting or deleting at the front or middle
Linked listAdding or removing at the frontReaching the 4th item: you walk
StackPush and pop at the topReaching anything below the top
QueueJoin at the back, leave from the frontReaching anyone in the middle
Hash mapFinding a value by its keyOrder: smallest, largest, the 3rd
TreeHierarchies, and fast search when sortedMore work to build and keep in shape
GraphAny web of connectionsMore memory and more careful code

Ask one question first: which operation will I do most often? Then pick the row that is good at it.

One last check#

Quick check

Quick check: Three features: the portal's Back button, the waiting room in a placement drive (first come, first interviewed), and finding a student by roll number. Which structures, in that order?

A data structure decides how the data sits. Next comes what you do with it: the step by step recipes called algorithms.