Docsity

Master Graphs & Trees: 70-Page Visual Handbook for Coding Interviews & Competitive Program, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Master Graphs & Trees: 70-Page Visual Handbook for Coding Interviews & Competitive Program and more Study notes Data Structures and Algorithms in PDF only on Docsity!

anal "Master the Graph, Solve Any Problem.” A COMPLETE REVISION GUIDE *x FOR * SPECIAL GRAPH PROBLEMS rm ; = a = WHAT S_ INSIDE? COVERS ALL MAJOR TOPICS PERFECT FOR mae All Key Concepts * Graph Bosics & Representations pee = Ste ara 7 : [Important Algorithms | % Traversals (BFS, DFS) ' || => Senpeeevetegiennng M Special Graphs % Shortest Path Algorithms ! | —> College Exams w Problem-Solving Patterns | & Minimum Spanning Tree (MST) — Placements & Interviews [J Complexity Analysis | te Topological Sort & DAG ! eo cee oe ae MZ Common Mistakes & Debugging # Disjoint Set Union (DSU) Ui dence ai en LAIN ali eerie. ips ee) sae ee ie ee (A Cheat Sheets & Quick Revision | we Bridges, Articulation Points, SCC | to Advanced | re | MM Practice bg eS. Checklists Becta Grape Naveed Tees | snchasiaatas | | Think + Plan + Code > Test 1 | Geeta yu need Ye %& Patterns, Templates & More... : Place ! | > Optimize > AC ! A. ae cccar cui || nese onan nec 2 | = = = = i j 70 HIGH-QUALITY 1 4 VISUAL EXPLANATIONS ie] CHEAT SHEETS & | PATTERNS & TEMPLATES | PRACTICE MORE, HANDWRITTEN PAGES & DIAGRAMS ; QUICK REVISION : o} TO SOLVE FASTER GET BETTER ! —————————EEes => CREATED BY Y= : | ~ KEEP PRACTICING. KEEP GROWING. = | Ramanand Tomar | = is — = va — ro = GET AC! = i Ne oy es te ee ee ae en = + he [pce] x GRAPH REPRESENTATION x Storage formats, pros/cons How +0 choose the right one ? Adjacency Matrix vs Adjacency List 4. INTUITION ADJACENCY MATRIX (5x5) ADJACENCY LIST EXAMPLE GRAPH (Undirected) A graph is a collection of vertices (nodes) QO A 2.0 6S OU o|—[1|f3 wc = ed by edges. \ connect oy (0) (4) Swern Sa Oh ee 4 |—»[o ola Lola | For each | We need a woy to store the connections so (2) 4 1 0 1 4 0 node, stare \ that th hh efficiently . : \ we can precess 2 Sear erricen y We - 2 0 ni 0 0 1 ‘a oan sn lh 2 —> 1 _—> 4 | all its ! Two most common waus: dé eLiJ[j) = 4 1 ' neighbors. ae) (3) E=6 3 4 4 ololda ie eines 3|—|0> 1/4 an eit ° Adjacency Matrix | edge I (4) ee ae Se eee cee ee ca Pc ° Adjacency List | else 0 : —— a ADJACENCY MATRIX vs ADJACENCY LIST carat are waa % TIME & SPACE COMPLEXITY | j 4 Matri j yu List Feature Adjacency Sostbaly Adjacency : If graph is DENSE (E is close to v+)) Operation Matrix Adjacency List o(v?) O(V+E) aly ie: DPieka Matri } & 3° ( Vi= number of vertices) ( E = number of edges ) [ 7 aaa mike Space O(v?) o(v + E) Space Efficient No (Bad for sparse graphs) en file Seams aes I) 0 ee ee Is edge (uw) exist? | (4) | O(deg(u)) curs ; o(1) | j Edge Existence Check Gat Cu) £41) O (deg (u)) \ — Use Adjacency List } Add Edge o(4) o(4) Iterate all neighbors O(v) 0 (deg(u)) a ; 3 "3 MEMORY TRICK st Tterate neighbors o(v) 0 (deg(u)) Dense Graphs Sparse Graphs - - of u pail (E = V7) (eee v2) Matrix = Whole Picture ( You store everything ) (mee D c a Implementation Simple to code Slightly more code ge Only iia tgs Bes . si sel ( You store only what exists ) ae GS ANN A Ue ee ee ra ag a I es 4) ADJACENCY MATRI | 2) ADJACENCY LIST I | ais Hs ae rag, a Se ers | . : ; Peep AN COMMON MISTAKES ) ( INTERVIEW TIPS & a | fX] RELATED LEETCODE PROBLEMS Sonieneg: Teer: | (| #200, Number of Islands (BFS/DFS + Moti tor > mat; | wector> adj; . i 5 ys ; ps ‘ bi es alicuis aes * rix) | ge vec in ma: | ae i ) | Forgetting te initialize all lists | a we Is graph directed or (| 50%. thuntion 0 Cenmiadapeinaian | need n(n, vector (n, 0)); | adj ma n(n, {}); Ep oe Earned ected carat, aceaing \ | + 207. Course Schedule (Topo + Adj List) | pace ht aa) is tae | only one direction edge )) + Ask about constraints: V and E. + 797. All Paths From Source to Target : | ff i i i i —_ | oO ee : eas ore a oo | " Using Matai: far “apace graph { q Decide representation accordingly. ; MLV = , i back * 7% é | enakiEwlgatl =i; adj [v] push. back(u) ; ! (waste of space) th a trade-offs in Space and »] RELATED CODEFORCES PROBLEMS ne. \ + 234A - Team | f/f iterate iqhb | Using List but mot checkin Nicabes tear om ih for(int v a (ud) fy : | pie create parallel ics : Q | Se oe : ae oe NS Gare ists #/ : ) : | i ultv * edge exists »/ } eile 5 1 the right approach. ‘ * SABA - Chat Room } 4 ea ae ae oa * 1133F - Connectivity Problem en a tale gc a eee CHOOSE WISELY, CODE CLEANLY, THINK LIKE A GRAPH MASTER! 39 [ PAGE 3 | > Ss Pape Se Rie 4. INTUITION « We pick a mode and explore one path completely before. exploring other paths. * Good for exploring all reachable modes, connected components, cycle detection, topological sort, backtracking problems . * Implement using Recursion ( call stack ) or Lterotive ( explicit stack ). . WHEN To USE DFS ? Finding connected components 1 Cycle detection ' Topological Sorting ( in DAG) Backtracking / All paths Solving puzzles ( N-Queens, Sudoku) Strongly Connected Components Articulation Points, Bridges, etc. 3. EXAMPLE WALKTHROUGH Start DFS from node O 5A. C++ TEMPLATE (RECURSIVE DFS) Visited Order Step Current Node (Recursive) Stack (Iterative) oO (9) 0 [0] 1 4 OF 1 [1] 2 2 0; 4,2 [2] 3 (backtrack) Oe Ee) fr] 4 3 O44 3,3 [3] 5 4 0, 4, 2, 3, 4 [4] 6 (backtrack) 04,23. "4 [3] 7 5 0,.4,.2,.3,.4,5 [5] 8 6 0,41,2,3,4,5,6 [é] 4q (done } 0, 4,2, 3,4,5,6 EY * GRAPH TRAVERSAL - DFS ~* ( Depth First Search ) asa eee ——_— DFS gees as DEEP as possible before backtracking . __ Uses Stack ( Explicit or Implicit - 4. DFS TREE (starting from 0) (0) oF ee ee ee | This tree shows one possible DFS exploration order. | Actual order moy vary ( depends on adjacency order JE | ry 5B. C++ TEMPLATE (ITERATIVE DFS USING STACK) 6. CONNECTED COMPONENTS 3. COMPLEXITY Hinclude Hinclude Run DFS from each urwisited node. using namespace std; using namespace std; Component id increases after each Time O(v +e) Es : : A 5 ov fisted stack a void es # aoe adj, void dfs_iterative (int sre, vector>% adj) { E me ype sell = [eae (v) ane - aaa vector vis E ee i q jie = Where , ‘ int n= adj size(); int comp = 0; i ee a . bi aah —_ eam vist, 0); vector vis(n, 0), comp-id(n, -4); Vo= number of vertices * process node stack st; - : a. 4 E = number of edges for Cint v : adjlu)) { st. push(sre); for€int i= 0, i> om; cout << uw <<" 8) // process node void dfs(int u, vector>k adj, | 5¢ Stack f1 ee Pr : H hee be #f push neighbors (in reverse order for similar order os recursive.) veetor & vis, veckor& comp—id, | = ae athe | int uy vj cin oe aes yy for Cimt i = adj{u}.size() - 4; i >= 0, i--) { int comp) { | % Not handling disconnected components. — | adj(u). push_back(w) ; int vo adj(u) Li); vis(u] = 1; comp_idfu] = comp; | j fe ! oat (v], Sum BarRCa), Hf remove for directed graph if (lvislv)) st. push(v); | $56 Cak | + 207. Course Schedule Ceyele) is ie ith i ee. iia 2 * «DFS explores depth first, backtracks smartly, and helps us solve many powerful graph problems ! o_* 4. INTUITION * CONNECTED COMPONENTS ~« Finding All Components in an Undirected Graph ( A connected component is a maximal set of vertices such that ( every poir is reachable from each other. el * A graph may be disconnected. 2 Jee. 3. HOW IT WORKS (DFS APPROACH) DRY RUN (DFS) i e i i ; Binet Oh. visite 0.452,3 iene * Vertices can be grouped into Consider the following undirected graph. bias ease ou A visi . (Comp components. s) Next unvisited = 4 —> visits 4,5,6 (Comp 2) e There is no path between vertices (0) (1) (4) 5 G) Troverse all nodes from 0 to V-4. Next unvisited = 3 —> visite 3,2 (Comp 3) belonging to different ee: 3. Tf o mode is not visited, it means it is AlL modes visited. Done | « We can find all components using port of a new component. = DFS or BFS. 4. Start DFS from that node and visit all / COMPLEXITY } eo Se a ae Cee me : | i WHEN To USE ? ' (0) (3) (6) & reachable nodes. Mark them visited, | Tine: aver) | / To count number of components 5. All visited nodes in this DFS belong | Space OCV) (visited + recursion/stack) | | ¥ To label component id of each node i to the same component. } Where, wv To solve problems involving groups i Connected Components. = { 0,4,2,3} , {4,5,6} ® {3,8} 6. Repeat until all modes ore visited. if Vow number of vertices H | ¥ Useful in many graph problems | Total components = 3 | E = number of edges \ | (e.g, making network connected) | ra = a ‘ 4A. C++ TEMPLATE (DFS) 4B. C++ TEMPLATE (BFS) 5. EXAMPLE RUN (DFS) 6. ADJACENCY LIST USED (Example Graph) Hinclude vector> getConnectedComponents_BFSCint V, Stark iO) Cat: visited) News Neighbors using namespace std; vector>& adj) { tor visited(V, 0); - void dfsCint u, vector >& adj, RAE gic ATE coiginiarhai DFS(O) — component = {0,1,2,3} ) > 4.5 ——S— ae vector& visited, queuecint> 4; 4 =e ay: We will troverse all | vector& comp) { for Cink i = 0; Lo < V, ive) { All visited? No. nodes using DFS/ BFS | visitedLu] = 4; Af mark visited if Clvisitea Li]) { f mea component fF 2 > 41,3 t sacs srouig a hiae ic } comp. push_back(u); {4 add to current component vector comp; Next i= 4 (not visited) a SG. 3 ee es for Cit v + adjlul) { q.. push(i); | 2 their respective if C'visited(y]) visited[i] = 4; DFS(4) > component = {4,5,6} 4 => § } components. \ } dfsCv, adj, visited, comp); while C!q.emptyod) { = wee ee Dee } int uo = g.front(); 4. pop); re 2. THe as hi back Gin): Al visited? No. mz = : " mp. pusheback Cu) 5 ‘ vector < vector > getConnectedComponents Cint V5 foc Cink aol eat tuay { 6 => § y % vector>& adj) { if Civisitedt v1) { Next: i=c% Grob. wisikedd 3 — yeetor visited(V, O}; visitedGv] «4 j vector> components; : h l t DFS(#) —> com tos {7,8} 8 ey forint, a0 tee eke Supeen cv); | VE Clvistted Lil) { Af mew component s vector comp; } } All visited? Yes. dfsCi, adj, visited, comp); components. pushoback ( comp); 2 components . push_back( comp) ; } STOP } } } return components ; } return components ; 9. COMMON MISTAKES 8. INTERVIEW TIPS +f¥ Pa f | i t 9. RELATED LEETCODE PROBLEMS 4i. MEMORY TRICK 40, RELATED CoDEFORCES PROBLEMS e % Starting DFS/BFS from only node 0. x Nok reinitializing component vector. % Confusing directed vs undirected graphs. a 1 | | M Not marking nodes as visited, | | | | | | | | i = a ™ Ignoring isolated nedes (no edges). 8) + Be ready to code both DFS and BFS solutions. | | * 200. Number of Islands (BFS/DFS on Grid) + 547D - Mike ond Foam Ask: Is the graph directed or undireckad? S47. Number of Provinces (DSU / DFS) * B39D - Favourite Sequence fates Caan tha ins ap sig 323. Number of Connected Components in an Undirected Gragh| © 418E - Visiting a Tree Clearly state time and space complexity. cial ae of meet , i Mi aries A971, Find if Poth Exists in Graph + 4030A - In Search of on Eosy Problem a GS 839. Similar String Groups (DSU) + 41336 - Almost Regular Bracket Sequence Think of o ciky map Each component is an island. Explore one. island complekely before. moving te another a wk VISIT ALL NODES, GROUP THEM, REPEAT —> THAT'S HOW WE FIND ALL CONNECTED COMPONENTS ! mn i PAGE 6 | 4. INTULTION . In directed graphs, we cannot use “parent” logic. « Instead, we track the state of each node while doing DFS. . If we go to a node that is already in the current DFS path (visiting stote), we found «o BACK EDGE — which means a CYCLE. i WHEN To USE ? Detect cycle in dependency graphs Check if topological sort is possible Used in Course Schedule (207, 210) i Deadlock detection in systems. : of * CYCLE DETECTION - DIRECTED GRAPHS + DFS Stotes (3-Color Method ) 2. EXAMPLE GRAPHS Graph with Cycle Cycle exists = OF41+352454 Back edge: 4—4 (to a node in current path) indicates a cycle. ae f * ; \ Im directed » back to tor (GRAY node | ire graphs edge an ances ¢ node) i | ! Tn a directed graph , a cycle exists if during DFS we find an edge to a node that is currently in the recursion stack (GRAY / VISITING). 3. DFS STATES (3-COLOR METHOD) 5. ALGORITHM (DFS BASED) 1. Creote stote[:] initialized te O (WHITE), 2. For each unvisited node: Coll DFS(u), 3. In DFS(u): - Mark statelu] » GRAY (1) ~ For every neighbor v of uc + Tf stateLv] =» 0 + DFS(v) + Tf stateLv] == 1 - Cycle (back edge) + IF state[v] == 2 + Ignore ~ After all neighbors processed : Mork stateLu] = BLACK (2) 4. any DFS call returns true —* cycle exists. STATE ARRAY EXAMPLE | — 6. C++ TEMPLATE tinchude using namespace std; bool dfs(int u, vector& adj, vector® state) { stoteCu] = 1; // GRAY (visiting) forint v : adjlul) { af (state[w] == 0) { iF Cdfs(v, adj, state) retumn true; /f cycle found } else if (statel[v] «= 1){ return true; 4 back edge — cycle Hf if stately] == 2 > already processed, ignore } stokeLu] = 2; return false; 4/ BLACK (done) } bool isCyclic(int V, vector & adj) { wectorcint> state(V, 0}; Af Oewhite, Legray, 2*black for(int i= O;i<¥, i+) { if (stateli] == o){ iP (afs(i, adj, state)) return true; } return false; t | | Index: O 292 3 4 | | | state: 0 4 0 2 4 1 | wGw Bs G 1. ee ee ee if 43. RELATED LEETCODE PROBLEMS * 207. Course Schedule (Cyele Detection) + 240. Course Schedule IL (Topological Sort) . 2342. Building a Metrix With Conditions * 1462. Course Schedule IV * 802. Find Eventual Safe States 14. RELATED CoDEFORCES PROBLEMS : * 59A - Word 206 - Dijkstra? 1679D - Shortest Cycle + 427C - Checkposts « 1O00E = We Need More Bosses + Use DFS + 3-coler (0,1,2) states. * WHITE (0) — not visited * GRAY + BLACK (2) —* completely processed * Edge to GRAY node = CYCLE. Graph without Cyele 4. STATE TRANSITION (3-COLOR) State Veluwe Color Meaning (DAG) he Node not. Unvisited ° WHITE visited yet Node is in Visiting < GRAY | current DFS path (recursion stack) Visited 2 BLACK At F (] | | If we find an edge to a GRAY node | om ™ r ! ee © WHITE (0) > Not seen | > Cycle Detected! (Back Edge) | a @ GRAY (41) — In recursion stack ~~ ------—----------- 4 | * BLACK (2) — Done, not in stack a a aaa nS ey, at —_ eee 7%. DRY RUN (On Graph with Cycle) 9. ComMPLEXITY 10, COMMON MISTAKES ‘| ea on] eee a ee a ie fl H i Step Action uw | Neighbor v | (oa gay | cycle? Time OV +E) ™ Using parent logic (for undirected graphs). Wz = z | 5 wv M® Nok marking node os GRAY before A | Start DFS(o) U beeen le pace : OCV) exploring neighbors. a Visit O > 4 ° - 7 oe Oo No bi (Recursion Stock + state[1) #OF bay ts Jie oe cap Ae att Dei eho etal ME fot OP:0. Ns = = all neighbors are processed. % From 3 4 3 calcietems Ne q Vo= number of vertices M Not handling disconnected components e YES ; | 5 | From 4+ 4 4 4404 é ng £ = number of edges (looping over all nodes). e a ao SS SS ee ~, 8. DFS RECURSION TREE (At time of cycle) (a4. Interview TuPs (0) (GRAY) Se ee = | # Explain with colors (White + Gray > Black). | Edge 4-4 is aback | | | * Say: “Edge to Gray node = Back Edge = Cycle”. (1) (GRAY) = i | edge to on ancecter | * Mention it works for directed graphs only, | G) jaa ‘\ | in the current path | & Useful for Topological Sort check, w& 3 | > Cycle | j (See a a re ee ee ee eS = ¢ | ee, 3 es 4 42. PATTERN RECOGNITION E lB bios ERE aes (4) (GRAY) —* If the problem asks to: wv Detect cycle im directed wv Check if topological sort is possible vo Find if tasks have circular dependency = Use DFS with 3S-coler method | 45. SUMMARY 16. MEMORY TRICK FINAL CHECKLIST _ Laop all nodes (disconnected graphs) Use 3 states: O,1,2 Back edge to GRAY node —* cycle - i (| WHITE = We Have Nob seen Te GRAY = Going through Tt (In sect) ) Done with It ED) fi Mark BLACK after all neighbors ® © (1) — im current path Ve = 2 a Fd a In Directed Graphs , A Back Edge To An Ancestor (GRAY Nede) Means A Cycle Exists ! * PAGE ? * TOPOLOGICAL SORT - KAHN’S ALGORITHM */ 2ez2 uz. ( BFS, Indegree , DAG ) such thot for every directed edge u— v, u comes before wv. 4. INTUITION * Used only for DAG (Directed Acyclic Graph). S. See SS 3. KAHN’S ALGORITHM (BFS) 4. DRY RUN (On above graph) * Arrange nodes in a linear order Edges : a ere 3 Seguin cat Step Queue. Pop Result Indegree Array respecting all. dependencies . 5) 6 (CIndegree=0) (Node ) (Order) [O42 See 59 Bacinllh een (BES ) 2. Push all modes with indegree = 0 Tritiel . n's Algorithm based alwenys Ss mepegueiae, 9] [54-2] = CJ Ea 205 2.3, 0] Indegrees removes nodes with indegree = O 343 % = = | _ Chie priceqne a 3. While queue not empky : i | [2,0] 2) ihe [s4 alt (4, 4ge0; "45 25] 5-05.35 . front node uw «© TF we can't remove all nodes > 3-4 4 is ss eau fo, 2] | (er = (5,2) = se eli “J i cycle exists (not a DAG). o> 4 ne yiternestlt - 3 E3g.43J fe) (5,2,0] Eten gst cd iO. Seed : each neighbor : — a | meh ae ene ae 5 1 4 oe 4 [1] 3 fees) Pedes, =ae<] ee WHEN TO USE * | decrease indegreeLy] by 4 = paar - io ‘oes > | ee ee eee if eiaaeeliv See 5 Ed 4 _[5,2,0,3,4]| [4,-,-,-, 9, -] dis | ihe Sepesie rent ae | One possible topological order : 6 [+] + |[5,2,03,44]) [-,-,-.-, 7, -] | 4 hes none | Build systems (make, gradle) | Satie: Suk ee ace ) | 4. Tf result size == V — valid topo order Vv Dependemey resolution. r | unique ) | ; s < lo? lbedty,ogcta okt poche Steevie v5 Es af else —* cycle exists (not a DAG), All nodes processed v= Valid Topological Order 5. C++ TEMPLATE (KAHN'S ALGORITHM ) 6. INDEGREE CALCULATION (From Example) 8. WHY BFS (QUEUE) WORKS ? 10. COMMON MISTAKES #include : , 5 { :: PSE Laat 2 we ie ay cea so, Ret amy using namespace std; Node oO ae 2 3 5 * Nodes with indegree O howe no pending | Forgetting to compute indegree correctly. | prerequisites —» they can come now, | | vector topoSort Cimt Vi, wector ¢wector ¢int> & adj) { Indegree 4 4: 0 3 o | ® Not pushing alk initial indegree 0 nodes. | vecter indeg(V, 0); +—______ + After removing such a mede, some neighbors | ; ; i for(int us GQ; u order; 9. CYCLE DETECTION | while (Iq. empty()) { pos - : | + Always check if graph is a DAG, int uw = q.front(); q.popl); H 3. COMPLEXITY * + Tf after the algorithm, order.size() != V shee order. push_back (u); SSS BS —+ some nodes were never processed . | * Explain indegree concept clearly. ~ for ee ; adjCul) { Time 2) ORV Gr ES | H Baader ibe wea | + That means there is a cycle preventing * Dry run on small example. in w)--; 4 Vee 4 a | if Cindeg lv] == 0) q.push(v); Spee: OR ed a a cara Brera) Serer canna ipaere sO | + Mention cycle detection using size check. } | Adike te ‘) once. Each edge is) * Hence, Graph is NOT a DAG. | | } | ae | | processed once. Be ee ee a ee ee | + Kaln's is iterative (BFS), good for large graphs. | return order; ff OF order.size() != Vi + cycle exists | Vo= number of vertices. | a a f L at ee ee a ee ee eee } -o-- — \ | SS ' mpeorkant : Kahn's Algorithm mot only gives | | i i i -, 1 E = number of | 1 (This returns one valid topological orde ke Ma edges. Fr eects he OR cempe neha’ omer meee 21mm | I Tf order. size() != V — Graph has o cycle ! ke oa ees a i Lael Sie eae yf 42, RELATED LEETCODE PROBLEMS 13. RELATED CODEFORCES PROBLEMS 14, REAL LIFE APPLICATIONS 15. MEMORY TRICK He, INE CHECREEST 207. Course Schedule ee ee * University course planning en eng tar ae 2] Compute imdegree. 240. Course Schedule TI (Find Order) aoraabe ae sdb at Chay + Build systems (compilers, make.) ieee bana eine with indegree 0 | [¥] Push all 0 indegree nodes 269. Alien Dictionary vere ey + Job scheduling .— ore “FREE” nodes (no dependency). | fel oPvsticaa sich Gina 340. Minimum Height Trees re oe nAN | + Package dependency resolution 4 Remove them, free others! ED | Fl’ Bidncecsaigie’ beagee Vv) Seo ae eer * 4434F Asya and Kittens = CPU task ordering z So : =) fel Check fail nodanccere scceaneil an wk = KAHN’S ALGORITHM = BFS + INDEGREE — GIVES TOPOLOGICAL ORDER & DETECTS CYCLES IN DAG! wy PAGE 9 14. INTUITION Start from source node . « Ak every step, pick the unvisited node with the smallest distance (greedy choice). * Once a node is picked, the shortest distance to Relox all its cubgoing edges. © Repeat until all nodes are processed. it is Finalized . f WHEN To USE ? | Single source shortest path i All edge weights ore >= 0 | Graph can be directed / undirected | Used in GPS, Networks, Routing, | | * DIJKSTRAS ALGORITHM 2. EXAMPLE GRAPH (Undirected) 3. DIJKSTRA’S ALGORITHM (STEPS) ( Non- Negative Weights ) 4. Initialize dist(,] = INF for oll nodes except source (dist[sre] = 0). 3. While pq is nok empty : a) b) c) a) Pap node u with smallest distance d. Tf «4 is already visited, continue. Mork u as visited (finalized) For each neighbor v of u with edge Tf disttv] =» d+ w then distlv] = d+ w Source = O Find shortest distance from 0 to all nodes. Push (distLv], v) inte pa- 4. After the loop, dist[,] contains shorkest distance from sre to alll nodes, 5. C++ TEMPLATE (Using Priority Queue) Hinclude using namespace std; vector dijkatra€int V, vector cvector>> fadj, int src) { const int INF = 4e9; vector dist(V, INF); 6. COMPLEXITY 2. Push (0, sre) in Priority queue (min-heap ) - te Priority Queue , Greedy | ee “Disestees Algorithm finds the \ stat ds fe «me = 0) wigted graph sith NON-NEGATIVE] 4. DRY RUN (From Source aa | edge weights Y: _ hse, - % [ | distl0..4] PQ (dist, node) | Po Relaxation / Update | Sea | ve : | r [fai fae, OBE sm) nh | fc) [to,0)] | - Init oO =o «© «© wo | KEY IDEA ||) 4 | £¢0,0)] | (0,0) One (4), 0-93 GF) 0 kw Fw | ————— ima: 4 4 4 — | | prle clues oempan then a: Jetcasabueasyy:. lucayays | teP2 Gs 83 2) | og og sg ws | closest urwisited node | | | | Wpdate 3. from 7 to 6) \ k A Vy — <— a lie | Firsk using 0 min-heap| [¢5,2), (6,39) | (5,2) | a-»4 (5) o 4# 5S 6 (priority queue). This greedy choice works 4 only because alll | [¢6,3), (40, 4)] cy | s-s4-C4) (Update 4 to 9) | o* es « F weights are || CCF, 4), (10,4)] a4) No update E 4 5 6 | er ee [| Final Shortest Distonce from 0 [o, 4,5, 6,7] ] 9. SAMPLE Time. O((V + E) leg V) | Input 10. COMMON MISTAKES Space Vee Sc st oye x Using Dijkstra when negakive Where, Edges (uv w) weight edges exist. Priority, queue , vector >> pq} df (dist, nede) E = number of edges = 9 3 distCsre] = 0; 1 2 pa-push((O, sre)}; 3. IMPORTANT NOTES 4 3 while (! pq. empeyt)) { * Works only with NON-NEGATIVE weights. 2 0 4 aute Cd, ul] = pa-tep(); pq.popt); CIF negative edges exist, use Bellman Ferd.) 4 4 Cd t= dist[u]) continue; ff already found better poth + If multiple edges exist, take the smallest one o 4 for (auko Rik : adjCul) { + Tf graph is disconnected, seme nodes unll ink vo = ik. First; remain INF. Source = int wo = ik. second; if (distlv] > d + w)f distIv] = do + wy; pa: push ((dist€v], v))i } } return disk; 12. RELATED LEETCODE PROBLEMS df disk[i] conkoins shortest distance from are to O° } ff adjCu] contains {v, weight} pairs. 13. RELATED CODEFORCES PROBLEMS « Each node can be pushed multiple times in the through edges hove non-negative weights. Hence the \_chosen distance to ‘uw’ is Final } = WHY GREEDY WORKS ir \] | Bree we pick the clozest unvisiked made “uy | | there cannot te any other shorter path te ‘a’ | | 1 biceaa but processed once. ~———-—., 0; 4 95 Output (dist) : 4 7 Net using priority quewe, which 4 makes it O(V"), 2 5 i Forgetting to skip outdated entries in PQ (if d t= distfu))- if weights can be large). @ elie © urwisited nodes becouse oll remaining Er 14. REAL LIFE APPLICATIONS Read Improvement New Year and Reads 743. Network Delay Time 20C - Dijkstra? 787. Cheapest Flights Within K Stops GORD - 1334. Find the City With the Smallest 641D - Number of Neighbors ot o Threshold | 43286 - 2203. Minimum Weighted Subgraph | 191C - Juice Ehab and Poth-etic MEXs * GPS Nawigation * Network Routing * Shortest Path im Maps Internet / Computer Networks Game AL (Path Finding) 41. WISUALIZING PROCESS Step O: Start at 0 +2) 6 @) +2) 3) @) —@) (4) (4) tall all nodes ore visited 15. MEMORY TRICK — { “Pick the smallest, | | ) Fin ik, then Relos | is neighbors.” e a | ee 46. QUICK CHECKLIST AU weights >= 0 ? dist[sre] = 0, others = INF 7 Min-heap (priority queue) used ? Relat all neighbors ? Skip outdated entries ? Find dist[i] BEBEBB Y) is answer ? | %e =9DITJKSTRA’S ALGORITHM = GREEDY + PRIORITY QUEUE —» SHORTEST PATHS IN NON-NEGATIVE WEIGHT GRAPHS | * | PAGE 10 4. INTUITION * We try to relox all edges repeatedly. « After i-th iteration, distlv] contains the shortest distance using ok mosk i edges. * For a graph with V vertices, the shortest path can have ak most (v-4) edges . * So after (V-4) ikerokions, we get the correct shortest distances (if ne negative cycle). WHEN TO USE ? Grips acy fast e hepa aij, ieee) Need single source sherbest poths Teas Sete! one ee Saoe, F Works on Directed & Undirecked graphs | 2. EXAMPLE GRAPH im) ( Negative Edges ) 3. CORE IDEA (DP APPROACH) * BELLMAN-FORD ALGORITHM + DP Approach, Relax Edges 4. DRY RUN (From Source = 0) This. 5. C++ TEMPLATE dtinclude using namespace std; skruck Edge { int ow, ¥, OS} 4; veckor bellmanFord(ink V, vector Sedges, ink sre) { int INF = 1e4; vector dist(V, INF); dist(sre] = 0; ff relax all edges (V-4) times. consk for(int it = 4; i ce Wed; ivedd bool updated = false; forCauke fe + edges ){ ime uw # @.u, VS OL, ww HF el) iFdistCu] '= IMF a&@ distlud + w < distlyv]){ disttv] = disttu] + w; updated = true; } } if (lupdoted) break; / optimization } return disk; // distances (if no negokive cycle) | Ne 6. NEGATIVE CYCLE DETECTION After (V-1) relaxations, do one more iteration, TF any distance con still be updated, then there exists a Negative Weight Cycle reachable from source. bool isNegakiveCycle (int V, veckor Redges, vector &disk){ edges ){ v= @.yv, forCauko Se : wk w= e.u, WCdistCu] != INF a& distlu] + w < distlv]) if negakive cycle wre; return true; } return folse; j he I Tf negative cycle exists — shortest pakhs NOT well-defined (can be -— 20) ©)! Let diskLv] be the shortest distance from sre to v. Tnikialize dist{sre] = 0, others = INF. Repeat (V-4) times : Relax every edge Catv, wv) IF distlu] + w < dist(y], updake. distLv]. is some os DP where state is distance till i edges”. RELAXATION OF AN EDGE Cu — v, If distlu] != INF ond distlu] + wo < distly] | distiv] = distlu] + w I Bellmoan-Ford works even if the graph has NEGATIVE EDGE WEIGHTS. Tk also helps to detect NEGATIVE ».- CYCLES... Y * < : : ; ; | T T T aa Edgissheleges 4ist(O] | distlt] | distl2] | distl3] | distl4] | Comment aw | Gn order) | | 1 iT | | Init - | 0 | = | « © Initial | | O-4, O42, 143, 4st (ied) | ° 7 44 44 | Using ok most 1 edge | 8% Get) | ca na, ae, 3-04 | | | | | | And (i=2) PSAP OS Aiki oO ? * 42 Using ak maak 2 best eid Ces ee ee ee eres | "3 = | | | 3rd (ie3) pede abi ake o 7 4 2 ing ok most 3 —— O80 4 943, a4, 34 =a < = =, | 1 ef ul 4— _— | 4th (is4) Ae aa aot ° ? 4 2 Ne chan: je | dea, 23, 2a, 2-04 | [ries | ( Final Shortest Distances fram O EO, 6%, 427 | 7. WHY IT WORKS ? After i-th ikerakions, disk[v] is shortest Ary shorkesk pokh has ok mosk W-4 edges (mo repeated vertex in simple path). | So after V-1 ikerokions, we get correct shorkesk distances . Extra ikerokion helps to dekeck megakive TIME COMPLEXITY O(V * E) SPACE COMPLEXITY | o(v) | 8. EXAMPLE EDGE LIST 9. COMMON MISTAKES Edge anes | Weight Cu) BM Running only once (need V-4 kimes). —— M Forgetting to check disttu] != INF Cd 6 before relaxing. eae § 7 ® Nok checking for negative cycle. % Integer overflow Cuse long long if i273 5 weights ore large). M Assuming ib works faster Uke Dijkstra ‘teas 8 (ik is OCVED). 9-553 7 Ferre aie eee eer eee = H 10. INTERVIEW TIPS | 24 4 9 | " ; ; : | ie _ | # Explain DP viewpoint Cok most i edges), | 34 4 =-2 | %& Mention negative cycle dekeckion step. | = = | *® Compare with Dijkstra (handles. negative. | edges but slower). _# Early stopping optimization. tr | a 44. SAMPLE INPUT / OUTPUT 12. RELATED LEETCODE PROBLEMS 13. RELATED CODEFORCES PROBLEMS 44. REAL LIFE APPLICATIONS Input: + 787. Cheapest Flights Within K Stops + 608D - Read Improvement eee + 743, Network Delay Time + GLE - Ehamy i wnok ae . 3ay a + 4334. Find the City With the Smallest + 1030F ~ In Seorch of on Easy Problem fra. uF 44 4 Number of Neighbors ok a Threshold | , 43g5e - Direct Connections 4 2 8 5 lp) ome | + 4976. Number of Ways bo Arrive ot ; | + a94c Tae Output dist : Destination O8 4ee * Rouking in networks with cost rebates * Currency exchange (arbitrage debeckion — negokive cycle). + Economical systems and optimization. @ 1S. MEMORY TRICK Se V-4 kimes Relax oll edges + 1 more time to check cycle CV Minus One, Plus One) 2) | “J 46. QUICK CHECKLIST Initialize distfsre] = O, others = INF [4 Relax all edges (V-4) times One extra iteration to dekeck cycle Works with negative edges Tf updated in extra iteration — negakive cycle Y) te = BELLMAN-FORD DP + RELAX ALL EDGES (V-4 TIMES) —>* WORKS WITH NEGATIVE EDGES & DETECTS NEGATIVE CYCLES ! x | PAGE 12 4. INTUITION * In normal BFS, all edges have weight 1. 2. EXAMPLE GRAPH 0 7 7 BF S ( Edges with 0/4 Weights ) Deque , Optimization 3. HOW 0-4 BFS WORKS ? * Dijkstra, works Fer any non-negative Maintain diskl] arroy Cinikielly INF, dist{sre] = 0) O-1 BFS is a special case of BFS for graphs where every edge has weight © or 4. It finds shortest distonces in OCV + E) using a 4. STEP BY STEP DRY RUN (From Source = 4) deque (double ended queue). : Res Deque * distil] weights but uses priority queue (log V). » Waerkodagne Step |e on ta’) Popped | Relaxed Edges Updaked distl] ig ae a as « O-4 BFS is opkimized, Foor yraphs where i T 7 = = nee 7 a Pop From front. oO [4] - | - disk[4] 0 © INF INF INF INF ag eg aig, Cheese + For each neighbor v of node u with edge weight w * We always prefer taking O-weight edges Gakendee 135 te [1] 4 472 (0), 443 (4) | distla]-0, dit[3]=1 | 0 © 4 INF INF First don't increase distance). 4 . : fi | i ist (they % d ~ TF disttu] + u < dist[v], update dist(v]. J} 2 [2,3] 2 | a+4 (4), ass (4) jditfe]-4, dtfS]-4 0 0 4 4 4 Sey cle gaat them “hee Pranks ab deapias - Tf w=+0 > push v to FRONT of deque t | -------- = Sate eetenieeteereene = i ws hes 3 [3, 4, 5] 3 3-4 (0) ne change (distf4]=4)/0 0 4 4 4 WHEN TO USE ? a ty Sheen BACs Seni ile =| beer je eg [ese aie oe] — a | : SS 4 4,5 4 445 (4 ast{S]=4)|0 O 4 4 4 ReMi eotng iene tae Sree | (Why does it work ? | C4, 5] +5 (4) ine See S Cs]=4) Bokeie denny, oka lena ! ; Sara) O-ssight edges dove increase diatence, so we exglere then | | 5 (s] 5 = = OO) et 8 Undirected or Directed graphs first (front). d-weignt edges incranse distance by 41, so they | | I Find shortest distances to all nodes. al Sie ae i 1 | = = | Vo Faster thon Dijkstra (O(V+E)) ! || are explored later (back). This simulates Dijkstra untheuk | | Fisal “akert di t ie Pose 4] tee eae? ee i See ee. - epnerey quese For 0/41 weights. 3 ae J 5S. Cr+ TEMPLATE (0-2 BFS) 6. DEQUE OPERATIONS 4. EXAMPLE INPUT / OUTPUT 40. COMMON MISTAKES ftinclude ee --—-, using namespace std; * push_front(x) —» add te front Input : i Using sermol qnive Cull give uireng result), | consk ink INF = 4e9; E ee Sey aie oa vee ae Kare XK Using + ¢ give ). | veckor zeroGneBFS Cink n, vector ¢veckor dist(m, INF); + pop-Front) > remeve From Front Edges: Cae a): | i a n | dequecink> dq; \° empty () —> check iF deque is omety | 1 a o % Not updating distance before pushing . distIsec] = 0; 4 3 4 | x Assuming ib works For weights > 4. | dig. push — front (sre); 7. WHY IS IT FASTER ? 2 4 4 | inikielizk ‘ H while (Idq empty ()) { On nas | Not initiolizing dist(sre] = 0. ink-weee dq Fron Obs cag. pen alrent: * Dijkstra (with priority queue); OCE log V) 2 065 a ee “ forlauto &p + adjCul) { * O-4 BFS: Ov +E) 1) = o pn ye int vom p. first; * Because we only have two types of weights (0 or 1), 4 5 4 | 44. INTERVIEW TIPS wt wos p. second; // w is O or 4d we can aveid using o priority queue. TFT ee a | €(dittu] + uw 2 disklv}) { ae Ber cr a ah: Source = 41 & Explain Haak it's on optimization of Dijkstra disttw] = disttu)] + ww; oe duikances for Of 4 weights | Flas © 0) da. push front(w); 5 we Key idea: explore O-cost edges first. Qukput : else da. push_back(w); = oe EeaE Bc : ail 2 ke Deque maintains nedes in non-decreasing \ } } From a | Tov | Weight (a) Condition Ackion — oe order of distance. 1 T T 1D), ye BE wy Se kay: | return disk; us w= O distCu] < distlv) | push front(v) C i . + : J Le siege GEM ASED | } 1 Tine Complexity: OCV + EJ ~ — - & Spoce Complexity: OCV) +a Hf Spoce Comnplesitiy : otv) | uoy wed |distCod +4 < distlv]| push bock(v) | eee = a ane 12. REAL LIFE APPLICATIONS 43. RELATED LEETCODE PROBLEMS 44. WHEN NOT TO USE ? 45. MEMORY TRICK . QUICK CHECKLIST + Teleporters / Zero-cost roads | + 2290. Minimum Obstacle Removal to Reach Comer Flipping bits (O-cest) vs nermal moves (4-cost) | . 4368. Grid problems with O/1 cost moves Stake machine / automaton shortest path g— 9 | * 4284. x TF edge weights > 1 (use Dijkstra) % TF megokive weights exist (use Minirwen Number of Flips ko Convert, ~ I Bellman - Ford) Binary Matrix to Zero Matrix EE | G Minirrurm Cost bo Moke of Least One Melid Poth in ao Grid All edges have weight O or 4 ? Deque initiolized with source in Front ? O-weight push front, 4-weight push back 7? Distances updated before pushing ? Time Complexity OCV +E) ? SHAH |e Y) | 0-4 BFS BFS + DEQUE OPTIMIZATION FOR EDGES WITH WEIGHTS O OR 4 —> FAST, SIMPLE & POWERFUL | * PAGE 13 1. INTUITION * In DAG, we can process nodes in topological order. + Every time we process a node u, we relax all outgoing edges (u — v). * Since there is mo cycle, once we precess a node, its shortest distance is Final. * This is similar to DP: states are WHEN TO USE ? Groph is a DAG Vv Need shortest path from a single source to oll nodes 2. EXAMPLE GRAPH 3. CORE IDEA (TOPOLOGICAL DP) 4. STEP By STEP DRY RUN SHORTEST PATH IN DAG (Tertegicst DP) DP Oneing, Relation In a DAG (Directed Acyclic Graph), there is no cycle, So we can find vf Faster than Dijkstra, when E is large Ne a 5. C++ TEMPLATE #include uding nemespece std} eonok ink INF = 109; | veckor int» shortestPathDAG (ink V, vector ¢veckor ¢paircint jint>>> Bad}, int src} { wector jindag (V, 0); for Cink us O, us; ues) for(aute Bp i adjlu)) indeg Cp. first] ++; ff Topalagical Sert (Kahn's Alge) queuscink> qj for (ink ie 07 iM; tee) FGndag [i] ** 0) og. push(i); wector tint? topo; shila (1a. ampbal ink w= gq. Pronk); q. pop 0); topo. push . back Cu); ip forlouke Bp: adjlu]){ Y DP Relaantion? ink v= p. first; if (--indeglv] = 0) q. push(w); int ue pok 4} } fare (ink ow 1 Fares) Wade ae] 9 TAT) conreneay HP ranch ferlonte Mp as 2 datfe)] Jf) DP leaker, ain lope Okie vwectortint> disk(V, INF); diatCare] = 0; } Fok (Sk rhe sted } Seon Tee tere A baie dik a4, RELATED LEETCODE PROBLEMS * 743, Nekwork Delay Time (DAG case) rae * 4962. Course Schedule IV * 41857. Largest Color Value in o Directed Graph BE + 1544. * 2685. Counk the Number of Complete Components Path with Maximum Probability (DAG) 415, RELATED CODEFORCES PROBLEMS E for adjacency lisk. asi xample : If dist(2] = 2, edge 2-*4 unth w= 7 %. WORKS WITH NEGATIVE WEIGHTS Tf dita] + 7 < dist] disk(4] = dist(2] + 7 + Yes, it works even if some edges howe negative weights (because 40. WHEN NOT TO USE ? a © there is mo cycle), 9. WHY TOPOLOGICAL ORDER ? + All edges go from earlier nodes in topo order ko later nodes. # When we process u, all possible best paths * tou are oclready computed. * Se relaxing edges from uw gives correct and Final andwers for outgoing neighbors . Tf oll weights are 46. REAL LIFE APPLICATIONS 20C - Dijkstra? Cap + Task scheduling / build systems VASD = Mike ond Paths rt + Dependency resolution BBFC - Demand the Strictly Increasing Path —_ + Lengest / Shortest time to Finish tasks GOFE - Dijkstra? (DAG variant) + Critical path in preject management 442A - Petyo and Divisers (Tope ordering) | # Data Flow in compilers oF ew wee rr SF Ff ww nue YP wee FF RTF the graph hes o eyele | ink wg. Fern), pet]! HX TF we need shortest path between all pairs (use Flayd-blarshall) o 2 & F 6 8 non-negative and graph is general (use Dijkstra). © 17. MEMORY TRICK ™) [Daa + Tepelogjcol Onder + Relasation | = Shortest Poth in O(V+E) | ———— i} | ee ee Oukput (Shortest distances from 1): HB Using Dijkstra unnecessarily Cslower ). # Topological Order (one possible order): shortest path from a source to all 1. De Topological Sort of the DAG. ‘ to GOR EY sain Tatintall” 2. Initiolize dist{sre] = O, others = INF. [14243-44576] Order and Relaxotion (DP approach). — 3. Trowerse nodes in topological order. Trikializakion : ie ee ec mceselahi suas dist] = 0, others = INF | Node Relaxed dist] dist 4.8] edge uv wi weight w Step | Edges Updated dis! relax the edge: | Processed Nede| 4 2 3 4 5 6 i] Tait - - ‘0 INF INF INF INF INF | if distlu] + w < distlv] dist | 0. |INF|INF|INF INF )INF) | [| teva (2), 2-03 Go) | asta 2, inEae4 | 024 INF IN aM | | aint [wis “diet faye us 2 2 2-4 CF) dist[4]=24+729 o 2 4 INF hi — $$$$$_____' 3 3 3-08 (3), 3-65 (2) | distl4Jemin(4,443)"7,/ 9 39 4 7 & INF a -—==— sa dist[S]=4+296 | Why ib works ? | 4 4 46 (4) dist[6]=74198 oa 47 6 8 Topolagical order ensures that when we 5 5 sé (5) dist[G]=min( 8,645) =8 fo24 76 8 i Poses SU afer ee Tee es «| « - No change oa476 al | st considered. Se reloxakion gies cerreck, == a ils Seca corneas. armies | shortest distances | F : eS ee See eee ee - Final Shortest Distances from 1: [0, 2,4, 7, 6, 8] (for modes 4..6) 6. COMPLEXITY 8. EXAMPLE EDGE RELAXATION 8. SAMPLE INPUT / OUTPUT ii. COMMON MISTAKES ee SE Time otv + £) | From u Tey | Weight (4) Condition Ackion | Trput : % Forgetting topological order. i Space o(v +E) wv tw] a) | = | F eadewcaata | Vrege = Bowe = at % Nok initiolizing distlsre] = 0. | . —_ =e = | (V For stack/queue & dist), ‘ez a edge: | Edges (uv ws) % Relaxing without checking if distlu] '= iis | | i | i) RB Assuming ik works on graphs with cycles. 43. INTERVIEW TIPS | ow First identify iF the graph is DAG. | & De topelegizal sort (DFS or Kaha), % Do DP relaxation in that order. w Time Complexity is OCW +E), % Works with negative edges (no cycles). *& 48. QUICK CHECKLIST Is the graph a DAG ? Got the topolegicol order ? dist[src] = ©, others = INF ? Relax edges in topo order ? Final distances updated correctly ? B&E888 wk SHORTEST PATH IN DAG = TOPOLOGICAL ORDER + DP RELAXATION —> FAST, EFFICIENT & WORKS WITH NEGATIVE WEIGHTS (NO CYCLES)! | PAGE 15 MINIMUM SPANNING TREE (MST) ¢krseots atgerthn) 1. INTUITION Greedy , DSU, Sorting An MST of o connected, undirected, weighted graph is o subset of edges thet connects all vertices wikh 2. EXAMPLE GRAPH 3. KRUSKAL'S ALGORITHM (STEPS) minimum total weight and has no cycle = We need to connect oll vertices 4. STEP BY STEP (USING KRUSKAL'S) nahi cass ener 1. Sort all edges by non-decreasing order “ote cn ‘ OE watighh: —_—* weight s We can't include any edge thot a : eet <= cee & Thikialine DSU! Ce all. wetbizes: } “Edge (cet | Misane Step | Edge (u,v) | Weight | Find(u)| Find(v) | Take? MST So For | Teal ? rat ; ie 2 cae alle ae ai| ose : _ Piss te ean & te Ve (Orsety aig iS ms anaes laa ¢ | eae | a D |.cesy | 4) 2 | 1 [eee | that always picks the smallest * For edge (u,v, w): Be - one | —_ | == } = | 4 2,5 2 2 2,5 2 2 5 wf 2,4), (2,5 3 eaiye (Mheh doesn hijiereshaita: cela If Rind(u) te Findlv) (no eyele), L side z Bsa Be a chi a | © Uses DSU (Union-Find) to debeck cycle. (3) or Uk ada MST ond 3 (4,5) 3 3 (4,5) | 3 2 2 x fog) {(2,4),(2,5)} | 3 a ec eee union(u, v). | (3,4) 4 4 3,4) 4 3 a2 | 4 | €¢2.4), Qa, 5), (3, a} ? t ? : : | | WHEN TO USE 4. Stop when we have (V-4) edges in MST. 5 (4,4) 5 5 (4,4) s 4 2 “| 1.4), (2,5). (3,4), al 42 | ¥ Need MST of an undirected | z, ; i ; oo z Gool : Pick edges to conneck all WHY IT WORKS ? é (4,3) 6 é | (1,3) | é a 2 X Cg) | (2,4, (2,9),08,4), (4.4) 42 | 7 Grogh is connected (or we con | 5 nodes with minimum total weight La Abunys picks the smallest safe edge. 3 (4,2) 40 # | G.a)40) 2 2 2 — |x Cegeled | ((2,49,(2,5).03,4), C49) 42 ) | i a L a i L ail | ¢ ). A no ‘ t get MST for each component) | ret Sos | + DSU ensures no cycle is formed. Sy ge ee eee cas + By Gh Property, this builds on MST [mst Edges (2,4), (2,5), (3,4), (4,4) Total Weight = 42 | 5. C++ TEMPLATE (Kruskal's with DSU) 6. COMPLEXITY 7. KRUSKAL'S ALGORITHM (PSEUDG) 8. WHY GREEDY WORKS ? Pinckude , perank,. Honk; 93 2. make-set(v) for oll vertices sdgjettret, Anesth! Vechsr eget | | 3 i i | DSUCint n){ DSU operations ; OCE «(V)) 3. MST = empty + By Cut Property, this choice is safe % Nok using DSU / wrong DSU implementation. | pares vented ed 4 hese : Eat : - | rank.aasignintd, 0); ( ) dc Ra a aaa Cia re a nate igen: + Repeating this builds the optimal MST. % Nok stopping after (V-1) edges | for (ink i= 0; ice mj e+) porentLi] = i; Tated OLE log E bey sy M Using wrong comparison in sork. | } ul red Ca, Ve Find lw): u é | int Find ink x ){ Space O(V + BE) ne ere 4. WHEN NOT To USE ? ® Forgetting that MST exists only for | W(porent[x] '= x) parent>x] = find(parent>x]); // path compression aoe undirected. aia ! } rekurn parent»); unientu, v) For Aivacked graphs Ckrusk doen kc 4 ae — i a ie ban stv at cA ie “rca Ae heernaii if size(MST) =* V-4: break X If graph is ai Ae gon oe z 7 a = findla}; b = Findlb); ay ee, q (Almost constant) | 5. return MST (we get MST for each component) Rapa Geely chia + ce taal WirankCa] < rank[b])} perent[e] = b; : else iF(eankCe] > vankCb}) parerthb) = 4; a Beat coma Seer renee ree eae SS robtiiehariehes else { porent(b] «a; rankla]++; } f We stop once ue ie (v-4) ‘high 1 Cause dynamic MST structures) (shew sorted edges + cycle check) re becouse MST of V nodes has exactly 1 we Explain DSU (find + union) roles. gEruck Edge{ int u,v,or; fj | (V¥-4) edges > g i G) \* Time Complexity = OCE leg E) * bool cmplEdge $0, Edge &b){ return ow < bu; } — Bi pe a an a a er i ‘ es AO 42, SAMPLE INPUT / OUTPUT 43. RELATED LEETCODE PROBLEMS 44. RELATED CODEFORCES PROBLEMS 16. MEMORY TRICK 4%. QUICK CHECKLIST Input - =i ss alas: ans a =e Ss a SE ae el VeS, B= F + 4584, Min Cost te Connect All Points + 6O%E - Minimum spanning tres, For each edge : ; BH) Sorted edges ? aa te ae [output * 1435. Conneching Cities With Minimum Cost + ALIFE - MST queries SORT =» PICK —» CHECK om DSU initialized ? ee ae gee MST Weight = 42 4468. Optimize Woker Dickribution + 8B8C - Minimum spanning tree for each = ADD =<» STOP ob Vet Cycle check with find() ? 3 . : MST Edges : © 4489. Find Critical and Preudo-Crikical. ais idigt Grerieeh) ' (sPcs) , Shas eV eas, 2 Se a (2,4) (2,5) (3,4) (44) | & tied Shanning hes oor oan ee ae CE) TA Total weight caleulabed 7? V) 3 4 4 4 3 y, %e MINIMUM SPANNING TREE (MST) = KRUSKAL’S ALGORITHM = SORT + GREEDY + DSU + NO CYCLE = OPTIMAL CONNECTION! * | Prim’s Algorithm grows the MST MINIMUM SPANNING TREE - PRIM’S ALGORITHM (Priority Queue, Dense Graphs) metas PAGE 16 4. INTULTION 3. ALGORITHM (PRIM'S) 2. EXAMPLE GRAPH 4. STEP BY STEP EXAMPLE (Stert from 4) = We wank to connect oll verkices with minimum total cost (no cycle). 4. Start From ony vertex (say 1). 2. Mork it visited. Push oll its edges Step | Current Vertex Edge Picked nee ee Tetel PQ Clipe queue) 5. COMPLEXITY » Start From any vertex. to the priority, queue. Added, (a, uy) 7 \adeight, (min-heap by weight) ee a: Repeatedly pac the -ymnriuin reagan 3. Repeatedly pick the minimum weight 16 4 - - ) (4-2,2) (4-3,6) [ Using Prierity Queue edge thok connecks o new vertex to edge (u,v). i = = —S = = ; (Min- ) Adj Lisk : | ll - - = 5. - 7 iis ner: Bees er ieee aap a. | | 4 2 | (2, 44 2) | 4-2 2 (a-3,3) (1-3,6) (2-5,5) (2-48) ree * Uses Priority Queue (win-heap) te - Else + add edge te MST, | 2 3 (3,243) 4-2, 2-3 + | Coy oeeeno aay| | = > OE ae Ge ene ee aga mark wv visited, ond push all : Space O(v + E} aa : ce = wl Groat oaNURY eau | 3 4 (2,344) 4-2, 2-3, 3-4 7 (a-8,5) (4-5,7) (2-4,8) (4-3,6) ‘Te | ‘ wu 4 AE | WHEN 0 Wen | 4%, Repeat until we have (W-4) edges | 4 5 (5, 245) | 4-2,2-3,4-4,2-5 | 42 (4-5:9) (2-4,8) (4-3,6) sing eyes Mak V¥ Dense graphs (E = Vv *) a en a ee ee Sree ee ee l Time otv?) er adj matrix available | = fe : — , — a é | [ pe, a a | WHY IT aceieae ae | — otv 2) peeve sti ig | : |, (OE: send seta ee pele Eves mewn | MST Edges: (4-2, 2-3, 3-4, 2-5) | Kruskal on dense graphs | C4 edges conmecting alk 5 nodes) | edge that connecks a new verkex te | | When graph is connected etc iaiaaciat oe | Total Weight = 12 Good for Dense Graphs ee oa eee | i (Cut Property) } ke CE close to v *) | 6. C++ TEMPLATE (Prim's using Min -Heap) %, HOW IT WORKS (MIN-HEAP) 9. EXAMPLE INPUT / OUTPUT 10. COMMON MISTAKES Winckude > & sy ¢ a7 : | Edges wu ow. 4 wacker > pq; KEY POINTS | a3 3 { *“ ke Sa ers : | keylo] = 0; pq. push( (0, 0)); #f start From nada 0 Vo Pick min edge crossing the cut (MST sek vs rest). Suth.ce Oukpu : Not handling disconnected graphs ink botallleight = 0; w Mork vertex visiked a P ae a while (!pq. empty()) { + Push oll edges From thot vertex a5 5 MST Weight = 12 : mn outo Cu, u] = pq. top©); pq. pop); . MAL: iM codekik: “amps Nail a 44 ( 1 S ueetags oe, Leese a Mr ae oa MST Edges: 44. INTERVIEW TIPS inMSTEu] = tran; tokalbieight ++ +; 8. PRIM'S vs KRUSKAL'S (4-2, 2-3, 3-4, 2-5) : ; | For outs (Cu; wk) edjtud { F = ————— i ’ ’ , we Explain greedy choice ond Cut Property. i i UinMSTiv) BA ut < kaylvd { | | Prim’s (PQ) ___ Krasikal 2 sv) | ies J wk Why we use priority queue | keylv] = wt; parent€w] = u; Stratagy | Gaea FAS oF yes nach poke acl caenclhaae edges overall — Penta aeane: : wk, u)); | Com wi ‘s. a mca ae ; Data Structure | Priority Queue | Dinjoint Set (Union-Find) | poe eth Reel | } [TF graph is not connected, | Best For Dense Graphs ['Seaaa Graphs | Time complexity for dense vs sparse. | es koto Weight ; | mint wonvt visit oll nodes. | Time Complexity | OCE leg VI er O(v7) | OCE leg E) te When bo prefer Prim's over Kruskal’ s. | } : - — Cycle Check | Visited array DSU (Find / Union) Sy | 12, SAMPLE RUN (Key updates) a3. RELATED LEETCODE PROBLEMS 14 RELATED CODEFORCES PROBLEMS. 15. MEMORY TRICK 16. QUICK CHECKLIST erties oAialed | so Ars ae = cil + 41435. Connecting Cikies With Minimum Coat + GO9E - Minimum spanning tree for ench edge [qm Pecietle atts (Gane hace Panag = z = | : P | “START + PQ — PICK MIN : al ae ara 6: | sso | = + 4584, Min Cast be Connect All Poinks + 4137F - MST queries @ H] Visited array initiolized ? aes z = he ee] + 4468. Optimiae Woter Distribution in ean pe eo ee | + ADD NEW NODE + PUSH EDGES Start From any node ? Aah 5 = 2 | 5 | + 4634. Pak Lhe Minimum Effork edge (variant) — REPEAT UNTIL ALL ADDED" Skip visited nodes when popped 7? Add 4 | 9 - | - - | 5 i | ° FSF. Cheapest Flights Within i Stops + 43650 - Yek Another Minimizakion Problem GH] Add (V-4) edges -- MST complete ? Add 5 |e - |[- - | - | P ; a =a | * PRIM’S ALGORITHM = GREEDY + PRIORITY QUEVE + VISITED ARRAY = EFFICIENT FOR DENSE GRAPHS —» BUILD MST ONE NODE AT A TIME | * | PAGE 18 4. INTUITION = Break the direcked graph into groups Ccomponents) where, every nede can reach every other node + Keseraju's Algorithm uses two DFS passes and graph transpose. + First DFS gives finishing order. * Second DFS on transposed graph | gives SCCs WHEN TO USE ? ¥ Amolyzing cycles / Feedback loops | Mo Dependency analysis | 4 RESAT, ‘Condaneakion Graph 6. C++ TEMPLATE (KOSARATU'S) include adiCW], revglN]; component. puah,. back Cu); C3, 2, 6,5, 4, 8. %. 4] — Pop order = 41, 7, 8, 4,5, 6,2, 3 % Not clearing visited before 2nd DFS. wacker cink3> via(N, 00), order; componank; For (ink. v + ravglu]) ee ip A HClvislv]) dfa2€v); * Run DFS on G" in this order: X Pushing node ko stack before exploring children wed dfs2(ink u) { = Start 4 + sisiks {4,2,3} + fest SCC Ber ora ee weekor Cueeter ¢ink +> kegaraja(int -) { (should be ofker — postorder ) for Cink wi aikjCul? a Sep A - ~ Next unvisited F — visits {7,8} —» second SCC H (Uaing “DRS wencerginal rapt Gadipean, Cf vialu]) dfat ced, via ansign(ns4,0), order. cleart); é : Nave inated ce eke TCR) Seo daras'see der. pushtback(u), Mf Finished for Cink isfjinenies} FCtvisli]) dfeacs); [| Sreverse oll stigss. } Hf Shap 2 alrendy built: revg + All nodes visited - done = — : 1 Step aera 44. INTERVIEW TIPS | reverse Conder. bagin(), ordar . endt)); DFS on GT | | = ga aaagatneia); 4. CONDENSATION GRAPH (SCC DAG) | te Explain with a smell exemple | p : —— + SCCs form nodes | Build revg | ae Each DFS tree eee sis | Emphasize Finish ime order + transpose. | while reading FC viabad = one SCC i nines | | He Time Complexity = OCV+ E), | sone | compoennt . cleart}; } edge exists from A te B ieay revegiv gra back); | faa bud, [ Repack. until it original graph we Mention ik Finds maximal strongly | 1 y p SER. push backel component J; fear * Condensation graph is a DAG connected components | a J } rebar sees; 42. SAMPLE INPUT / OUTPUT 43, RELATED LEETCODE PROBLEMS 14. RELATED CODEFORCES PROBLEMS 45. MEMORY TRICK 46. QUICK CHECKLIST BEE ios Smart: (Member sr Reeanees + 4270 - Checkposts ee e Did you do first DFS and store finish order ? SG aaa 2) RORS, (Coaren {Schedule lr ) | Edges : + 20BE - Blood Cousins ee ? Aoi? dageas aed aed e MHS. {Conamie) Scheele: AY (Cheam BAG con "ae einem DFS + ORDER + TRANSPOSE > DFS \ [] Did you transpose Une graph correctly? 445, S46, 6-4, 3-7, condensation graph) aie ee : ( se ORDER ve eee { Did you reset visited before 2nd DFS? 748, G47 * 684. Redundant Conneckion (undirected i ahs ree Ls r rT. ; bain Reha is + 400573G = Strongly Connected? ——— Sr | DEE CME TERS RDES | SrOkG "sr SA Beda {4,23} (4,5,6} (7,8) + 803. Bricks Falling When Hit (DSU on DAG) Are SCCa printed/ stored. correctly ? - we KOSARAJU'S ALGORITHM = DFS (ORDER) + TRANSPOSE + DFS ON ORDER = FIND ALL STRONGLY CONNECTED COMPONENTS IN O(V + E) TIME | * | J Y) PAGE 19 STRONGLY CONNECTED COMPONENTS - TARJAN'S ALGORITHM | Single Pass DFS, ta-tink a. INTUITION 2. EXAMPLE GRAPH 3. CORE IDEA 4. ALGORITHM (TARJAN'S) 5 Sie WY STE (DFS cian sae es4 + 9s4- te pl + Kosaraia uses tooo DFS. RRS Epi eerie 4. Inikislize: time #0, sock » empty, we tinku) lou) Stack (bethen wap) | Aikion # SKC Found From, node i Tarjon’s uses one DFS. inStackEu] = felaa for oll uw. | | | = i ae * For each node uw: i = zs a 4 ‘ i Ey [4] Lviatk | + While doing DFS, we maintain 2 RDaY eA cohen acta Ri iaieads |) #7 For sack: sevieited cadens, | le a ae ‘ [4,2] | soit a | discovery time (tin) and lmo-link. Sigube\ls) adhere x Bala): a| 3 3 a | (42,37 vai S,bock to 4 4 lutdlea | 6. COMPLEXITY +: Reaalgh: lbsipaists Cae tieeidagiala using bree edges + beck edges | 3: In Fala): [s | 3 done eae (4,2,3] [return te 2 + oul 2]+4 ——— = From u Cincluding u) using O or Che nas a eck) ae} tinku] = lowla] + +sbime s | a dane a 4 [4.2,3] | cebu be 4 + Malt Jed | Tine Complexity : | by) Push w inte stack, inStackfu) = true Nee | | Pe | toh aoa , | more tree edges + at moat one aeiieape: oe a julie cadalbe: ne 8 4] | 6 4 done 4 0 wus | | ov ED back edge. e win adjlu): —— | * TF lowla] «© tinla] — uw is rook of an SCO : re ? 4 4 4 ta] [nasa DFS From 4 | (Each edge & node | » TF lowlu] == tinfu] — u is the i) TF wv nok visited + dfalw), a | Sf | Pop From stack unkil u ko get that SCC. bese lbacaipaectya) ia Ss + [4,5] | with 5 | 4 visited once) | rook of an SCC. ba ese % (9 - [ee + T4561 [nit 6, back to 4 loafe]e4 | | | r -————- — ii) Else if inStack£y] == true, PS ee . 4 [4.5.6] |wtuen te S > lel S]=4 Space Complexity, © | | WHEN To USE 7 (ase ee a head > lola} © min(lowlel], Hatv)) [as |s a : ei aa =F ov) | ‘A 42 4 | om ki ad oe | | Wo Large grophs (single pass) mee 7) iC all iain Baciakae: pemtintla.| a) 16 tele) == tinla): | see: (4.5.6) ig (stack + arrays) | Wo When recursion + stack is oh SCCs = {1,2,3}, {4,5,6), (F}, (8) Rati etl, casted | Rep bray iil a = ; a th Wee as i ee | ane =oaee beet | AM ~ Vo Need SCCs of directed graph | a re of Ulself Clout a] == Uinta), then a stevte | (alk popped nodes form one SCC). 4% | F done - ? 0) | leu] == tial? ] = pop 7 [ wrta for ary \ ; stig ical ! | sce: {7} | _ — | scc | 4. —— | be SSS ee = i i aa A eh fas| 8 a 8 [2] | raw BES From 8 | rege — ee aes 46 | ® dere, - a 1 | tna == tink 8] = pep. € L sce: {8} F. Cr+ TEMPLATE (TARTAN'S = : : Ee OE talons NS Ure eA 9. DRY RUN SNAPSHOT Winclade edjCh]; = lo [Shack Cempty) | Stock (empty) Stack Cempty) ese cds at int HinEN], LnwlN], tier = 9; F Chenabud ne tink) { r S| | \ bi : : 4 i i : Assign tinlu] = lowlau] = +etime 1 | 1 book inStackEN}; vackor Cink > comp; | | i | i : , , Ee te Show smell dry run stack at; while (2) { L Piste J | ; H % Forgetting to mark inSteckla] = wacker (vector ¢in*? acca; ink = . 5 ere a | : H H | when popping. * s Peaveer : : inSteck[nede] = : (e ; \ | | 3 | aig gaa corp ipuinb ble Crh); ie ie eae ‘asics L | I % Nok checking lola] o= tinlu] H kin] = lowLu] + ++timar: GE Cebda vel brates | eciaraeiea - - - _— - re Ww Skate kime complexity OCV+E). | sk. push) } | ot TF in shock + updike Lola] : {4,2,33 Seca: (4,2,3}, {4,56} S0fa: {4,99} , (4.5.6), | Soper nema a ae cr : 4 (7), (8} % Using global timer incorrectly tr Mention SCC DAG property. for Gat vw) adjlu)) { f Ate haga dic io _ — Th . - so 3 3 Ceci Graph (SCC DAG) : : 2 e ae {A nok wistbad If tewlu} = tintw] nore % Reusing arrays withouk clearing. akwd) r= 7 .. tewla] + min(lestu), lowl+]}; | Nedas are popped in reverse ] —+ Pop shack urbil : DFS Redsh de wach Sec. | | | i pena ge So see Ww 5 dae Gf GnStackEvD) { (7 beck edge ae os — | lofi} = minglowle), aly), 9° --———_$_$£ __— —_" I ae eae ae arte ae : —/ si r > + | Repeat for alk wwisited nodes | (iste the chang = BON Graceland: | je _ — ——— ee = — — 12. SAMPLE INPUT / OUTPUT 13. RELATED LEETCODE PROBLEMS 44. RELATED CODEFORCES PROBLEMS 45. MEMORY TRICK 46. QUICK CHECKLIST ree r - > 5 —_— SS * ns 8, m= 40 Ohatpuk : | + 54%, Number of Provinces (Undirected) + 4270 - Checkposts (SCC + DAG) ; ~ DB dia apie eR Rg i. he sak Edges Cu v): i ce ; ; tin = “Time IT Noted you" | ‘ : 2 jee + 4974. Find iF Poth Exists in Graph | + 400390 - Vacations (SCC) duectinais : facia inc arene mataiors er 4 65 * 3412. Find Connected Componants * 349D - Weke Tee (500) [eadiwim lceapaeaE recy steshe” TJ Update lew using back edges (in stack) 2 4 7 | i ae 8 + 802, Find Eventual Safe States (concepts of SCC) + 4487D - Substring (SCC on graph of sbrings) L Te lewlu] == tinlu] — pop SCC 5 6 | a : a ee ee GH] Re for all unvisiked nodes 64 (ray order Sratdes SOCS is ah’) | qep | 2 peak (V) ee e 4 pis * we =TARTAN’S ALGORITHM = SINGLE DFS + STACK + LOW-LINK —+ FIND ALL SCs =| IN OC€V + E) TIME ! *