Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
76%
(25)
76% found this document useful (25 votes)
7K views
214 pages
Data Structures and Algorithms Made Easy - Narasimha Karumanchi
Data Structures & Algorithms
Uploaded by
Sherry Srivastava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Data Structures and Algorithms Made Easy - Narasim... For Later
76%
76% found this document useful, undefined
24%
, undefined
Embed
Share
Print
Report
76%
(25)
76% found this document useful (25 votes)
7K views
214 pages
Data Structures and Algorithms Made Easy - Narasimha Karumanchi
Data Structures & Algorithms
Uploaded by
Sherry Srivastava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Data Structures and Algorithms Made Easy - Narasim... For Later
76%
76% found this document useful, undefined
24%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 214
Search
Fullscreen
apr DATA STRUCTURES AND os un a ALGORITHMS “@J MADE EASY solution different ee Narasimha Karumanchi US oa Pr etoreteea on teeny CareerMonk PublicationsTable of Contents Introduction Recursion and Backtracking. Linked Lists Stacks Queues Trees Priority Queue and Heaps ~ Disjoint Sets ADT Graph Algorithms 10. Sorting. 11. Searching 12, Selection Algorithms [Medians] 13. Symbol Tables 14. Hashing 5, String Algorithms-----~ 16. Algorithms Design Techniques 17.Greedy Algorithms 18. Divide and Conquer Algorithms ~ 19. Dynamic Programming-- 20. Complexity Classes ---~ 21. Miscellaneous ConceptsPata Structures and Algorithms Made Easy Introduction Chapter-1 INTRODUCTION Bs objective ofthis chepter isto explain the importance of analysis of algorichms, their noeons slasonshibs Pee scy pooblens as posible. We first concentrate on understanding the basic elements of slgo-shes portance of analyse snd then dowly move towards analyzing the algorithms wit diferent notations 200 finally the Frablems Afer competion of this chapter you should be able to find the complexity of ny ven algorithm (especially recursive functions) 1.1 Variables fore going wo the definition of variables, let us relate them to old mathematical equations ‘All of ws have solved Frany mathematical equations since childhood. As an example, consider the below equation: Be caere have to worry about the ase‘ sbove equation, The imporant tng that wef sy eadesrand Pee toon nos sme names (andy) which hold values (Goa). That means the names (x and y)are the ple Bolas Heane oesg data, Similarly, in computer science we need something for holding data snd variables se the facility for doing that 1.2 Data types In the sbove equation, the variables x and y can take any values ike integral numbers (10, 20 ete.) real muses aan cor us 0 and 1. To sclve the equation, we need wo relate them to kind of values they can tke and data type isthe name being used in computer science For this purpose A data type in a programming language isa st of data with values having predefined characteriics. Examples of ‘datatypes are: integer, floating point unit number, character, sting ete Computer memory is all Sled with zeros and ones. If we have a problem and wanted to code tits very difficult provide the solution in terms of zeros and ones. To help users ‘programming languages and compilers are providing the facility of data types. For example, integer takes 2 byes (actual value depends on compile) float rakes 4 byees ee. This sys tht i essary we are combining 2 bytes (16 bis) and calling it as integer. Similariy, combining 4 bytes (32 Bis) and iimitas float. A datatype reduces the coding effort. Basically, athe op level, there are rwo types of data YP e System defined datatypes (also called Primitive datatypes) + User defined data types System defined data types (Primitive data types) bata types which are defined by sytem ae called primitive datatypes. The prmisve datatypes which are provided by many programming languages are: in, float, char, double, bool, et 1.1 Variables 9{Gon ind Push Table, Gaps, and many eer For emp ack wes rete ering the data src The a lement nse it he mack deed ‘onc operons far crating te sce puting an element onto the sack oping =m ment ote dente inp easThnysma n acaly whenw wa : different kinds of applications, and some are highly specialized to ae Tice Stein at Atte es ys er defied ata 9 se elles ck we lth mey tbe nd ou eis pion on . ae ot ceattaletgemer hg ae 1.5 Whatis an Algorithm? 5 ee ets consider the problem of preparing an omelet. For pepringomelet, goer ate we fellow are: 2) caaeek Zig roeleecene i eigen ose Dem Soosre tisha me ‘Whar we are doings er gen problem (eating omelet ving sep by sep proses for sling Formal
11 oi ht pe el 1 4 100n!-+50-O(0* with ¢ = Zand = 11 — Example Fin upper and for (0) = 2m? = an Solo: 20° — det = Ds forall > 1 28 — 2s! O(n th ¢ = and n= 1 : Example Find pp und fof Salons» forall > 1 = O(n) with € anda = Example 6 Find wpe bund for Fn) = 410 Salton 410 410,foralln > 10 = OGL )wthe = Land ng = ‘No Uniqueness? ‘Tere ae no wniqu x of values fry and ¢in proving the apt bounds. Lt ws consider, 100m 4 §- Fortis faetion there are lip sod values pie, Vinuaizetion Setuiont: 1008 +5 < 1008+ 10in-s 10in forall 2 5, ng = Sande = 101 ea sokton, 105n 5 1054 foralln > 1.ng & Lande = 10Sisalseasaltion Seluin2: 1008 + § = 1000 +5 : sample, OOF) 1113 Asymptotic Notation 1.14 Big-O NotationStructures and Algorithms Made Easy 1.15 Omege-0 Notation ——S ae Now consider the definon of © sotsion. fi defined a» @Cgtm) = (/(n: there xi pore conan Cuestndng sah that 0° Gal) 2 Tle) Ga(t) foe all n= my) (0) & an aeymptce phe boond for Flo). Og) hee ans with the me order few a © Bxamples| Bxample- Find @ bound foe f() =" sn 00 108) wih 6, = 1/5.¢= Land nyt Example? Proven « 0(32) Seludonc, =< x = entmonlybolistorn © 1/6, neo) ample 3 Proven?» 0¢%") Selon: = «cn only olde for < e/6 on! © O00) ample Proven £6(logn) Seluton: lean
0, 1 stherwise Tin) = Solution: Let sry solving this ncn with subetion. Te) =27—)=1 Tea) = 2076 -2)-1)-1 = BT4-2)-2 Tia) =2@M(n=3)-2-1)-1= Pr(n— 4) -F-2-F 119) = 270) = 2! 8 Bah Tiny 228 Det ge BP Tin) = 2° == 1) frote:2"-" $203 $4 aD] ‘Complexity is (1). Note shat whe he recurrence elon looks exponent the slutin othe recurrence relation here ge diferent eu Problem-23__ What isthe running time ofthe following fnction? eid Fania) Ine while 4 pane : ) Solution: Consider the crmments in below futon: ‘eid Function Git) ( incl; 1 ss increasing not at ae 1 bat while mE Panelt™) 1.26 Problems on Algorithms Analysis Problem-21 1 |Mecan define the rms! according othe relation 55-1 +. The vl of 7 inepeaen ‘The value contained in atthe ( inmtin the sum ofthe Bet“ pokiveimegens I _eraons taken by the program, then while loop teroaes i 1.26 Problems on Algorithms Analysis 1.28 Master Theorem for SubtracStructures and Algorithms Made Easy ‘ile op exci gn timee fulrijom 2) aster loop exgceeoge Unes ffs; eom 2) Problem: 4 ey othe complet lhe ave neon Oo?) Problem-27 Find the complet of he blow program. neti int Mo = Drenn: betarteticrrts+)| Tonite ts) -as}++D paul” bres } 1 Solution: Conse th comment in he lowing function Function( em) rider oer ong ecie wes forinet—Tit- aris) ivinaer ao eocoe ony te Suto break Statement Fong shsomsi+){ , 1 ‘To complet of the above function O(H). Eventhough the inner loop i bounded by m, hut due tothe Break statement its exciting oly once, Problem-28 Woe « recive function for the nabning time T() ofthe function given Below: Prove ing he Tteraive method ha (9) = 90) fanctio(nts) ifn 1) ea forint =item forte }=1;)emsjes) ana) 1 Solon: Consider the comments in bow futon: ancton ic) il — 1) eae ots loop execute es foritisTiseoasiss) ‘inner oop exaust 1.26 Problems on Algorithms 1.26 Problems on Algorithms Analysis_——__— + @232~ "i erature and Algorithms Made Eary 3) 3 ERROR Data Structures and Algorithms Madi iors p12) 2 ‘The recunence retin fo running tie of thi progam bs (5) = T= 1) + — 2) +. Nese 0) Sa eas indcning binary wee, ach tp ecunivel cal the ropa fr mre by 1 and 2:20 earl ecmrence ve O(0, The numberof eves st depth 2" nce his i fell sary mee a St, coh cal prin fen lews OC!) eoputacon for he constant facto, Running te is cel exponential i sndtis O12") : Tos ~ 3)* one Renning ine of flowing rowan? Taneion(a} a " Tonic j= 1s} ensbe=id prin +" x! Canider scones in sow Stn: ‘ction e) : ’ ibis opener aes ice fects consis) Tr lop exec ines with iereae by thera Problem-31 Determine : eS eit" +") ) In the ave code nner lop executes n/ times for ach value of sunning imeem On /) =OXhlog. ‘ Problem-36 What iihecomplenty of Zt log4 ? Sel: Ugh pti oper gy’ = og +g, we cam meat srl eal ogi = tag 1+ 1ag 2-4 +109 a : “This shows at that he ine complet = O(nlogn). Problem-37 Whats the running tine ofthe following recunive function (specifi ta funeion ofthe put valve n? Fit write the cuence fomia sad thea finds comple. encoli 0)L ‘i= ear for(int ied tense) GP Satin: Conier he comment in bow fanton ‘unto Git (| Man) star: {bio eects with recurve loop af ale 1 for(onieh sen 3:6) ce Nate Wen 1 se " . We can sn that for sem sna t= for evry inte 3. Problem-34 Cons : T(x) = STE) + O(2) Using maser theorem, we ge T(t) = (0) a thon) shen mera Problem-38__ What the mining sine of he towing recur fein pid ‘acm? Ft wit ecmence formas ad show i un sing indo do ii then se fsnsomine 26 Problems on Algorithms Anal 1.26 Problenit ou Alga Asaiyaa‘Data Structures and Algorithms Made EY _ in 1): 1 Seton Consider the comments in bow fn ‘a= 1) erm hop ex fort si 3: hes Stines with recuse ase lest tel ‘hed stzemenrgurs conan ne [0()). With ‘ing he Subraction and Cangser master teres, we et TE) = 943" Problem-39 Writes recursion formula fr he emsing ine Tn) fe ci Solon Consider he coments in Welw fron: ‘hogy exes» sew cone rear al wit 80 faction (tn 1 ‘The rcurence smanertheoram, we geT(»). = OC). Problem-40 Find the comply of he earence Salon: The pvearcarence fot inthe ase there foe. Lt ws ty toc by asuming n= 2". Aplynglgarthoo teh si 092 m= logn Now, th gi tecones his plete of ede & (9) = Tn) + CH) = TH/5n) + O68) = 47 Arpving the maser theoremnln). and Algorithms Made Easy ri freon omen ie == a>) funcron( 92) ‘ec wits 2 ale function > Ere os acini T= 21) a eee 49 Find th compley of he Below Facton nein a whe <2) vehi = 0 Mi funtion while
a) =) Moga code Be ogni wa d “Tine Comply: O(agn + lan) =o? Problem 50. Ehsta.0(n), where O(n and for onder nie > she 0) "OH "OM OBR —_—)OULSN) Satan: (Eaten 2) = O60) Basen 1 =O(8). Problem-51 Which fee flowing thee cams are comet 1 (1 + 8" 040), where kand m aeconsant 112" 0g") — i a2 Gytanatt "(Ladi etn @LManaitt Soon) (9 + 1)" =n ew 4 often 277-002) Problem-52._ Considers ilowing fancions: ia) = in) =m 1a) =n Which ofthe allong statements abou the asymptotic behaviour offi) (4) fe) = Ot = 0) (@) Ko) =2 gin gin = On) (Oa) = O49) = O4) oan ae "aan iseIn and Algorithms Made Easy Data Stracures : yor tn 0 Probl en) ins = Sem) 1 sce es forint ko) (cae nes Gm OF 2, Taig Tr Ge 0-4 «jk sacs jtimes =n) mes f a, ’ e Comploiy tn") sie he de ‘ime, Thefts Problem 1.26 Problems on Algorithms AnalysisData Seructures nd Chap’ determine the value of (n~D! and mip tt with nT the be cs, when. Lhe fancion 5 Ng) 2 BA*S¥Or! Byam RECURSION AND BACKTRACKING ‘ wth Saag ons oy fits aac, Mv com is 0011 fin tre ‘ea er 5 40 ANE Heaney nb 0-1) oo eee ess 2.1 Introduetion ‘Recursion and Memory (Visualization) recursive cll makes a new copy of that method (actually only the variables) in memory. Oitce a method ends sing cop ears sme da). the yy of at senting meted eave from meray, The vce pts lok ok al corral and arte ne Fr be ending kt onaerthefOong amp alls ise wih 2.2 What is Recursion? Prin (pie numbers m bach ‘in 0) the theterminating bse tun (pein e's Why Recursion? ‘etn Prin) ieee ” eth cuample fe call hep fncon wih et ly our memory signments may lok ike 2.4 Format of a Recursive Function Pan) Prin) oar Recaro 0 msi uncon ol Returm0 ‘Now: et consider orto uation. The viniation of factor function with ed wlohe: =. a 6-2 is retuoed 1 Dein of 326i armed hie dfn can ety be sin fein Pi-2isreumed 25 Recursion and Memory (Visualization) 2.1 Introductionsoo and Back Structures and Algorithms Made Easy 2.6 Recursion versus I tio 1 Deca Towerof Hen post cron il he Tow of Han mtn par comin fh (oppo tes ero my socal fleets wich an de otany fod. The pose ans wth th as om ida ending dr of i ame) the sole ate tp, thar making 3 coil shape The ete of the ple eo move te nie ck 2 erring he fling ie Bony oa ty Vmods ine Recursion ach move combo aking he pe dk om oe fed a ding mt ste roo po he thers a may snd be pret not Todi be pod cn ty of nea ‘Move the top n~1 dks rom Source w Atay) towe, Mahi di om Sarco Destination ter Move the n~ tisk om Aciny tomer to Destination ower “Tranfering the wp n~ 1d rom Source wo Auelary ower cm apne dough fea problem and cn be led in the une manner Once we salve Tower of Hat with hed we cml with ay ‘umber sk with he howe sith, TowersOMtanoin cha ompes char tope. har ape) | 7 Hfeny 1 disk: mk he move and earn Notes on Recursio Hoo PrinlMove ik] rom eg 0 pe ome, pe 1 Mow top dis fom Ato Bing Ca¥ aly * 1 serie of Towel, mpc, ape. ope) 1. baci (Move remining fm Ato) ell prin\aklove dk Se fom pg st peg mop EE: ee TowensO Mane 1 soe tone ompe i 1 2.10 What is Backtracking? Becuacking the method of exhaustive search sing vig and eonguer. ‘Somes the tes alors fora problem oy al posite Thissabeae low, bat there ate andar ok that canbe set lp " ‘Took alors for generating hale ejects, such at nay ering (2° pies Yor mi P mutations [nl combinations [nri(nr), gen es patie) te Bactrachng speeds the exh search by pring 2.9 Problems on Recursion 2.11 Example Algorithms of Backtracking Binary Swing: guneraing ll binary rings + Generacingk~ary Suis 2.10 What is Backtracking? 2.6 Recursion versus‘Data Structures and Algorithms Mas ‘he Kaapack Protien Genera ow ann ye rer rans ‘Graph arin Prblen 2.12 Problems on Backtracking Problem-2 Generate lls sin Les Bethe running mea arn) Ase Generel he sings length dw rk = 1 Seludon: Let rasan weep carat face ary sags eng ila<1) Lae) be the raaing ime of 7) =firen- 0 ‘Ung Suber 3 Congver ste: ete: For more probes. ele Seri 1 fneton snWhy Constant Time f 3.4 Arrays Overview sceving wes and Algorithms Made Easy spinor change old inked 00) [ow Linked Lists ind Ie ba oe NULL reference. This egies hr he Isto rversed pte st toa NULL erence. Final linked is wastes memory tems of era reference on of Linked Lists with Arrays & Dynamic Arrays Co} ‘4 farey no fal or siing te ements) [oan 09 erionacending | OO [oc fay nt fall Cli ifaray wm lt fi [oa [ou ‘Tavay oo fl (rain he elements) | O@) leet [onary i 5 al fe hig ela) fo a Oe) ‘tinted lis’ mean snl linked i. Tis it cone of numberof nodes in which each dees Rest tothe following eemers. Te ink ofthe nt nade nthe ite NULL which indetesend of the li Ie NULL 7 +e T4 T ings 9p decaration for ined It of integer ine dats i Operations on a List Inserting aie in chet Delesing an er fromthe i arsing the Linked List bin hc he Ne to the tee tthe To avert wes el ing Follow the pines splay the contents of he noes or count) a they ate ated Suop when she nex pine: points to NULL ofa 7 [aes i Head ‘The Lisength function aes inked st as inp and counts the number af nodes inthe i sed for pritingthe it data with exp faction 35 Comparison of Linked Liss with Arrays & Dynamic Arraysanodes net oer polatstohe new nae Fei} He a ing a Node in Singly Linked List at the Middle ue that we re ven» onion where we wan er the ew nod, In thi cte aun we need ody es einen swe wan wo an clement postion 2 shen we wop st postin 2, Tha menos we aves 2 nde nd ree en ete for dap eume tat cond node called poston noe New noe pins nen te poten where we want oa this ode =a Lf [=4 THe) Ee New ede swt the code for ths hee cane. We mas update the fit lent pnts in dhe cing funtion, nok inthe allel fncion. Fr thi reo we ated ownd double pointer The flowing cae inser & ode inthe egy nk it ‘oid rerLinkedLnt(trct ListNado “heat datas postion ( struc LstNodepg"aewNade: ‘ewNode-(tNode allactszefsrct Lita) iflnenNode) prin Nemony eo 1 ewNade oda peat 3.6 Singly Linked Lists ‘36 Singly Linked Lists‘Data Sericrures and Algorithms Mac ® ‘Mowe se bs ‘pine — 1 Pewee “headend in the position where we Licences ue We can implemen: be three Time Comply: O(n. Seis for cating one esporary arb Singly Linked List Deletion Asin inet ete ao we + Detng te: nade Seeing es nde Dele an ioermeda Deleting the First Node in Singly Linked List Head Temp a Te Heal gall Linked Lise BEE rove fm th it Tis operation i ticker than emoving the! A nein te step:‘ava Structures and Algorth ad hed), Deleting Singly Linked List, Ti ty sting secret ody “head - NUL Tie Complexity O(n) or scansing te 3.7 Doubly Linked Lists Bh cane os Atty eds oct ietion A noe na sing inked le cso linked ist wan dele» nal fo previous noe and can err an ex pin of he is. Spe erent node 1), for teatig (ven 2 node in the Be have the pointer oi drs (ince, ea tages of doubt ikData Structures and Algorithms Male 7 : a er Inserting a Node in Doubly Linked List tthe Middle As dcse in ingly nk x. rene ne (te i Head + Potion nae Now. es wrt he code fr al these te cas ot jus ine called futon. Fo ha es {he dovbly linked ix void DLLInserserct DLNede es, imtk- 1 sect DILNie “tem, "0 newNode = (art DLLNode*) ma ‘MlncwNe)| ‘ . newNode-dat = dae postin -- nsering a newNede— Wied) ad) the new ade hee me wantData Seretures and Algorithms Made E59 ‘Deleting the Last Node in Doubly Linked List vende bce alin so ind a mae Dips tel ade pL i _ Previous node oi Deleting an Intermediate Node in Doubly Linked List ‘Assi reise, min revi ‘be deleted, change the previous nodes = at poin a‘Data Structures and Algorithms Made Essy ine suc LitNode "nw » 1a crcl lnkd it we 2 obi inked ats). (Counting Nodes in a Cizcular List The cca at i accent node mek head, withthe bly ov he nodes, he Isha amy ode current coming ee nde Read the it empty, Ace willbe NULL din that exec ‘othe fi nae, kee: head» NULL) esa do{_ coment=eurent—nen: | whee head i ‘Time Complesy: O(n) fr scanning se comp Printing the content ofa Circular List We smume here hat the ls Being ace by ts hea the tll pode fe it wl be the ne previ he hea node, Ler suse we want fo pei ‘odes wating with the head nade Pit i contents nave ote ne vid (tract CLLNode “en meee heat ‘ rer f ———— Current caren nex,Data Structures and Algorithms Made 1 “Tne Comply (9, fr canningMade Ey pce Complexity: 0), ‘Deleting the frst node in Ci See PORT nai whit wl po toed Alo, upsell ade gl nae of head shown tlMade E35 Data Serctures and Algo with D ig 3.10 Problems on Linked List Problem-l —inplement Suck wing Salon: Refer Stacks chp Problem? Find node rom Solan: Brute Force Method S amber of nes ae Solution Yes sig hash icMade Easy gar sig ink tithe op sh Indl the creme of op CoPL-Ok nent puri cueeat nde i ting the ument ode oes hismethod wort? As pershe alin we endef he inked at oterie ne wil Problem-7- Can we ie ing Algo © Tamer linked i odes one by ii already there i hs sed. Tis pombe on lis har ng he nade Bete Gane mith Potin Suge cin SB ee loving slprth ve tn oni And en. ee Aerts ee a ae a ecole > ee i oe Pe es xn oor mung ern mae aaa ‘Think of orbit and 3 hate running on 2a:Data Structures and Algorithms Me etedinConi Siow 8x eP| sit 1 Tame Compe OC Ss Problem-l0._Wesregveaa ds) or tle fens whthera given hie Li Shion: Ie ame a Probl Problem-I1_ Check whet ode ofthe lo Salution: The wstion ean se nine che sow Pe co ne nae sine Te pone ss int FindBesino while 8 ifr ont 1 Hower slow } ftgaapsss hilo ListsData Structures and Algorithms Mi Problem 15 Inns ees ee, by king and a eng eno flowedSpace Complesi: O(n) O(m) Problem-20 Can we ass Soltion: ¥ Algor. Crete wo acs: Tener the Travan the cond lt 3 ps ll Now. compere the op hey aes, ben eee Rerum he vale ofthe Tine Comply: Om +) for aes Problem-21. tsthere a satucon: Podge fi Algosithm + inthe sayin the ine repening leenc in Problem-22 Can we sil think for finding ale ining sorting nd rch Time Compesty: Time for 5 (tax. 2) Problem-23— Can we inyroe [Bien Apprcach: Se Find eogehs (Li 2nd 12) ofboth is Fake aierence do engin Maked sepsin longer), non retin ing shape for 5 Oe same A clement whieh intogm,ntogn) 43.10 Problems on Linked Ls:‘ ad Algo Data Seractures Problem 34 re sich ofthe following gives (1) comple Problem 35 sez wo keds ving 8 ce alec ied ss we mom fd enl aac ea doubly ke ats we ont hve 1 Problem 36 inc ewo . ircular linked lst using, Floyd cycle finding id Spline LixNose “haart LitNode hea, rue Lito seu LitNode ‘MlowPis hea fed — NULL edd ode inthe circa i then aris then it Prr ent be 2 frevem nes ass ner ‘3.10 Problems on Linked ListsData Strucures and Pfoblem 4 jeg ee ewe Linde inate N rie rin Baer 6 (oer “BOP * ‘fade Easy Data Structures and Algorithms crea isthe ol copy ofthe nde that ou posto frp one we temp NULL me stepson: epee Rep damage old Ht nd fil n nest pointer inne Bist ie Gem NULL) sey OCD. numbers, give an algerth fr making changes Problem-43 Givens linkd le with even and lem, we can use the sping lg. While traversing the li, pit he Hed fen nas at eke onsning ll odd nodes Now, to get te fal st we ean aig lr the even node inked i inked lis, averse the oii linked land move alo nodes a separate Une il Atte end flop, he origina is wl hae al the even odes nd the odd node wl hve al il ep the ordering ofall noes same, we must inser ll the ad nodes at he end ofthe od node Time Complesiey: 0) Space Complenty: 1)Made Easy seructures and Algorithms Data from he stack Away stack operations cher he each ells: oe Exceptions ’ lt Sack ADT, operas 2 Nice emp Ateping th est of FOP 44 Applications Fatoving ete soe types whieh Direct applications Salosing of yas wing nein calls (ding recuson) ing pans in sock mrs fr Problems eon) rack Bator) ching Tas ia HTML aod 10 Indirect applications sir aa sre rts gorithms (Semple: Tre avers agp) ramp Simulting ques fe Queues chapter * Gempenentet 45 Implementation There many vay ofnplentng sack ADT and elo arth commonly meth Single aay bed Dynamic ay ted implemention 2 Linked ties implement Simple Array Implementation TiiPinplementaton of wack ADT ck of nerf the top clement an arey- Inthe ary, we add lements rom left ight andcapes 4 ange Toying 0 push ae Dynamic Array Implementation cs simple gay bused stack, We tok oe index ai , wus) an element, we neem ack. Tomer to dle (or pop) an element we take the ele uly inser elemeng nthe tis sin aed ae ary sock copied? wife acrement the iz ofthe ary by 1 very ine the sak is fall 1 of: decease se of 571 Problems wit this pponch? fs oo expensive Let ws se the aon for his For example, a 2 and copy ail the old ary element to new ary ad atthe end a snow array ofa mand copy al he od aay m= =e nso phan clement co 5s the itl ne 716) Game similarly a to pew ary and ah coment. Aer pes oer operas) proporcnl a 1 + 2 Aernave Appr RepesteéDashng ee eee earn ne, and copy ems, With thi apron, pai lig tachoiqu, HE the ary il crete» newb sem takes ime proportional to (000) = nd moved tll n = 32. That mea doubling at 1,248.16 The ther way of aalysing the same at n = 1, if we want add Qu a double the cates sie of aray and copy all ce clemens Aik = 1, we do copy operation stn = 2, edo 2 copy operons and n= 4, we do 4 ony opel By the time we rach n= 32, che al number of copy persion is 14+ 2 + 4+ Botte ae doing the doubling operation og approximately quo 21 value (32) Ine obec scusion. Form push operons we double the ary size fog times, Thal on. The tt time T(n) of seri of push operations pope ave log terms in below exp 1424448.orthms Made Easy Da Seruetares and Algorithms ce Comply Time Complety ie Comglest me Compl Linked List Implementation ening ach iby wig Li ‘pera plemented seni Push Sack temp = mallcore tempter Pg Ine Egy nt at sent Sack ‘emp, IsFmpy Sack tep dated fete 45 Implementation engages) [OOgorithms Made Easy Fray or Tei ais oF Tf gh =o Teo ht Tegan = — st pa Tage = rahe Tc Leen consider the infix expression 2 the oder ofthe mer operand) 1 esis expesons do ot 3 dandy equivalent 234° +, Notice that beeen pe es 234 in bth ass, Buc the petra Only one sack enough algocthm willbe used to change the onder of cna ermiehandake open frente om hl not ouput patentee stb port ap reson, The stack tht we x. The sac We See Algo, 2) foreach chunctertinthe input fcr a ight parenhes), Popand ouput tokens nef parenthesis popped (ut nto) an operator re pene op and eutpt ters unl oxeoflower priory tan x encountered or ef pa ncoustared or he stack emp Popand oupet kent unt the tack empty Forbecer understanding le us wae owt some sample: A*B- (C+D) +E ‘Hapa Gana |Openionon Sack Sack | Poti apres [ime [A 47 Problems on Stacksata Seructues a The value oftenData Structures and Al wrt Advance S = (trict Avan ounce Advanced Time Sep tn cock}, Tis gph ba mach Dee Se Problem-6 forthe it posible improve the accompli? son: Yer. The min problem of revou spponh i och ph operation we are ping he ack ao (ter dh ne element oe eiting minim cere). That meas, we are pushing je sgh ipo the pe cplesy. Wes ave he a tac, ut op fom he masta el ocho on he min ack We only sh sack when hee ng tl oo he mast les thn or sh be cent va In hi Sit lif we wane topcase we at ne te teapot in an ng egal vee sa eng Lag: we ge Nain mck | Mis ick Say ‘Main ack | Mis wack} oping gin oly pops rm he main sack, (Mas ack [Mia]Data Structures and Algorith Tine Comper) Spe Complex: O( Problem-9 For the Problem, ifthe nif singly linked List Seleion:Reer Linked Lists caper. Probes-10 bien 8 gic Algom > Tavee he lat il we en During the travers pas al he lee wack ote gre each mets conten th top ofthe ack they ae same the saad in the ipa i sina thi process until the sacks expy othe atin palindrome 1 tur pStack 1 Time Gomplesiy: O(n. Space Comps 01 |) Problem-11 Givens ack, how 0 eves he . ink operationDracut Apri Mae mee 1 Ld a sucks we ee he ftw norm ; of hist To implemen ith Staring index of th hid ack bane froth ach mina pop operons for tis see ailing» nw chen nae to Bam the pew element teat + Top ito bop and Topd Dron nego vc bgt ad ncn cy ah ro aT ctr edt eee nesta of he apron mick andy pushing agin. Inset the en Time Compisty:O(1).Spue Complexe: Problem-16 Foc Problem 15, iether any ch the righ sack eich grows othe lil Sato: Yes. When he the fl tac which grows imo the mide ack, we ned wo shi the ete mide ecko make room. The ame thing tappene pl blem (umber of hil) what we ea mide ack cases ito bumpin the right tack To solve he sve heoning pies coud added at orang side ofthe idle It For ample even clement ae pac hd othe sgt) Thi would hoe the mide tack balanced inthe cnet of the aay 1, wheher by growing on is own oF 3yimplenting mide sack? lead elements would il need be si when bumps hele oh of he three stacks if they growin at diferent ates and i one stack doen't change much. f you pot ie at hee then i eave «apne the idle dc ight tacks which pa ut of space inthe aay, Teves no change a We can optimise the inital cat Aiferen average sit. or example spo stack wll evenly gst psa! oping ‘ch other If ehey clide, then its likely yon ver comple but he average number shew pa educed Problem-17 Null (sachs none a As similar to Proble-15, what fe want ipl tuple Bee er snes tare ines ueftm 1. Asinar toch dni of nec seth w aay we eh yom para hve tl), Te se en ok Basefma) Tope)Data Structures and Algorithms “= operation and aisha indetes 2 P Problem-20- ier ssn comainns * Me roehck whee iver SE Salmon: Given 2 ring of length 2, we wi with rope to farting on a sack. The ely resiced open is op wow FOr RSI ng om 3h Th eek ih pit 207 POP een ma rere ree hn aber of OPO Proble-21 Suppo thie two gine ss Both of wich inert ame pit ne i The eo pone bt ei re at he eof erin ch the 7 eet ty have de hie tc nd Us gt et erecta tos te inde erg oi ing a SEO i ae i — Solution: Yer. or ed ists hae Problem-22 Finding Sans my A lem-22 Finding Spans: Given an ary A, the san Sf of A isthe maximum number of @ ene medic preceding A) ‘ nc chr Af Al Gitecmy of waking Given an ay A of integer, ad the macau ofj~ sje 4 the coon Solution:aright sn Problem-25 for Problem 24.0 Selon: ine seach ngs of comple bribes solving i the ements in let Tap the stack The, we dacard h ay all bobo se nied nc thes ce beep the ations vere ‘eens have been priced, adhe sack ie) top Stor! eigt q Tit inpreion this scat seems tote having 0 ‘ibe snd popped mon one adn ne cp fof Wot forthe deci and tse upd [Space Gomplesiy: O(n) or aac : we look cael, even ssn: a ne leet pad a slot of the algorithm i OOO ao
You might also like
DS Through C
PDF
100% (1)
DS Through C
542 pages
Data Structures and Algorithms Made Easy - Data Structures and Algorithmic Puzzles
PDF
50% (2)
Data Structures and Algorithms Made Easy - Data Structures and Algorithmic Puzzles
828 pages
Design & Analysis of Algorithms (Book)
PDF
100% (1)
Design & Analysis of Algorithms (Book)
263 pages
Data Structures and Algorithms Made Easy-Narasimha Karumanchi
PDF
85% (40)
Data Structures and Algorithms Made Easy-Narasimha Karumanchi
228 pages
GATE NOTES - Computer Networks(s) - Optimize
PDF
100% (2)
GATE NOTES - Computer Networks(s) - Optimize
190 pages
Design and Analysis of Algorithm
PDF
100% (2)
Design and Analysis of Algorithm
210 pages
Kruse - Data Structures and Program Design in C 1991
PDF
100% (2)
Kruse - Data Structures and Program Design in C 1991
272 pages
Crisc PDF
PDF
No ratings yet
Crisc PDF
9 pages
A Practical Approach To Data Structures and Algorithms-1
PDF
No ratings yet
A Practical Approach To Data Structures and Algorithms-1
573 pages
Java Handwritten Notes
PDF
No ratings yet
Java Handwritten Notes
86 pages
Deep Sea Electronics PLC: 5210 Autostart Module Operating Manual
PDF
No ratings yet
Deep Sea Electronics PLC: 5210 Autostart Module Operating Manual
55 pages
Algorithm
PDF
100% (5)
Algorithm
327 pages
CS8501 - Theory of Computation (Ripped From Amazon Kindle Ebooks by Sai Seena)
PDF
100% (1)
CS8501 - Theory of Computation (Ripped From Amazon Kindle Ebooks by Sai Seena)
520 pages
Operating Systems Notes
PDF
100% (8)
Operating Systems Notes
325 pages
Data Structures & Algorithms Interview Questions You'll Most Likely Be Asked
PDF
20% (5)
Data Structures & Algorithms Interview Questions You'll Most Likely Be Asked
24 pages
Data Structure-Basic Terminology
PDF
80% (10)
Data Structure-Basic Terminology
7 pages
Data Structures Algorithms Tutorial
PDF
0% (3)
Data Structures Algorithms Tutorial
19 pages
Data Structures
PDF
100% (2)
Data Structures
75 pages
Books4career - Placement Preparation
PDF
No ratings yet
Books4career - Placement Preparation
151 pages
Principles of Compiler Design
PDF
100% (4)
Principles of Compiler Design
162 pages
Complete Data Structures and Algorithms Guide: Resources, Notes, Questions, Solutions
PDF
No ratings yet
Complete Data Structures and Algorithms Guide: Resources, Notes, Questions, Solutions
100 pages
Data Structures and Algorithms Quick Guide
PDF
100% (1)
Data Structures and Algorithms Quick Guide
73 pages
Data Structure Using C
PDF
58% (12)
Data Structure Using C
250 pages
Data Structures & Algorithms - 1
PDF
No ratings yet
Data Structures & Algorithms - 1
100 pages
Theory of Computation (TOC) Notes
PDF
100% (3)
Theory of Computation (TOC) Notes
62 pages
DESIGN & ANALYSIS OF ALGORITHMS - Lecture 1
PDF
No ratings yet
DESIGN & ANALYSIS OF ALGORITHMS - Lecture 1
22 pages
Algorithms Notes For Professionals
PDF
100% (3)
Algorithms Notes For Professionals
253 pages
Design and Analysis of Algorithm Quantum
PDF
100% (14)
Design and Analysis of Algorithm Quantum
359 pages
Algorithms Illuminated Part3
PDF
100% (5)
Algorithms Illuminated Part3
230 pages
Data Structures Basic Programs
PDF
No ratings yet
Data Structures Basic Programs
132 pages
DVC Notifier
PDF
No ratings yet
DVC Notifier
4 pages
Data Structures
PDF
100% (4)
Data Structures
275 pages
Data Structures and Algorithms Made Easy Cover
PDF
9% (32)
Data Structures and Algorithms Made Easy Cover
1 page
1 Introduction
PDF
No ratings yet
1 Introduction
104 pages
Data Structure
PDF
100% (2)
Data Structure
72 pages
ITSE205-DataStructures and Algorithms PDF
PDF
No ratings yet
ITSE205-DataStructures and Algorithms PDF
115 pages
Computer Science and Engineering
PDF
No ratings yet
Computer Science and Engineering
247 pages
A Complete Note On Data Structure and Algorithms
PDF
No ratings yet
A Complete Note On Data Structure and Algorithms
160 pages
Data Structures and Algorithms - Lecture 1 - Arrays
PDF
100% (5)
Data Structures and Algorithms - Lecture 1 - Arrays
25 pages
Data Structures Coding Interview 90+ Chapters
PDF
100% (1)
Data Structures Coding Interview 90+ Chapters
35 pages
Maharashtra Industrial Development Corporation (MIDC) Recruitment Examination - August 2021 Admit Card For Computer Based Online Exam - Provisional
PDF
No ratings yet
Maharashtra Industrial Development Corporation (MIDC) Recruitment Examination - August 2021 Admit Card For Computer Based Online Exam - Provisional
3 pages
XCT 7 40vcc617fqee
PDF
No ratings yet
XCT 7 40vcc617fqee
294 pages
Data Structures & Algorithms
PDF
89% (19)
Data Structures & Algorithms
52 pages
Design and Analysis of Algorithm
PDF
No ratings yet
Design and Analysis of Algorithm
116 pages
Lecture3-Analysis of Algo
PDF
No ratings yet
Lecture3-Analysis of Algo
58 pages
CP Algo PDF
PDF
56% (9)
CP Algo PDF
440 pages
Unit 1 - Daa - Notes - 2023
PDF
No ratings yet
Unit 1 - Daa - Notes - 2023
30 pages
DSA Study Guide
PDF
No ratings yet
DSA Study Guide
1 page
Data Structures & Algorithms
PDF
89% (18)
Data Structures & Algorithms
431 pages
14EIT72 Instrumentation System Design UNIT-IV - Computer Based Controller
PDF
No ratings yet
14EIT72 Instrumentation System Design UNIT-IV - Computer Based Controller
48 pages
Introduction To Algorithms
PDF
90% (10)
Introduction To Algorithms
769 pages
15MA302 Discrete Mathematics PDF
PDF
100% (1)
15MA302 Discrete Mathematics PDF
3 pages
The Theory of Computation
PDF
100% (21)
The Theory of Computation
471 pages
STUDENT VERSION - 017 Data Structures and Algorithms V1
PDF
No ratings yet
STUDENT VERSION - 017 Data Structures and Algorithms V1
202 pages
Striver's CP List (Solely For Preparing For Coding Rounds of Top Prod Based Companies)
PDF
100% (2)
Striver's CP List (Solely For Preparing For Coding Rounds of Top Prod Based Companies)
7 pages
Intro To Design & Analysis of Algorithms 3e
PDF
100% (5)
Intro To Design & Analysis of Algorithms 3e
593 pages
Design and Analysis of Algorithms
PDF
91% (11)
Design and Analysis of Algorithms
94 pages
Google Technical Interview Prep - Trello
PDF
No ratings yet
Google Technical Interview Prep - Trello
4 pages
Mcs 021 PDF
PDF
No ratings yet
Mcs 021 PDF
171 pages
2marks DAA
PDF
No ratings yet
2marks DAA
10 pages
Algorithm Analysis: Prof - Dr.Eng - Ir Taufik Djatna
PDF
No ratings yet
Algorithm Analysis: Prof - Dr.Eng - Ir Taufik Djatna
39 pages
Algorithms Design and Analysis by Udit Agarwal PDF
PDF
67% (15)
Algorithms Design and Analysis by Udit Agarwal PDF
245 pages
5.12 English
PDF
No ratings yet
5.12 English
35 pages
Data Structures and Algorithms Made Easy (In Java)
PDF
10% (144)
Data Structures and Algorithms Made Easy (In Java)
1 page
CEC366 Image Processing
PDF
No ratings yet
CEC366 Image Processing
2 pages
AIML Notes
PDF
No ratings yet
AIML Notes
75 pages
1994.roberts. Defining Electronic Records, Document and Data PDF
PDF
No ratings yet
1994.roberts. Defining Electronic Records, Document and Data PDF
13 pages
Data Structures and Algorithms: 1 Algorithm Analysis and Recursion
PDF
No ratings yet
Data Structures and Algorithms: 1 Algorithm Analysis and Recursion
37 pages
Simple en Crypt Ing and Decrypting Data in C#
PDF
No ratings yet
Simple en Crypt Ing and Decrypting Data in C#
7 pages
Analysis of Algorithms Review: Adapted From Notes of S. Sarkar of Upenn, Skiena of Stony Brook, Etc
PDF
No ratings yet
Analysis of Algorithms Review: Adapted From Notes of S. Sarkar of Upenn, Skiena of Stony Brook, Etc
32 pages
Technical Ptoposal-Zncb Head Office-Questionnaire Information - Og
PDF
No ratings yet
Technical Ptoposal-Zncb Head Office-Questionnaire Information - Og
303 pages
Timetable Generator Using Genetic Algorithms 1
PDF
No ratings yet
Timetable Generator Using Genetic Algorithms 1
15 pages
WS-C3650-24TS-S Datasheet: Quick Specs
PDF
No ratings yet
WS-C3650-24TS-S Datasheet: Quick Specs
8 pages
Dichvusocks - Us - Service Socks5, Anonymous Proxy, Proxy Service, Proxy Server, Hide Your IP, Tools Client
PDF
No ratings yet
Dichvusocks - Us - Service Socks5, Anonymous Proxy, Proxy Service, Proxy Server, Hide Your IP, Tools Client
1 page
Excavating AI
PDF
No ratings yet
Excavating AI
3 pages
Rohini 66482883011
PDF
No ratings yet
Rohini 66482883011
7 pages
Sixteen
PDF
No ratings yet
Sixteen
36 pages
Nama Item Harga Keterangan
PDF
No ratings yet
Nama Item Harga Keterangan
14 pages
Visiferm RS485 ProgrammersManual ODOUM102 11100430201
PDF
No ratings yet
Visiferm RS485 ProgrammersManual ODOUM102 11100430201
97 pages
Updated UM Praptra1
PDF
No ratings yet
Updated UM Praptra1
17 pages
Daftar Pustaka - (New)
PDF
No ratings yet
Daftar Pustaka - (New)
13 pages
Lecture 02 Write Basic Go Web Server
PDF
No ratings yet
Lecture 02 Write Basic Go Web Server
17 pages
P1411 Puppis S1 User Manual V1.1
PDF
No ratings yet
P1411 Puppis S1 User Manual V1.1
60 pages
2PGDCA2 Unit II Internet and Web Designing
PDF
No ratings yet
2PGDCA2 Unit II Internet and Web Designing
26 pages
Rahul Resume Sept 2021
PDF
No ratings yet
Rahul Resume Sept 2021
3 pages
Zihad Projeject
PDF
No ratings yet
Zihad Projeject
20 pages
Ngaf M4500
PDF
No ratings yet
Ngaf M4500
2 pages
Isen6902 HW01
PDF
No ratings yet
Isen6902 HW01
2 pages