ЁЯПл The SchoolтА║ЁЯзо DSAтА║ЁЯОп рдзрдбрд╛ 12 тАФ рдпреЛрдЧреНрдп structure рдирд┐рд╡рдбрдгреЗ: рдкреНрд░рд╢реНрди рдард░рд╡рддреЛ
ЁЯЦ╝я╕П See the drawing + lab ЁЯПа Course home ЁЯМ┐ Branch on GitHub тЬПя╕П View source
ЁЯЦ╝я╕П рдЖрдХреГрддреА рдЖрдгрд┐ labThe drawing + lab рдкреВрд░реНрдг рдкрд╛рдирд╛рд╡рд░ рдЙрдШрдбрд╛ тЖЧOpen full page тЖЧ

ЁЯОп рдзрдбрд╛ 12 тАФ рдпреЛрдЧреНрдп structure рдирд┐рд╡рдбрдгреЗ: рдкреНрд░рд╢реНрди рдард░рд╡рддреЛ

ЁЯУН рддреБрдореНрд╣реА рдЗрдереЗ рдЖрд╣рд╛рдд: 12 рдкреИрдХреА рдзрдбрд╛ 12 ┬╖ ЁЯОУ рд╢реЗрд╡рдЯрдЪрд╛


ЁЯУж рдпрд╛ рдмреНрд░рдБрдЪрдордзреНрдпреЗ рдХрд╛рдп рдЖрд╣реЗ

рдзрдбреЗ 01тАУ12 тАФ рдкреВрд░реНрдг рдХреЛрд░реНрд╕. рдирд┐рд░реНрдгрдп рддрдХреНрддрд╛, complexity cheat sheet, рдХреЛрдгрддреНрдпрд╛рд╣реА problem рд╕рд╛рдареА рд╕рд╛рдд рдкрд╛рдпрд▒реНрдпрд╛рдВрдЪреА рдкрджреНрдзрдд, рдЖрдгрд┐ рдХрд│рд╕-рдкреНрд░рдХрд▓реНрдк (capstone).

ЁЯзТ 5 рд╡рд░реНрд╖рд╛рдВрдЪреНрдпрд╛ рдореБрд▓рд╛рд▓рд╛ рд╕рдордЬрд╛рд╡рд▓реНрдпрд╛рд╕рд╛рд░рдЦреЗ

рдЖрддрд╛ рддреБрдордЪреНрдпрд╛рдХрдбреЗ рдЕрдХрд░рд╛ рдЬрд╛рдЧрд╛ рдЖрдгрд┐ рдЪрд╛рд▓реА рдЖрд╣реЗрдд. рд╢реЗрд╡рдЯрдЪреЗ рдХреМрд╢рд▓реНрдп рдореНрд╣рдгрдЬреЗ рдкреНрд░рд╢реНрди рдРрдХреВрди рддреЛ рдХрд╢рд╛рдЪреА рдорд╛рдЧрдгреА рдХрд░рддреЛ рддреЗ рдУрд│рдЦрдгреЗ. "рдЬрд╛рдЧреЗрдиреБрд╕рд╛рд░?" тАФ lockers. "рдирд╛рд╡рд╛рдиреЗ?" тАФ рдХрдкреНрдкреЗ. "рд╕рд░реНрд╡рд╛рдд рдЕрд▓реАрдХрдбрдЪрд╛ рдЖрдзреА?" тАФ рдЯреНрд░реЗрдЪреА рдЪрд│рдд. "рдЖрдзреА рдЖрд▓реЗрд▓реНрдпрд╛рд▓рд╛ рдЖрдзреА?" тАФ рдЬреЗрд╡рдгрд╛рдЪреА рд░рд╛рдВрдЧ. "рдиреЗрд╣рдореА рд╕рд░реНрд╡рд╛рдд рд▓рд╣рд╛рди?" тАФ рд╡реНрдпрд╛рд╕рдкреАрда. "Sorted, рдЖрдгрд┐ рд╕рддрдд рдмрджрд▓рдд рд░рд╛рд╣рдгрд╛рд░реЗ?" тАФ рдХреЕрдЯрд▓реЙрдЧрдЪрд╛ рдЦрдг. "рдЦреЛрд▓реНрдпрд╛ рдЖрдгрд┐ рдХреЙрд░рд┐рдбреЙрд░?" тАФ рдирдХрд╛рд╢рд╛. "рддреЛрдЪ рдЫреЛрдЯрд╛ рдкреНрд░рд╢реНрди рдкреБрдиреНрд╣рд╛ рдкреБрдиреНрд╣рд╛?" тАФ рдлрд│рд╛. рдкреНрд░рд╢реНрди рдореЛрдареНрдпрд╛рдиреЗ рдмреЛрд▓рд╛; structure рд╕реНрд╡рддрдГ рдЙрддреНрддрд░ рджреЗрддреЛ.

ЁЯЧ║я╕П рдЖрдХреГрддреА

flowchart TD
  Q{"what does the question ask for?"}
  Q -->|"the i-th thing"| A["array"] ; Q -->|"by name"| H["hash map / set"]
  Q -->|"most recent first"| S["stack"] ; Q -->|"first come first served"| U["queue"]
  Q -->|"smallest / biggest, repeatedly"| P["heap"] ; Q -->|"sorted while changing"| T["balanced tree"]
  Q -->|"rooms and corridors"| G["graph + BFS / DFS / Dijkstra"] ; Q -->|"overlapping sub-problems"| D["DP"]

тЭУ рдХрд╛рдп

Cheat sheet

Structure / рдЪрд╛рд▓ рдЦрд░реНрдЪ рдХреЗрд╡реНрд╣рд╛ рд╡рд╛рдкрд░рд╛рдпрдЪрд╛
list index / append O(1) рдЬрд╛рдЧрд╛ (position), batches
list insert front / pop(0) O(n) loop рдордзреНрдпреЗ рдХрдзреАрдЪ рдирд╛рд╣реА тАФ deque рд╡рд╛рдкрд░рд╛
dict / set рд╕рд░рд╛рд╕рд░реА O(1) рдирд╛рд╡рд╛рдиреЗ, рдореЛрдЬрдгреА, dedupe, caching
deque рджреЛрдиреНрд╣реА рдЯреЛрдХрд╛рдВрдирд╛ O(1) queues, windows
heapq push/pop O(log n) рдкреБрдврдЪрд╛ рд╕рд░реНрд╡рд╛рдд рд▓рд╣рд╛рди, top-k, Dijkstra
sorted() O(n log n) рдПрдХрджрд╛, рдордЧ bisect рдХрд┐рдВрд╡рд╛ sweep
bisect O(log n) sorted рдЖрдгрд┐ рди рдмрджрд▓рдгрд╛рд░реЗ
balanced tree / B-tree O(log n) sorted рдЖрдгрд┐ рдмрджрд▓рдгрд╛рд░реЗ, ranges
BFS / DFS O(V + E) hops, reachability, рдХреНрд░рдо
Dijkstra O(E log V) weighted рд╕рд░реНрд╡рд╛рдд рд▓рд╣рд╛рди path
DP poly overlapping sub-problems

рдкрджреНрдзрдд (рдореБрд▓рд╛рдЦрддреА рдЖрдгрд┐ design reviews рджреЛрдиреНрд╣реАрдВрд╕рд╛рдареА): 1 рдкреНрд░рд╢реНрди рдЙрджрд╛рд╣рд░рдгрд╛рд╕рд╣ рдкреБрдиреНрд╣рд╛ рдорд╛рдВрдбрд╛ ┬╖ 2 brute force рдЖрдгрд┐ рддреНрдпрд╛рдЪрд╛ O рд╕рд╛рдВрдЧрд╛ ┬╖ 3 pattern рдУрд│рдЦрд╛ (two pointers? рдирд╛рд╡рд╛рдиреЗ? рд╕рд░реНрд╡рд╛рдд рд▓рд╣рд╛рди path?) ┬╖ 4 structure рдирд┐рд╡рдбрд╛ ┬╖ 5 code рд▓рд┐рд╣рд╛ ┬╖ 6 рдЯреЛрдХрд╛рдЪреНрдпрд╛ cases test рдХрд░рд╛ (рд░рд┐рдХрд╛рдореЗ, рдПрдХ, duplicates, рдкреНрд░рдЪрдВрдб) ┬╖ 7 рд╡реЗрд│ рдЖрдгрд┐ space рд╕рд╛рдВрдЧрд╛, рдЖрдгрд┐ рддреБрдореНрд╣реА рдирд┐рд╡рдбрд▓реЗрд▓рд╛ trade-off.

ЁЯдФ рдХрд╛

heap implement рдХрд░рд╛рдпрдЪреЗ рдХреЛрдгрд╛рд▓рд╛рдЪ рдкреИрд╕реЗ рдорд┐рд│рдд рдирд╛рд╣реАрдд; nested loop рдПрдХрдЪ loop рдЕрд╕рд╛рдпрд▓рд╛ рд╣рд╡рд╛ рд╣реЛрддрд╛ рд╣реЗ рд▓рдХреНрд╖рд╛рдд рдШреЗрдгреНрдпрд╛рдЪреЗ рдорд╛рддреНрд░ рд╕рдЧрд│реНрдпрд╛рдВрдирд╛ рдорд┐рд│рддрд╛рдд. рддрдХреНрддрд╛ рдЖрдгрд┐ рдкрджреНрдзрдд рдПрдХрд╛ рдзреВрд╕рд░ "рдЬрд▓рдж рдХрд░рд╛" рдЪреЗ рдкрд╛рдЪ рдорд┐рдирд┐рдЯрд╛рдВрдЪреНрдпрд╛ рдирд┐рд░реНрдгрдпрд╛рдд рд░реВрдкрд╛рдВрддрд░ рдХрд░рддрд╛рдд.

ЁЯФз рдХрд╕реЗ (рдпрд╛ repo рдордзреНрдпреЗ)

demo.py choose рдирд┐рд░реНрдгрдп рддрдХреНрддрд╛ print рдХрд░рддреЛ; repo рдордзрд▓рд╛ рдкреНрд░рддреНрдпреЗрдХ structure рдЖрдгрд┐ рдХреГрддреА рддрд┐рдЪреНрдпрд╛ docstring рдиреЗ рджрд┐рд▓реЗрд▓реЗ рд╡рдЪрди рдкрд╛рд│рддреЗ рдпрд╛рдЪрд╛ рдкреБрд░рд╛рд╡рд╛ рдореНрд╣рдгрдЬреЗ test_dsa.py.

ЁЯзк рдХрд░реВрди рдкрд╛рд╣рд╛

python3 dsa/demo.py choose
python3 dsa/test_dsa.py
python3 - <<'EOF'
# capstone: the timetable clash finder тАФ which pairs of meetings overlap?
import random, time
random.seed(9); M = [(s, s + random.randint(1, 3)) for s in random.choices(range(0, 200), k=500)]
t = time.perf_counter(); n2 = sum(1 for i in range(len(M)) for j in range(i + 1, len(M)) if M[i][0] < M[j][1] and M[j][0] < M[i][1]); t2 = time.perf_counter() - t
t = time.perf_counter(); ev = sorted([(s, 1, i) for i, (s, e) in enumerate(M)] + [(e, 0, i) for i, (s, e) in enumerate(M)]); open_ = set(); sw = 0
for _, kind, i in ev:                                      # sort + sweep: ends (0) before starts (1) at the same time
    if kind: sw += len(open_); open_.add(i)
    else: open_.discard(i)
t1 = time.perf_counter() - t
print(f"O(n┬▓): {n2} clashes in {t2*1000:.1f} ms ┬╖ sort+sweep O(n log n): {sw} clashes in {t1*1000:.1f} ms")
EOF

тЬЕ рддрдкрд╛рд╕рд╛ тАФ рддреБрдореНрд╣рд╛рд▓рд╛ рдХрд╛рдп рджрд┐рд╕рд╛рдпрд▓рд╛ рд╣рд╡реЗ

рдирд┐рд░реНрдгрдп рддрдХреНрддрд╛; 12 checks рд╕рд╣ tests рдХрдбреВрди OK; рджреЛрдиреНрд╣реА clash counts рд╕рдорд╛рди, рдЖрдгрд┐ 500 meetings рд▓рд╛ sweep рдЕрдиреЗрдХ рдкрдЯреАрдВрдиреА рдЬрд▓рдж тАФ рдЖрдгрд┐ k рд╡рд╛рдврд╡рд▓рд╛ рддрд░ рд╣реЗ рдЕрдВрддрд░ рд╡рд╛рдврдд рдЬрд╛рддреЗ.

ЁЯПБ рддреБрдореНрд╣реА рдЖрддреНрддрд╛рдЪ рдХрд╛рдп рд╕рд┐рджреНрдз рдХреЗрд▓реЗ

рдирд╡реАрди рдкреНрд░рд╢реНрди рджрд┐рд▓рд╛ рддрд░ рддреБрдореНрд╣реА brute force, pattern, structure рдЖрдгрд┐ рдЦрд░реНрдЪ рд╕рд╛рдВрдЧреВ рд╢рдХрддрд╛ тАФ рдЖрдгрд┐ рддреБрдореНрд╣реА capstone рджреЛрдиреНрд╣реА рдкреНрд░рдХрд╛рд░реЗ рдмрдирд╡рд▓рд╛ рдЖрдгрд┐ рдлрд░рдХ рдореЛрдЬрд▓рд╛.

тЪая╕П рдиреЗрд╣рдореАрдЪреНрдпрд╛ рдЪреБрдХрд╛

ЁЯПн рдкреНрд░рддреНрдпрдХреНрд╖ рд╡рд╛рдкрд░рд╛рдд рд╣реЗ рдХрд╛ рдорд╣рддреНрддреНрд╡рд╛рдЪреЗ: рд╣рд╛ рддрдХреНрддрд╛ рдореНрд╣рдгрдЬреЗрдЪ performance review рдЪреА checklist: рдкреНрд░рддреНрдпреЗрдХ hot path рд▓рд╛ рддреА рдХреЛрдгрддреНрдпрд╛ row рд╡рд░ рдЖрд╣реЗ рдЖрдгрд┐ рдХрд╛, рд╣реЗ рд╕рд╛рдВрдЧрддрд╛ рдЖрд▓реЗ рдкрд╛рд╣рд┐рдЬреЗ.

ЁЯПЖ рдХрд│рд╕-рдкреНрд░рдХрд▓реНрдк (Capstone)

clash finder рд╡рд╛рдврд╡рд╛: рдХреЛрдгрддреНрдпрд╛ meetings clash рд╣реЛрддрд╛рдд рддреЗ рд╕рд╛рдВрдЧрд╛ (рдлрдХреНрдд рдХрд┐рддреА рдирд╛рд╣реА), рдЕрдиреЗрдХ рдЦреЛрд▓реНрдпрд╛рдВрдордзрд▓реНрдпрд╛ meetings рд╣рд╛рддрд╛рд│рд╛ (sweeps рдЪрд╛ dict), рдЖрдгрд┐ рд░рд┐рдХрд╛рдореНрдпрд╛ timetable, рдПрдХрдЪ meeting, рдЖрдгрд┐ рджреЛрди рд╕рд╛рд░рдЦреНрдпрд╛ meetings рд╕рд╛рдареА test рд▓рд┐рд╣рд╛. рдордЧ рдПрдХрд╛ рдкрд░рд┐рдЪреНрдЫреЗрджрд╛рдд рд╕рдордЬрд╛рд╡рд╛ рдХреА sort-and-sweep O(n log n) рдХрд╛ рдЖрд╣реЗ.

ЁЯОУ рдХреЛрд░реНрд╕ рдкреВрд░реНрдг рдЭрд╛рд▓рд╛

рдЕрднреНрдпрд╛рд╕ рдпреЛрдЬрдирд╛ рдмрд╛рд░рд╛рд╣реА рдзрдбреНрдпрд╛рдВрд╡рд░ рдЦреВрдг рдХрд░рддреЗ; quiz рддреНрдпрд╛рдВрдЪреА рддрдкрд╛рд╕рдгреА рдХрд░рддреЗ; Database school рдзрдбрд╛ 09 рдЪреЗ trees disk рд╡рд░ рдиреЗрддреЗ, рдЖрдгрд┐ School portal рд╡рд░ рдкреНрд░рдорд╛рдгрдкрддреНрд░ рдЖрд╣реЗ.

ЁЯОп Lesson 12 тАФ Choosing the right structure: the question decides

ЁЯУН You are here: Lesson 12 of 12 ┬╖ ЁЯОУ The last one


ЁЯУж What's in this branch

Lessons 01тАУ12 тАФ the whole course. The decision table, the complexity cheat sheet, a seven-step method for any problem, and the capstone.

ЁЯзТ Explain like I'm 5

You now own eleven places and walks. The last skill is hearing a question and knowing which one it is asking for. "By position?" тАФ lockers. "By name?" тАФ pigeonholes. "Most recent first?" тАФ the tray pile. "First come first served?" тАФ the lunch line. "Always the smallest?" тАФ the podium. "Sorted, and it keeps changing?" тАФ the catalogue drawer. "Rooms and corridors?" тАФ the map. "The same smaller question again and again?" тАФ the board. Say the question out loud; the structure answers.

ЁЯЧ║я╕П Diagram

flowchart TD
  Q{"what does the question ask for?"}
  Q -->|"the i-th thing"| A["array"] ; Q -->|"by name"| H["hash map / set"]
  Q -->|"most recent first"| S["stack"] ; Q -->|"first come first served"| U["queue"]
  Q -->|"smallest / biggest, repeatedly"| P["heap"] ; Q -->|"sorted while changing"| T["balanced tree"]
  Q -->|"rooms and corridors"| G["graph + BFS / DFS / Dijkstra"] ; Q -->|"overlapping sub-problems"| D["DP"]

тЭУ What

The cheat sheet

Structure / walk Cost Reach for it when
list index / append O(1) position, batches
list insert front / pop(0) O(n) never in a loop тАФ use deque
dict / set O(1) avg by name, counting, dedupe, caching
deque O(1) both ends queues, windows
heapq push/pop O(log n) the smallest next, top-k, Dijkstra
sorted() O(n log n) once, then bisect or sweep
bisect O(log n) sorted and static
balanced tree / B-tree O(log n) sorted and changing, ranges
BFS / DFS O(V + E) hops, reachability, order
Dijkstra O(E log V) weighted shortest path
DP poly overlapping sub-problems

The method (interviews and design reviews alike): 1 restate the question with an example ┬╖ 2 give the brute force and its O ┬╖ 3 name the pattern (two pointers? by name? shortest path?) ┬╖ 4 pick the structure ┬╖ 5 code it ┬╖ 6 test the edges (empty, one, duplicates, huge) ┬╖ 7 state time and space, and the trade-off you chose.

ЁЯдФ Why

Nobody is paid to implement a heap; everybody is paid to notice that the nested loop should have been one. The table and the method turn a vague "make it faster" into a five-minute decision.

ЁЯФз How (in this repo)

demo.py choose prints the decision table; test_dsa.py is the proof that every structure and recipe in the repo does what its docstring promises.

ЁЯзк Try it

python3 dsa/demo.py choose
python3 dsa/test_dsa.py
python3 - <<'EOF'
# capstone: the timetable clash finder тАФ which pairs of meetings overlap?
import random, time
random.seed(9); M = [(s, s + random.randint(1, 3)) for s in random.choices(range(0, 200), k=500)]
t = time.perf_counter(); n2 = sum(1 for i in range(len(M)) for j in range(i + 1, len(M)) if M[i][0] < M[j][1] and M[j][0] < M[i][1]); t2 = time.perf_counter() - t
t = time.perf_counter(); ev = sorted([(s, 1, i) for i, (s, e) in enumerate(M)] + [(e, 0, i) for i, (s, e) in enumerate(M)]); open_ = set(); sw = 0
for _, kind, i in ev:                                      # sort + sweep: ends (0) before starts (1) at the same time
    if kind: sw += len(open_); open_.add(i)
    else: open_.discard(i)
t1 = time.perf_counter() - t
print(f"O(n┬▓): {n2} clashes in {t2*1000:.1f} ms ┬╖ sort+sweep O(n log n): {sw} clashes in {t1*1000:.1f} ms")
EOF

тЬЕ Verify тАФ what you should see

The decision table; OK from the tests with 12 checks; both clash counts equal, with the sweep several times faster at 500 meetings тАФ and the gap growing if you raise k.

ЁЯПБ What you just proved

Given a new question you can name the brute force, the pattern, the structure and the cost тАФ and you built the capstone both ways and measured the difference.

тЪая╕П Common mistakes

ЁЯПн Why this matters in production: this table is the performance review checklist: every hot path should be able to say which row it is on and why.

ЁЯПЖ Capstone

Extend the clash finder: report which meetings clash (not just how many), handle meetings in several rooms (a dict of sweeps), and write a test for an empty timetable, a single meeting, and two identical meetings. Then explain, in a paragraph, why sort-and-sweep is O(n log n).

ЁЯОУ The course is complete

The study plan ticks the twelve off; the quiz checks them; the Database school puts lesson 09's trees on disk, and the School portal has the certificate.

тЖР Previousdp greedyFinished! Take the quiz тЖТcheck what stuck

This page is the lesson's README from the lesson-12-choosing branch, shown here so the whole School stays on one site. Code files open on GitHub at the same branch.