You are on page 1of 58
| | Leet Code | STRIVER'S | SDE | SHEET 1cs C4 ume biti ya . 8 rfel itn We'll take two eluanny Ci [lite te Ololo ¥ A tummy foray 2 Ceive of vous) 3 Ainearly traverse. 3 Whenever you find 2 0 then make ©? in the columnth index 4 O? in the owt index Complexity > OCNxm +Nxm) Space Complexity 9 06M) + o(m) Most Optimised Approach + oO As ‘Take new vanabe za ya ! bool Col = True dao afi L| elo oF of) Dusouy Arey —SAt heres we change 2 col = faues Now travese from back $ check whether fey that partialay elements zero is Present in the dummy column array or dummy Yow ce if yea then convert that element » Zero @). “Time complenity = 2*(Nxm) Soe Cnplacty » OG) 5 a © RAISONI GROUP Sen bons — Pascal Friangle « : - _ num Rows =5 Output =} [1], “td — nat) = 3.3.1], [rsey a] = 7 in_interview , Hh / ask what is the valus Present at pe vow a : ie Soo 4 34 clumna (6) Print only one of the: from \ then fermuta [RC = J Now forthe enginal - Problem lize the | vector tits for (iro + re numRaes FerCizos KES tH) | ves FAT) then a _ firGelsjsis sti) ee fi Feat alum Beale Clelemout ument ms (IG ans fi 5-9 tans [i wD _ Sg re pe Nest Petmutnl Ary = (1,2:3] then its permutations ave [2a] [3:2] then next permutation [3.12] fr Cia) > [Gsa] [rad] Brute - Apporach pulls Generate All possible combos (permutations) then find the nums arr Fehurn its next permutotion a if lut nums is found then the first pemmat ation will be its next petmutation iC atinet Approach: “linearly traverse from backwarels and we have to traerse til we found ar(i}< anfiti] 135 G44? index 4 = | ans? gd step Agus ewe Ainear traversal from back and find element which is eae greater than the valu at indey =| PPRPRPARSNNHMHOKCKKE ESA. = + o| 2 a thin we hove index a = 3 Tr ctep 7 EES Suap(amrfindext], orLindler 4) S145 32 IV™ step Yenewse( indexdtt , fat) 7 eames seec2? RAISON! GROUP Fen teen ‘ample ‘ a — —_ es 1 Input. nums= [-2,1,-3 “2,1 FS.4 | [ - Subp a an Smax. sum = 6 Solution i - a int mx = = INT_MIN ; ee - oe “Fake—one. Fraverse. Tee Comput. Stun _ _ ~dnd_ take mx = max (Sum.mx) a sium will be then (+9 rer[iow] , afi) points lowtts Tid ++ ; if mid pointer 3 1 — then midt+t; poind if mid lay es esi iien { seap(a (oid, arr (righ |) poin’ . high -- 5 AAAGAANAN Ghee ee. — - ou are given an ame nxn 20 Matec representing an Image etal the image by 40 Ylegree clock wise * { You have to rotate the Tmage in-place. which_means You have to mo the input 20 matrix directly - | __*_Do_not cate another 2D matrix and 4, the rotation ® Merge Intewals [medium] Given an enay of intewals where intervals(i] =[startt, ends] Mewge ol overlapping intewals and yehnn an away of the Ron- overlapping intervals that covey alt the intervals in the inp. Example -. Intervals = [C.s} Gag] Ceate) , Ciss19]] Output = (6), Go] Gone] ach 3+ — © Brule foe | sot oll the given intervals. then check if the intewal is merging ornst f yes > then add to the ps [¢ = O(nlogay) © | Optio Approach] Se ne] 216] eo) 13 ]am] eal ae leit7} sot Lala Tac sal sic git ]tSashiea7 cy iterate . and check ave merging or not if 73 move printer on next index , Now ie ay Now (irq) 16 ts] ” Cv] then (i6] $ Bg) they Ore not Merging 3 At this poiuat as sad 0:5) to ou ps Now (9) 3 [ae] Tre) 5 Ban |4 auth [10] Ca] ars) co Now a a (i ay os —f 6 at > Te + O(N), 06 Answer = C16) Cnt} fis ay ONdagn) fin trouer"9 y RAISONI GROUP. Been trond — 3) Merge Sorted. Array 0 0) in _O space = oe You are given two inte ‘num ($num seed in non- decreasing ordey_,_ai yepresenting the Taker af slemants in nund & num 2 wespertively a Merge num! 4 num2 into a single_amay sorted in_ nen» non = decreasing ordey atj=[1 ]al7]a i sieem and then add ai el Giieienees te _the | 93 _amay ee yh | Take out ete m 1 elements from a3 pat in ay wt dd dedetet i eteieiei sii a |) dt te” A proach a wi: T4 7 € 10 a a2: 3 3 9 “Traverse neo in owt $ check if omfi] > ow2(i} vb if yes then CLs [a] afi] s.vap low ati ers Ci) 2 Te+ O(n = O(mxm) 'Takayefi ser (Ta fa] : Os = + Bia —Yepeated n ; Example :- = | Approach : | then we can Temata! throu hums “ — act ah a oy ——— ‘stn)= oc) | There_is -onl © sort the nums array find the_dupplicate Mambots ____ oe eget Co ige Conde + itp —where_each_integer' isin range [1.n]_inclusive.— nums = [t 3, 4.22] _ output = 2 _ if (nums(iJ = =nums(i--]) | > 0 nlogRR) —_-setuin_nums[i3s ; space 20/1) Complexity Vector veturn nums[iJ; _ most- Optimized method :. linked - List Cycle. method 34 2 then we hike clement present at index 29 239 then take elumeut of g index 1 a4 233 dike wise Z 3 3 eee Now we will apely [forteice-methed | slow if moves 1 Step pointer > it moves 2 Step se ‘= ta a) fast t ay Ng d fost 15. Ss \ a> 3 / iv ‘ Niage this process akes place 9 ageuu 4 again Iss 2—- of x ry J Fao? Nees Now we will plow tu fast poiuter at first N C wed acs Move sow 4 faot priutey & fut IS5 a-33 i* Te = O(N) Sc= O01) RAISON! GROUP | fost = nums[o) 5 | while (slow 1+ fast) § Slow = nums[o}; aaa |, lh wh wlUe hums (slow) 5 while Cslow |= fast) f fast = nums[nums (fost) | t a Fast = nums{p15 Slow = _numsf[slow] i —3j __tetuin slow: Seg oan] | ESS OOO @ Find the wepeating and missing num bers = You ave given an o oN inte gers with the values tn the vonge Cin} both inclusive Each integer appears exacky once except A which appears twice 4 B which 7s missing. 1 find the repeating no. 4 the missing no- Semple nums = [8,1,2+5,3] Result = $3,453 Brute force .- . 7 aa pe Ta tute f size (N+) and aac [initialize i+ with © then add the values to the Substitute ovay (frequung) and find if the frequney == a Len o7 missing No. 1-3 Eepening tor for (i=o te n) i Substitue [Amay{iT] +45 3 for (I to 0) 4 if (cubsthute G:J==0 I] Swostitute [1 71) 1 ans. push-back (7) 5 “Time Complexity = O(N) + O(N) % O(N) Space Grnplexity = O(N) mn fl on | 2 then Subbrace the ie for Pray » olso P= Sum of Squorer # paial re- “pe n(nin(ans!) —_@ i calatah Sum =I $5um of Squares ? p, —® oS lee [oss nm) ——O RAISONI GROUP. Seon tend a 8 [Ss of eliments ~ Sum of naturel . ot frre No: fron 1 ton Gives te StehibrZ& :- ®) Inversion of Array cs of Sze n’ containing all dighndt for a given inteqev ar ° valu , Find A total no. ot wale that exist A pale Cow(i3, afi) 3 said te be an inversion Whe a) lewfis> ow GQ) and jis nal Kis nums = $513.2 1,45 ~ There ave 7 pain (50) 0813), (5,29, (8.49, .2),(3.1), Qn) #( for the Array which is Sotted in eee order, the moximum inversions = N*(n-1) a Approach Bruti fore = Traverse through array with two loops and cheek (an (i) > owG7 $$ 39) Coust tt 5 Te = 0(n2) $c.2 001) Day = 0% Search in _a Sorted 20 matrix. ® — aud ae iudeg Given a*m#p' 20 mahix Gite a program fo find the particular wtegey exist Input :- mahix = Fania | target = 3 Of Tome ™ ‘ana ahhh 4h bb 6 & 6 & Eb ARAARANTNN [to, 1116, 26), [23. 30134,6 Output = Tue Approach © Brut force We cou traverse through the 20 matrix $ F we found the target element, qetuyn Hue. for (j20 3 i ® pan Seareh t ° 1 Forget = 30 2 3) Low Aigh a Is id= O+IS _ om a a So = =1 Pou = F/4 2 (13) Fka=3 ® RAISON GROUP % 7 tree eed — . = TT 7 aC _ int_n= matrix .sizeO T.C= 0 (dog(many) | Sc= 60) 7 t- - int_m = matrix [oJ - sizec; L int low = 0 5 high = (n¥m)-15 — while (tow <= high) 5 7 i: SS tut midi= Low + _Chigh - tow) | 2 )s | fo if Comotrix [mid /m] | mid fom] == tanger) else if (matn ts fe or “Time Complexity = O(n) S.¢ = OC © 0 ptimized “Approach - ped diddiieieesesl *| Using Bin Exponentiation 4 = 4%4 gh (ayy? = 162 \ 62 = (Wx) = 256 asé x Gs6)° I 256'= > 256 double ans 1o | fog n a an =P a if (nn -J3 # DNS | while (ne yo) | if (nn pa=2 OF Peeee eee eeeneeeeeeeeeeen | ans sang *x%s an= nn-1s else { : ‘etuin ans; a | — ans = double (1.0) / (double) (ans); 7 © find the majority element that occurs more than (M/2) times Given an aay of N integers , urite a program to vetum an element that occurs mord than (M[2y times. Input N=3 nums = [2,2 ,5] % occurs more than gj, = 1 time So result = 3 Solution © Brute force - Check the count of occurences of oll elements ot the a one one - Stot fiom the first element of the arroy and Fequut > Ploor(w)> ) then retum that elment a the answer TF nots proceed with the next elemeut inthe array § “repeat the process r Time complexity Space Comple: © Using Hashmap = Hashmap Crey. valu) 1 map mp for (int j=0 3 {aw.size 0) Sitt) melan Gil ]+ts for (auto i : amp) iF (Second > /2)) rebum i-fist > ry7] iFvyayvyvuvey 7 a Fines why thi intution worked | Here owt: will be zero | ‘S=2 times "SS time dey tition 3 Hee CIT nt te = rire at ® Bo Ss - ss77—> —! a RAISONI GROUP oe neon 5855 © _Mest optimal Sation To is Hu ave | Tc = O(n) S.c= 001) Moore's Voting Algorithm { + 7 - ial 715 IE sls OE 5 s|s| ne i¢ a . % 3 tw 1S 14 1S cnt = 84 [Now isis gator | ete, a= 7 ol {Ber eter | \ - izw, a(v]>7 it, 1G ents | - iT et | Tess] fiw apa Litt, is6 c a af=5 i=1¢, a[i4]=e5 _ [Tt ero | afd=7 eles isis, als] = | cout=0\ eR kept a[al=5 = al=s cute x2 el=es ats £3 wel 5 Given an of N integers. find the eluents that Gppears more than (N/3) ‘times in the erry . IF no Such element exists, Yetumn an emphy veetbr . pecepoaehes © Brute fore + Simply count the no.of appecrana, for each element using nested loops ‘and whenever you find the count of an elemeut greater than Niz times , that element will be your ans for Cint j=o > I< 3 i++) ent=1 for (int ye it! + 365 4+4) if Ga [iJ == av Gq) ent+ iF (ent 7 (ris) ans push -bact Carr (53) 5 “Time complexi O(N) Space complexi ots) ® Using _Hashmap :. unordered map (rls)) Qns.push back (i-first)s RAISONI GROUP maou © Extended Bayer _Maore’s Vat = ams EE] - etna as [ for(int el = nums) c2=0 vector ang cout 1 = Gyut 2 =05 if (isos icszs 144) fF __ if (mums (.3 = =m!) Count + 5 etse if (nums (iJ == num) - Counk2+4+ 5 bo if (cout +7 (2/3) -f— uth — back Cnumi) i _if (coum 2 > (62/3) “ans. push back Courn23 if (a e= num) C+4; else if (eL== numa) cot+s else tf Co yeturn ans ; Tec O(n) ; Given a matrix mxn' count paths from left-top te the night bottom of a matrix with the pin thot from i each cett you can efthey only move +o the vightward divector or to the downward divection 3 Example rope onal output = 2. Explanation - © . Right > Down @ own ad EY Hes “Btal @ woys Appro ‘ach © Beck Recursive Approach »- Thiti we ave at (0,0, i: ally fi ) ° fiom here we can go! | t the right as well as bottom and we will a unti] the base cove hits wish ® OS TS cos 1 és O GG) 8 « x Succes) Gace Ans = 2 Time § Span leno will be exponential count Paths (ink 7, int j. int ny int m) j (ize (rn) $5 j= (m-1)) vyetu 13 iE(ipen I seem) veluro else . ~ wretun coutPaths (i+! ane) 2 coutfaths (iy jth MD) . Y » S ® © » mason argue > | © Dynamic ie_Programmin _ Solution a | © Tw Tate, a dummy ti Ab] and_initialize it_with . 5 > . , > = > > — ) > J = __ ) Comma » - ys “int_couud Paths (int i, int j, j_int_n._ink m, vector > $4p) ) ) if Ciz=(n-1) $$ J==(™1)) rerum 13 » if (izen Il jz=m) return 035 - ) if (dpO IG f=-2) vetwm ap OIG] 5 ! _else _ a ) retun dp GIG] = cout Path jm, op) _ = rar jth rmimdp)s int unique Paths (Ce vector > de Cm+i , vector 2 * ar GDI couut tt3 _ | yetum count; | Time Complenity = OCN2 OS \go Ps] '3 12 [9 [¢ [2] [efslesleo) ~~ NN = } 2] al ~ \ewl 4a. eps] alr] ge if NY 7 ‘, g XY qo aa Lis & tJ @ 1@ ~™ Go 25 Now , we will place the ‘\j’ fe Such a index Such that afi] <= 2*aGJ (keeping 7 constoutt) % J stays over there so 25 will never contribu 1 cur awe - a Q) Now i move forward 3 19 2 The ig alte oct contribulu fo our perform merge aus Now +, 6 oO ‘i © 26 40 2 Ig 25 <= 2*$2 (tobe) move jojtt ig i jj moves by one Sicp 25 <= 2% 19 one 4o <= 2* 19 Cfabe) Stop. (Right crray exhausted ) left array exhausted ot perm merge pce nM ANAMANnnrAMDMAaADPAMADADD & AE HAAKHKKAARAAAS © RAISON! GROUP Neen beyone — (oe cabot) - erform merge step _ a) ii Criglt. array exhauted) —_ ; _2#2 as (No contribution) on : - we Aave to cheek. oo 1g 25 40 __ gsave move 3 : 12 & 2k6 = add no of Climente cn left of meispig Pee 2 2ak6 (x) - move 5 - Ig <= 2k9 (X) move j 9 Right a eabrausid - - Add # elemedlo on Jeft of J poluter - - & © © 3 ans move i t 25. = 8 f= 22 (X) ; 2 Ks 26 (XD) TF Right array exhauoted - 25 = 2G (x) nid ae - for 40 343) SO ans= (f2tItl 143+ 2343 [sAs = TS] 9 Tn da mo. of pies Now merge 6 Shp [2TeTs] 12]'39 [3S] 4o —__-— Time: Complenaty = O(nlogn) + O(n) +4 o(n) Merge merge Count Se operation operation Spow ea = O(r) “Terup ae in merge Sot int yeversefains ( vector Siut >4 nums) veturn MergeSert (hums, 0, nums-sizec) =I); int merqeSovt Cvector 4 nums, int low, fut high) if Clow == high) ehwm 05 iut mid = (Tow + highYo 5 int inv = mergeSoxt (nums, low, mid} // lef cunson inv += mergeSort (nums, mid +1, high) s/| Riakt . “Ye cungion inv + = merge (nums, low, mi yeturn d, high) mere fe nchon, inv 5 * s 3 RAISONI GROUP = Hin prone — int merge (vector 4 nums , WE Tow, iuk mid, tut high If iut cut =o: // Stove the fotal no. of pals iuk_j=mid¢ls (pul the j index to Hu fist index _vigut half far (int i= low 3 Te=mid 3 itt)f : - while ( j<=high $4 nums (iJ > 210 * numsGJ) { _ jtts — 3 cnt_+= (j-(mid+ 15 ff coumt the # elemento Placed to the lef side of'j” ) ) ; ) : ) ; , ; Toe function Vector temp 5 ir int left = low , right =mid+! 5 while (left ¢= mid 44 vigut <= high) § if (nums (teft] <= nums Crigut J) § | temp. push back (nums [lett +#])3 i —_ - Es elsef 7 temp .push_back (nums [right #4] ) 5 _ — J mia any anrey exhausted , thent : oe , while (left <= mid) £ f Left array ) ee temp. push ba |S deft out — ) 3. = _ — pt _ ia while (right c= high) f y a Ml py back thie hemp array fo nums array for(int i= low 5 ie= high sith) nums [jJ= temp[ j- low]: 3 veturn cts RAISONI GROUP Sion 8 — Example_‘- Input: nums=[ 2.71115] target = 9 output + [o‘] Solution ‘= _ (co _ ee Simply traverse sha h_the_nums_a’ a OT fx Cint ico isn itt) | for Cint jz itis jens j+4) “if CnumGd + nums G22 tage) 1 ~_ans. push- back (i); ans push -back Gi | if (ans size() ==2)_ break> return ans. break ; i © Be- cinter Approach sort the aw use fwo variables .each will start from one eud of the a and tyavese in both direction to find the required sunt. for each element i’. we try % find the second clement vector ans, temp: temp =nums + ——> stove He wana corre in teup array sort (temp) + int feft=0 might = nts mt xy 5 while (heft < right) 5 if (templlePt] + tempLaget] == forget x = temp [deft]: y= temp [right]: break ; 3 | else if (-tompliett] + temp Grght] 7 target) right -- 9 else t Jf Now Run one mare (oop to find the incleces ofxty i YUU deft ++ > fox (iu jz0 5 icnumssizeQ 5 i++) § if (rums{iJ==x) ans.push - back C3 else if (nums (]== y) ' ans. push-back (7); -retum ans; © Hashing Ast Effient) We'll we the hashmap fo see if there's ar value (target -1) that can be aolded to ‘the cunent amo value Ci) Get the sum equals to target. | Sf eae -i)_ found in the map We -rétum a index $ index Stored at tC cans ke) — - — location in i map - unordered —map Sea © Using 8 pointers + Binary Search Sott Given Ex: soit it ia! the % so 7 2 [3)2 7 j aa 2 4 1 t k nums(i.} + nums GJ +nums [kJ = 0 we have to find = =© inthe “right Cusing binary, Bo half is not there in the oS so move K aga SFE Wit2s 4 % S-4= OF i441 poi: ) / ( AG! 2 of , Ve 7" How whew 4 Pose LT3]4] tits [227 313 Ta Tals Une 4, rail CBinavy Search) il+3a= § russ [7] + runes GJ + runes [J = we have to find = 9-s-@ sw ve hae gt [1]1[3/4 as one qued ; So set (vector cint?> sts for (i=0 to 9) for (jit! to n) = for (k= j4! ton) f — —____—-| int x = target - (ums (J+ nums (J + pums [KJ) Hf Cbinany ~ Search Coums.beginQ+k+! 5 nums end()sx) year ind = quod. push beck Crome J (Ds a ____ quad. push - back Crums(jJ) > quad. push-back Cnums(eJ)3 uad.endO)s — ___ quad: push - back (x) sort (quad .beginO 5 st. insert (quad); ams j i ene > ans €st-beginO, stendO)s © Optimal Approach (Two pointers) Givew aah 4] al3 alah hh) sort this left wight i rye 243]3 B ale) ue) aos numsGJ= (f= 2 To find -@ 7% Dies now (umn tJ + rues Fright] ) (+4 <7) 3 So ne sol” s + +t 5 ae (2443 Ghetto for “Targer =9 Now [ids GhEBEEIE] we ide. Theve is no need to check checked for erate (mums [left] + nums [right] = = x) (+4 == eds [7 Tr TaTa] * Now éLminating duplicates and Suiiay tept F ght feunters on fee x dn Eo atelals = Lalal ap Rp J inter Crosses the night ointer Now >“ will jump 2 Dts ieee) fi a rigid ‘ Remaing Valu We we = 3-(1 en for (ares "TED FPF? F FY fg — iy i fF Tf ft 7g ft dl luylhldtlhdPlhu PPP ae ee ee .® a2 Now skip the duplicates Gj deft aig - a {ri Er nat 44 nums[lepp] == quad)? eH + “PtaPeB eee C fr (iz0 tor) target.3 = target ~ jet - nums(i] __ for(jzit) mm ‘target -2 = ee et-3)- remsB J - a while Cleft Cale) (6 -~= nums(iett] +nums [ght] ifC2 < target-2) > deft +45 | “else iF (2 > target-2) 3 vigut--3 else § vector Gut quad €,0) push all elements (1.3, left, gut) ae Bt cog 4§ numafriglt] == quad (81) > bight dae (iuscn £E name nums[jt) == numslJ) = petetets ey while (+1 if (nums [i J= prev +1 § cay tes Chee at ta to He pree else if Cnwns CJ = J= prev){ cur=13 set defoulk 3 prev = nums [iJ ans = max (ans, cur) 3 3 yetun ans > = OCnlogn) + Oh) & 0(nlogn) = o() Time Gomplexcity Spoce comp exity RAISONI GROUP a eonteyent — ) Optimal Approach + (using Hashset) Insert Ql elements tuto HashSets Now ‘traverse the hashset, and will check the — (Mum -1) element is present of not then we'll do cureutNum = _nums cunveut Streak = | OE L i, in th _ Hash Set . - ———ma_longestSteae = max(longestStrect , GamrentStreak) + set hashSets for(int num: nums) T= o(n) hash Set. insevE(n wn) i [sc = 6(N) longestStvealk = 03 for Ciut num + basbsfetnurts’) { if (IhoshSet - Couut(nusn-| a CureutNuw = nus cuwreut Streale = } s whils(_hoshSet.cout Gr CuvreutN ww +1) £ - Coreut Numa += 5 5 Cuneut Greak + =! 5 4 / a longestSheak = max(lonqastSenk , curreut Streak); | 3 : ehuin lon getStreak 2 integers We bee Given an om containing both positive and negative i te find the length of the longest sibaway with the sum ot of elements equal t jer = nums = [9,-3,3,-1, 6, -S] output = S subarrays with sum =o = 4 £-3,3] 9 Jen=2 [1,678] 2 len [-3.3 i1,6,-S) -{ian=5| ® Solutions = O Neiwe Approach :- O Initialize a variable marden =o (Sores the maxima (eugth + eae with su O @® Traverse the array from start aud initialise a variable _Sum=? which stoves sum lef subarroy Starting with urventIndex @® Traverse from next elemeut' of curveubIndex up fo 0 sum += nums (iJ if (sum = =0) moelen = max(marlen, j-7 +1) ; vetum maglen iut moxlen=6 for (iut ico 3 ven 5 +4) sum =o for (iut j=7 5 j¢N 3 3+) sum+= nums UJ; if (Sum= =o) moxlen = max(maxlen. j-i +0); elu maxlen + }Atic a Atiz 3 | ating Ati=2 ie. (1,0) (Fey, Vals) sum =0 » This s sbarray with sum =o sum=3 > Add to hashmap Ge (bat before check if "3" exists 1p the fash cr not) Gif it does not exist then! ad sum=5 — Add to hashmap(S,3) sum S-2= 3 (t ic exish in the hashmop) So thin meauo that , till index 9 2 we had Sum =3 (3:2) cand ff fill 4 we howe Sum=3 Suned- aaa SLC L IS 3 eee ae = the inde a in suncs— lig ‘ dengih = ar ahich which we have got we. ‘hawe get o3 S=3 (previous) = 4-2 —@ =-S hashmop or not gum = 3-8 [os if 8, is present in “| \¢ if net add jt ol ith its “am index Sum =- St! Add C416) At ict maxi = hen-= max (ten, maxi ) = max(S:2) maxy= 5 At i=8 Sum = 3+10 =12 —+» Add (13,6) in hashmap i hea At i=3 er ap =a a , 23 Add (36,9) So fhe Pmaximum engi = Ss RAISONI GROUP ron brs — unordered -map O_Brute force ~ borg dong int count =o for(id izo 5 ign sitt)§ lut ww xor = 05 for Civ fri 5 jem jtt) F Gur xor = cuwxor A AID3 if (am-xor == 3 f Couttt 5 Time Complexity = 0(n2) Gpace Corn ele =0(1) “doy Run org 2 e - tums =| 4/2] 2) 6/4] k=6 oO Assign XDR= 0» unt +0; at_izo | ie XOR= ONG =G —> Doe thie ging a - k=6 (x) Add to postr op with it cout eeeeens ene 04.) Gu) f _ oe - > LG) | 7 = - Hash At ich : S (Prefix-xog , Count) | ROR = GAD ee > 1) 2 Ye it is giving ee OEE 2 eRe i ts peed Her increment count 3 Counttt > ieremeut the ous At iz2 xoR = 6% 2 -G@ -~— = xe*k $: are CE DD check in the hashenap Add (4 cst) But 4’ is oud abres so we'd “jut Gecemest ee Lee ie cs) At it3 yop= 4 AG (4) = 2 3 y= xorAk = 2 6 T=G | (pret!) woRp= 2 al «& <> one Sr js L = —— dee 5 werd 6 = 2. a yon = 2 DY icy ore KOR= 2AG (6) —> Y= KORAE ast = 646 y Fo RAISONI GROUP. vison bend — XOR = XORAT > a fe ifGor==g)f§ — j i \ or *B) I= fre a cnt += freq [xor 6] 5 3 freq Cor] + = 15 3 yeruin ont 5 | - ©) [Length oF Longest Substing withouF any R Given a sting , find the length of the longest Subshing any Yepeating thayacter character without & S=“abcabcbb" olp = 3 . (0) Brute force :- Take two loops 9 © One for traversing the shin @Arother nested loop for finding different subsiin gs we will check for all substings one by one 4 chesk for each ond every element if the element is not found ther we will store the elemeut ip hashset otherwise break from the loop $ cowt it. int—ars—e—6 5 int Cowt = INT-MING for (int ico 3 icn 3 itt) { unordered set Civ > Sti for (id jet i Jens jt#) § if Cst. find (SGT) | = st-endO) § couut = max (coud , j-i)5 break 5 5 st- insert (sjJ) 5 f 3 rerun ea Count Time Complext Space Gmplexi s=“abcaabcdba o 1 2 ¢ 4 6 67 8 GF Check if S[iJ is preseut in the set (Not preseud) c b a ‘Sel —_ So__Ronge Cl ~8)_ 9 Mhie_cubsthing-boa_no_aspeatg —— 1 ____| __ move the sight pointer _ 2] i - —___fAtiet: dens (7-L4t) = 6-041 =! update den =( insert the character into set preseut (wht!) = 1-0 =2 te! ig not preseut in See - Ge) 9 GAH) = 7 = (2-0 +) =3 : Upaate > fen=3 Gasent <) [At ES an ‘a' is preseut 60 we can say that Cl-R) yange has some “repeating characters 5 So we've J to remove that __rertove a’ from sot 4 —— Ce @-L+1) hva’ ®) Teg 080 sate ClensD fet > cS ger bt a @bedba Can “ a 3G GoThis ha pepea tiny character remove 2 S[ieHt] > vemove b then left t+5 Now zu shill has eating chavtactem ow Coa repeating remove ¢ > JSettt+t 5 left aoa —— “remove ‘a’ at fed (1t does not oe crepe ating characters) t en = fe But we'll not update the length push this a" to set move the Rts” © At i=5 c “B’ is not preseut ree den=2 (No updation) ob bed b push b into set Sg At izé remove (sett] 2 vemove 'a’ | o ~c! is not preseut eH +45 6 ten = 2 (No updation) bcd b, puh*c! into set we still have ‘b’ q nt i=7 remove “b’ c ae “yt #45 ‘d’ is not present , dena (L-R par 4)t! cab d @ fen=3 (No updation) spt Geo [eo AS) wh “al ‘into set ra" is ie Ae eut eo ‘ fare 4g > ed b =(-ot |9 3t1 St 5 - ~ int 1-6 scRsaeasae - for(int 2-0 3 # (4,0) den=! Rtt3 @ pur’ > (bi) den=2 Rts © pwr e's Car) den=3 Ret Now ‘a’ is preseut in the m IT know “a ' is pre © pr *f $33 0' index so we’will shift “L" to (+1) a= Ip 4S index L b c a (Now update the index fa) na 8 Cee) S (b,ID (ais) do © bo a 2 gy awe will Pr 3 4 Shed 24 (2) 4 (ou) ‘, (a,4) | v , 4 pe | 6 ab 4 @2 y 4-§) (Cos) ange [4-8] ca) — EASON SROUP _ a,b,c (c.6) ae | Cbs) ——_ 4 — tte —— | Now af i=7 a fi thee hag = 7-4t! Ga) = 4 Cas) | : Sf {| . Cau) : Now at izg 47 ame nel - —_ a(b) c d b&b - q 5 6 7 R 4.7) | - Test = Ce.6) - L Chia) a ca § Cone) | Now at i= 9 = cd ba \ (a2) | & 7 = $ ! nO “ shing cam Thane 256 T char | vector Z iuk > mp (256 , -1) 3 ‘int lefr=0 . Tight =O int Len=o while Cright cn)§ i (mpLsCrgutl] =~) § left = mox (mp (s Cright J] +1, lefts 3 mp [s right] = ght den = max (len, vight - left +) 5 aight ++ 5 return len 3

You might also like