Practice Daily, Get Batter, Be Unstoppable! re | YAP Master the Patterns, Solve Ang. Problem! PAGE 12 i. WHY DP ON GRIDS? + Many petame ork oa 20 gra, + We move from tap-lefe (0,0) te bebtom-right [n-2, m-1). * Allowed moves: Right (+) and Down (4). + Optimal substructure + Oerkapping aubprotlems + Use DP Me mach call (5, j), the onever | deperats. on calls (e-4, DD and |G p-4D only. 5. C++ CODE - UNIQUE PATHS dass Solution { public: ink wriquePatheLink my int nd { che Cemcar tlanng apteMEj] = dpli-adt + apClti-s fC return dp{m-1][n-1]; } hs 8, MIN PATH SUM ~ DP TABLE (Example) Grid DP ON GRIDS Unique Paths, Min Poth Sum & More! gy 2. UNIQUE PATHS (Count Paths) 3, DP DEFINITION Problem: Count the number of unique paths From (0,0) te Cn-dym-2) when you can only move Right or Down. Let dpli}Lj)] = sumbar of unique paths to reach coll (i, j) : from (0, 0). Exanplet n= 3, m= 3 L J s|—|—]4 Transition: vital | Ast 4pCeIGj] = dpli-2)0i) + pCi Ij-4] PRRs 6 (from tap * trom left) Ed Ba we | Baus Cases: paths Lt I=|-Le 5+ apLo}fo} + 4 (starting call) + For First cow Cie O)e apCOJEj] = 4 + Foe First ealume Kj +O) dpfiJ[0] = 2 6. MINIMUM PATH SUM Problem: Gietn & grid of non-negative ewmbers, find a path from (0,0) te Crodyen2) such thot Une sum of rumbers in the path is minimum. Example a} 3]a Lette blame lien) 2 os fa 7 Neca the coment Hin Sum atala j SPag ————~ | Pe Ded (Right + Right + Den + Dawn} 9. Cee CODE - MIN PATH SUM snes Solution [ 410. VARIATIONS ON GRIDS @ Unique Paths with Obstacles + Sere alls wre Macked (-1). © gridQilLj] in Vecked + dgfiIEj] = 0. —|—} @ Mesimam Path Sum in Tangle + Sinar Uden tak fs btangalar arid, @D Masini Path Sum + Replace eniel.) sith mel © Cont Pathe with Stops Um 3D DF dp IES DER) = wage be resch (5) fb atape, D Cherry Pickup CheetGode Fi) OD parse geng Foo stark te and ot 3D DF, i) 1] 4) 4 i 1 2 3 z| 4] 3 |[e] + Each call + sur of bop + laft, + Bollom-right call (2,2) = 6 oka unique pothe. 7. DP DEFINITION [ek dpliDEj] = minimum path sum ty reach call (i, j) from (0, 0), Transition: ebpLiQLJ] = geileDL)) + eivledp 10050, del]-21) (freon top or From left) Bane Conan » @e€0KCe) = grialo}to) + Feat cme dgfGTL] + aefoltj-a] + griafoItj] Beak eta: dof i]C0] * dele A100] + gril ILO] ak eeinPathSnml ueckertvackartinkshE grid} { Mele Ink ns griduaiaa(), m= graf). siaa(); wacker Crusher tink?» dpln, vactercinto(m, 0); Tine Complatity: dplONo) = gialo}o), On & m) Ferink jo4s jim, jee) MONG) = dplOILG-2) » grill 0]C4 I: i 9 aLiITOT = aefi-t0C0] + grafsTtoy, | Sees Comet May 0) Ofn * =) + jim jee) r grldQi ML) © inCdedinA]Lj), dpQi Nj AD; Can be eptimined to Ole} er On). pte delet — —_ »% 41. SPACE OPTIMIZATION (FOR MIN PATH SUM) 5 x] Instead of 2D DP, use 1D array: 7 ia x 7 wether int? dele: Neo sts! 40] = gridLo][o | for Cink j=4; j ‘UGered for large grids) le ei] = dplj-4] + getsLOILj] _ _ fer Gok When te Use DP on Grids? 4p{0] 1 a Magen’ fer Cink jm t E Del Rights Laatieal So Start Lp) = mieldptg], pf)-20) + gated, | Mev tien pelh mem B= Ent ) ww Count paths Ca 1 Of With/Whthouk slstacles return apf 4]; Of Mulki-dimensional grids. 12, PRACTICE PROBLEMS 13. COMMON MISTAKES /f\, 44, MEMORY TRICK cb) 15. INTERVIEW Instat fica BONUS FORMULA Th 62. Unique Pathe ee een Tp + lleh ake Grid DF ce wary, common in Cag (2 63. Unique Paina TT Xt Kheg bilan 7 Sig Oo alarviows TF no sbrlacdes, Se, ‘aman Me Unig et inated oF in - - || Seater aak Humber of Unique Paths HO. al i er HF Bad 2 oggentty a FEI 42. nim falling Poth om § ae ie a A 2 Wella Leenatblana Clatma2, ant) EE ars. Deegan Gore aed en pape inde ne ae (Combinskions) I WA. Cherry Pickup He Mek teeing sleacles property pl as + Oplinize space Sf nended eg : ] PRO Trp Drew the grid, define your state, Find the branainn, sot base canes, (OF Grids + DP = P. ful C inakion! é n. and tulld OP table slap by slap! a. PALINDROME PARTITIONING — Prablain ‘we use 20 DP to check if mubatring DP ON STRINGS Palindrome Partitioning & Wildcard Matching 2 cut te (Othe partitions gine mara cute) 7. DP DEFINITION & TRANSITION 8. EXAMPLE = WILCDARD DP TABLE per ye wacker Cwuclar dhael>> pall, etcar sults, 2: fer Link ie OL ic my weed [ s a a 6b uit) = df maw eae : fe fot f 1 Hj HDL aut: 0 eae / | 4 aCe] = Go 0) 70: minleafil, 1+ wtH1]), ) i oe ’ f ra * ait-o 4 © return extant) cami teati}eaen > 6, WILDCARD MATCHING Binblams: Gin ring ond pation p eminining sildeards “7? matches ony single char) and“ retin nny teguance vlading empl), daterming AF pattern matihes entire string. Example: a+ “abefedgiaacdfimda” pt “abted isda” Use 2D DF where dpfiJ[j] = dows Aewarer: True, a(0..i-2] match plO..j-1] ? 9. Ce# CODE - WILCDARD MATCHING ales Baltics | de(iJ)] = true af of Ott] matches pl. j-2] a= Take (ned) =| Tseaileen Ae eo) "Vie Ghiaatias apakiued 4 4) 1F pfje-2] too latter <6 a et 4 ete Soa etal vector twectertheal?® dened, rackorthool Met Falaa)}: a0 + Steal aD ate PT se 2) UF jal o- 7 fi bbe ui a mai CI) + a o/tl/relelele (pint) o= "6 pCOIGD = dpCOIC-21, fer Gah be Pern a 9 ea] ao/Fi/[t{]ti]ele ACTED = dplDp-20 Ce etches empty Hdpli-tIL] Cot matenan one mere che) «db | OF | OF] oT] | OF eect fuera weiss eee F G@l-2] 20 FU pl] Base Cases: e F F T T ahah atheiseeee + dpfo](0] = true F | Fle|t|re ane oe Tenet Onto Space: Diam = aple]Ej) = GEO. 5-2) ore att #9 + dplsJO) = Fela for tO 40. OTHER STRING DP PROBLEMS eiteranees [A Palindrema Substring (Leabode 5) For odd length: [Longest Palindromic Subteqeence (516) a boe (A Distinct Subeequances (115) ? a TH Count Palinatromnic Subsirings (647) Fer evan, length (I Wideard Matching (44) 5 7 : (Regular Expression Mashing (10) ra A] Seramble String (87) a Understand the pater, draw the DP table, "I PRO TIP > Fil bose cones Firsk, than transitions! apl4]04] = trun + Match! 24. TRICK — EXPAND AROUND CENTER r Pe Unahl for: Longast Polindoamic Subatying, ? ot Ln Colors tm OCA?) time, OC2) paca) = J apEsJEj) ~ Futon , raturn defn Jl], 13, COMMON MISTAKES Falindroms Partitioning X Forgaiting hou cases gn 6 & & 3 Handling. '*" tncommectly J] a 2 Mok precompating palindrome table ‘ = Ve 2X Ofibyrona in indices Loa ew Using , . ; 4 fh | 14, WHEN TO USET . . b F of Palindrome problems + 20 DF or Expand Arwurdh Cenber Wf Fallen matching + 2D DP Wf Ag sabstring property + 20 OF Strings Hide Patkerns, Dpslieveels the Solstiog! cr _* "+ PAGE 15 | DP + TREES ieee Tree DP (Example: House Robber III) ip — « rab tis vote 1. PROBLEM - HOUSE ROBBER ITT 2, INTUITION 3. BP STATE DEFINITION Use children's rasa to compas. Geren = Winery tres, ech vile tne AR each mode, san hewn 2 choices: fer each rede, maleiain tue : some monty 44. STATE TRANSITION 5 1) Rob this mile + cannot vob the children Rekurn the masimam manag you ean a TF era thie nade: alka saan hicaacsteea acon 2) Ship thin nada = children con be dpfreda)[0) = man moray fer a Sr ow reba or shipped fo WD ak ce ead geld dp[reda] [0] © anda- val Fsaenple Tras: + dp[teft][0] + dpfright][0] + Wa oben this from beta (ehildeen) | dpCneda) 2] = set mirage children carmel be mobbed) te Up (rout) | 00 wah Ute rede oo as L J @ ge WF we ship this ede: i | Think F- aa is a, ‘ol do Ab eomry, anda: Return: max(dpfroct](O), alpfroot}(1}) | dplreda] [0] = sauldpLiaAt](0], apftereI00]) srabveda]) = nede- onl. + shig[ loft] + ship[right ] + manldpLright ILO), deLsghtL2]) stigfnee] + meclr{lert], [leh ]) | Gabtudrer samt robbed or uhipyd) Anawert 7 (Rob 3 + 3 -* 4) | + maxtrabfright], sbigLright]) é ® (2) (3) (aah skip = mantlefls dip, Ueflirah) © men(right-ship, rightorse) Gren-Cieh Subir Sun roe + nede= oval + lafleship + righl skip 5. VISUAL = POST-ORDER TRAVERSAL (Botlom -» Tap) 6. C++ CODE (DFS + Post-order) For wach nada chew: (skip, rob) class Solution { 43, 3) f ree Pesk=seder, stapat vactordink> dfelTreaNodet moda) { at in a if Ctnoda) ature (0, O}; Mf {akip, rob} (4, 2) (4, 9) ae Unie (dip, oA) ute lefk = dfalnode->Left); 4, A pair . ute right * dfe(ode->right); eee ink skip © max(lafi[O], laft(1]) + max(eight[O], right 1]); i 44) Finally ob rook + bale mae ink rob = node-pval + left[0] + right[0); 3) 0, 1) (0, 1) ™ ————— reluen (skip, rob]; Noa | Velua aft Cabin ab) Righk abort? ahpfrods) | rade] Explanalion, } a 3 0.0) 40,0) ® 3 baal dip ®, mei-al a 1 0.01 wor 7] 1 fa int rob TreeNode* root) { aja 0.01 ta.0) ® 1 tw Sis pate AEA) a a way C22) meshavementnaies) Bee aoz sib aaa ays ely a] an meager | Seeeaes ) a4 ta 2 au ease % . 7 . Time Complenity: O(N} | Final Answer = manlskig[root), rob[ract]) = max(7, 8) = & | | (ob modes: 3 -+ 2's children (3H -4) and right Length © 3 > Length * 4 [ts ta] vo Matrix Chain Mulbiplication dpLi]Lj] = min Teej — ¥ Burst Balloons r idk. hea )l] i ky j ae ee oe CAE + pee TEGD + coats td) From Leaf Values t t t Polygon THongulation Conk to wolve Conk be olen Conk be mainly left, interval right terval the toa parks Ay | Ag | Aa | Ag | Ag [i,k] Chea, j7 ak a | i . Coed i [Foo Tip TR, Eoery pose oplit K mat be triad! | (&) MATRIX CHAIN MULTIPLICATION EXAMPLE S) DRY RUN TABLE (are = (40, 30, 5, 60]) Let arr = [40, 30, 5, 60] (n= 3 mabrices) n= 3 mobrices + indices: 1 2 3 Mekrices: TJLj] = min cost be multiply matrices from Ai to A Ay* 10% 300 ps 3055 Ape Sn 6O ae? Se i 4 Two ways be parenthesize: thy 4 2 3 ®@ ((AAz) Aa) Cost = 10-30-5 + 10«5<60 4 0 4500 4500 Pee | | AL A i es Le | | Legend i Ly (40-30) « (3045) = does r a | eat 3 ns | Le (1025) x (5260) = 10-60 ead DOS gore 3 -.9 p00 i | AL (AAA: | @ (Ar(AzAa)) 3 i | Aa As Goat « 3045460 + 19*30-60) (3005) « (5x60) = 3060 = 9000 + 18000 to Le eat » (30560) = 10=60 are Answer = dpf1][3] = 4500 Minimum cost = 4500 @ INTERVAL SPLIT VISUAL %) C++1% CODE (MATRIX CHAIN MULTIPLICATION) We want dpl1][4] (example with 4 motrices) Smetana pie 5 ERG is ae, er pee eee int n © arraiéel) = 4 7 ramiete a6 matrlsas veutercvertercint>> dpined, wecterciats(asd, 0)); Splik oh k= A Split at k= 2 Spit ak k= 3 Hf Van = Length of inbervel for Ci len = 2; mon tel wa) [bal bal) [al tal] [lea hidacte pail oe RH ink j= te len - 45 pCi] 5] = INT_MAX; oft she (22)) [B8)) 80) | fe2]) f.a)) | 23] for (int k= i; ke j- 1 se | jis int cost = dpliJCk] + dpfkei] are{i-1] + arr[k] « ili Ba est 4eCCIEET = rsinddpE CCT, seet)s ) ie pl 41E0; } HF Usoge: wectortint? arr = (10, 30, 5, 60}; #f cout << matrinChoinMultiplication{arr) << "\n";) // Output: 4500 Try every cplit point k in [i, j-1] * and take minimum, 4 (8) COMPLEXITY (3) INTERVIEW TRICKS (4G) COMMON MISTAKES (EL) PRACTICE PROBLEMS Tem Complesitys (NA) | “ Se B tee es Bet X Filling DP row-wiae (wrong order), Sf Matrix Chain Mulliplication (LC 10) {3 nested temps) | oe aca : Wrong interval length / bounds. of Baersh Balloons (LE 942) Space Complexity: O(N?) | kes : Not kryjng all aplit points. & Minimum Score Triangulation (LC 1039) wv Tr eile ik (DP table) a a Troorract indices in cost formula of Minimum Coat Tres From Leaf Values Wrong rwltiptication cost (Le 1130) faerfi-t] + arefk] + afi) LN ~—-----=- - . O's Memory INTERVAL DP = Pick Interval —» Try Every Split -» Combine Left + Right -» Take Best ‘ G5) — (loop k) {add costs) (minimum) “VA | } xx KOK zaill (PAGE 18 DP + GAME THEORY — =~ + Players play optimally. Optimal Play (Minimax DP) & + Vou bey be masinize your score, + Oppanant also plays optimally, Trick: dp[i] = max(score - dp[next]} + Use DP + Minimax. 1. WHAT IS DP + GAME THEORY? 2, CORE IDEA & FORMULA 3. MINIMAX GAME TREE VISUAL + Too players take burns, & From pesilien’\i, youpich ona! neve, [any [8,530 | + ach planer plea optimally + Opponent will play optimally from nant stats . ° he mauimlnn alr stare, = Vaur asara = poinks you git ame = «Ral geal: sanienine your sesre apponant’s bask scora from nask, saasumlng oppanerl. alae (playa ab Gide ae optimally. ae | deCiD © Hanimn, stare, francs ‘ fees the current player can achieve Wo Pick fram Ends (LC $86) ___ ee ¥ Shane Gama. rr z v Colne in aw Line deli] © mam Wakafi) = dp [nant], Uakali) = epfnent2]. ..)) Vv Degue Game ‘we || t i - Many More! Y ore yes taka nee oyprmantie beak from. next stake - oo 77 Peo Tip Tt, iz ¥ Rook value +23 —+ bask score difference the starting player can achieve. Think in kerma of “score differance” (Current Player - Opponent) L J \ 4. EXAMPLE ~ PICK FROM ENDS 5. DRY RUN (ap[i] = max(acore ~ do[next])) 6. Ces CODE (PICK FROM ENDS) | Array: 8, 45, 3, 72 | 7 eee Tun Rama | apts) teptarenen ink selvetvactersint>& name) { ink n= numensize(); a te i iui ese atalar 30 f-O07 7-0-7 F Orly ana lament veutercint> dp(a + 1, 0); J dela] © 0 : For (ink Ge n= Ay i> at + Each wanks le maximise their tobal. 2| a-o-3 2 | meta) 5 te atten nett als Bh ink bakeRight = ruma[i] - dpli + 2 eee rer 2 | a8 apf} a2 8-48) e812 melazsys a Tool Sum 841543475 33 ay as] aad pli] © max(takeleft, takeRight); Ty dpf0] = 23 (best scare difference), 1 B-dplt] s+ T-dplt} = -5 23 rant-4, -s)+ + than firsk player's seore = (33423) /2= 28 ink total = occuulate(muma.begin(), numsend(), 0}; — - return (hobol + dp[O]) / 2) J¥ First player man score || p00) = Ze <5 Bact ners difteranen fer fink ployer’ | | t (te oct) le ee i | | Spacer OCH) 7. HOW IT WORKS? 8. GENERAL FORMULA (VERY IMPORTANT) 9. (OTHER GAME DP EXAMPLES + You pick & number. i. 5 oe a) dp[i] + mas Problem ‘Shake Transition Iden, = Opponent. will lene you in the F | wtota where his advantage ix Shona Game ple] La] Pick Uf J right, miniminn opponent i score if pick option! - dp[nexti], score iF pick option? - dpfnext?], Dogue Game ple] C3] Fick from anda Mele already kms thet advantage ing dplneet] . Goina in Linn | dpfSIE5] | Flak ann oniny opponent plahs nad 3 \ J Bis pant ecteintoge Krom) current shee: Ramu Bones pL [r][k] Remme + marge same calaen hake - aeeranee ~ dpfnant] | . i Nels tapi] = beak score differance from state i rs dele] ee Sp 0= lous Gp) = scare iF pick sption = pinta ya gn Granta # dp(aaxt] = appenant’s bert from nant state 10. GAME TREE MINI EXAMPLE 12. COMPLEXITY 12. COMMON MISTAKES 13, PRACTICE PROBLEMS oe B aneig See ay a 0 Pick from Ends (LO 486) r a a" x oe | nok cet dilFareeue (uc e77) Ot) ‘OtN) >< Forgetting spponant also plays L as optimally. Coins in a Line (Gon be optimised te OC1) Ath careful ending) v Of Stone Game TI (LC 1140) ¢ ¢ Deque Gama Pick Now + Opponent Plays - You Get Left ry MEMORY MAXIMIZE YOUR TRICK Score Now - Opponent’s Best = Your Advantage PAGE 19 A DYNAMIC PROGRAMMING PROBLEM we HOW TO IDENTIFY Recognize the Pattern Before Writing the Code vy 2. WHAT MAKES A PROBLEM DP? TA Overlapping Sebpilent multiple (5) gre (4) #03) iat NO an Repeaked ay) GQ) Ga) te ral i NN Tt ” OP optimal answers of amolller problems, “santti0) | “a ™ Beatl7) + Bent) ~. a Final Answer 4, PROBLEM TYPE + DP PATTERN 2. DP IDENTIFICATION FLOWCHART (soa) ? 3. KEYWORDS - THINK DP! Tf you see these words in a problem, think about DP. Can tha problam be broken into smaller similar probleme? a IT'S PROBABLY DP! | ep a eat . aa Ketan Min} | (Humber of Maye) | (Teun / Fabs) Find marcrwms # | Count total ways Chask if something rrinimun somathing,| Le de something. is pausible wr valid Example: Example Example: Masirars Sire Gling Sirs Retin Egan neramsing, Salve. Su. Coin Change 5. HOW TO THINK? (5 STEP METHOD) a 2 ae) Sa te mask, ron, column, he.) Define the State Lak the Choices Tdertify the peremater (inden, pesikion, Whab will ee shored in def] # pl LI) 7 | MAK MIN Largest, cmallact, best, optimal NUMBER OF WAYS umys, how many ways, sounk, umber of ways, tolal umys TRUE / FALSE rue, false, velid, possible, + is posaible SUBSEQUENCE feet) sepewce, pelindrone), ues, Lis, em sequence SUBARRAY ¢ SUBSTRING ] subarray, substring, continusus, sum of subarray, maximum subarrey ‘OTHER COMMON SIGNALS divide, split, Form, include / exclude | Sequence DP | Subarray DP Gri OP Tree DP | Interval, DP Digit DF | {Sabsaquance} (Conbirwsoe) | ,| ell] | 2Es3Ts A Dives jd 129 Find longest / Bash teontirmmras Het in gah Weck on bree, Sela an range Marbars with, hath eebsepearan, | park. ¢ anbarrag. | wlth cmmairaiets, | urushares G10 ¢ herate. | dig contrainte cs, LES, Edt Kedane’s Alge Unigua Paths House Rebber TIE | Matrix Chain Counk numbers Distance Max Subarray Finimam faith Sam | ‘Tres Diameter | Multiplication | slthenk 3 6 QUICK EXAMPLE - CLIMBING STAIRS Problem: Tn how many ways can you climb te the top WF you can take 1 or 2 steps? @ What changes Current. position (2) ® Stale pLi] = murbur of wage be reach abap | | Step 3 ; 5») Che yo oak Sm range Ecos aay ahead Fron int (lake d stay) or ed taba 2 ans) || Write Transition Transition ers How be mare From carrent sabe pCi] = dpfi-2] + dpfi-2] | be next stoke? ©) Bese Cane dp(O] = 1 Cone amy be stay ok start) om Base Case dpfi} = 1 C4 step) GED Se ae DF Tabla / Rawk: , ae = EE i | Fallow these atapa and you can solve e (nos @ a a ‘nnn ——— _Anawer fer ns BoB 4. MEMORY TRICK “MAX or MIN? 5 DP IDENTIFICATION CHECKLIST Can the praesent Laka aren inllar problema? NUMBER of WAYS? [Bl De these srallar protons rapsah? TRUE or FALSE? BB Can we there ard, route the, enters? SUBSEQUENCE / SUBARRAY? [Deus the anawer depend an prarioan rumulhe? @ CHOICES + REPEATED STATES? Dyas Seely ed 7 Di eee Gf THINK DYNAMIC PROGRAMMING!" ap a 1s ES ys = Use DPE | SBP “IF the future depends on the past, you're probably looking at Dynamic Programming.” 7. DP vs GREEDY a cl a A Guarentens optional ‘es: Coden, corrack) ae alas arena anmer ‘COMMON MISTAKES Wreng tala definition Tnaerraat transition Wreng base sass Nat handling adga cosas Forgetting overlapping subproblans, Wrong ilarakion order (in tabulation) Tnlagar overflow KAR KK KH * 14. PRACTICE SUGGESTIONS Start with Fibonecci problemas Tey Grid DP questions Pid ras qn De String DP problems Move to advanced DP (Trex, Digit, Practice, Pattern, Perfect! ere Bikmask))