· acknowledgement the author is very grateful to god almighty for his grace and blessing. deepest...

578

Upload: others

Post on 06-Aug-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 2:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemSolvinginDataStructures&AlgorithmsUsingCFirstEdition

ByHemantJain

Page 3:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BookTitle:ProblemsSolvinginDataStructures&AlgorithmsUsingCBookAuthor:HemantJainPublishedbyHemantJainHIG 4, Samarth Tower, Sarvadharm,D Sector, Bhopal, India, Pin Code:462042PublishedinBhopal,IndiaThiseditionpublishedMarch2017

Copyright©HemantJain2017.AllRightReserved.Hemant Jain asserts themoral right tobe identified as the author of thiswork.Allrightsreserved.Nopartofthispublicationmaybereproduced,storedinorintroducedintoaretrievalsystem,ortransmitted,inanyform,orbyanymeans (electrical,mechanical, photocopying, recording or otherwise)without the priorwritten permission of the author, except in the case ofvery brief quotations embodied in critical reviews and certain other non-commercial uses permitted by copyright law. Any person who does anyunauthorized act in relation to this publicationmaybe liable to criminalprosecutionandcivilclaimsfordamages.

Page 4:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 5:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ACKNOWLEDGEMENTTheauthorisverygratefultoGODALMIGHTYforhisgraceandblessing.DeepestgratitudeforthehelpandsupportofmybrotherDr.SumantJain.This book would not have been possible without the support andencouragementheprovided.Iwouldliketoexpressprofoundgratitudetomyguide/myfriendNaveenKaushik for his invaluable encouragement, supervision and usefulsuggestionthroughoutthisbookwritingwork.Hissupportandcontinuousguidanceenablemetocompletemyworksuccessfully.Finally yet importantly, I am thankful to Love Singhal, Anil Berry andOtherswhohelpedmedirectlyorindirectlyincompletingthisbook.HemantJain

Page 6:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 7:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 8:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TABLEOFCONTENTSTABLEOFCONTENTSCHAPTER0:HOWTOUSETHISBOOKWHATTHISBOOKISABOUTPREPARATIONPLANSSUMMARY

CHAPTER1:INTRODUCTION-PROGRAMMINGOVERVIEWINTRODUCTIONVARIABLEPOINTERSARRAYTWODIMENSIONALARRAYARRAYINTERVIEWQUESTIONSSTRUCTUREPOINTERTOSTRUCTUREDYNAMICMEMORYALLOCATIONFUNCTIONCONCEPTOFSTACKSYSTEMSTACKANDFUNCTIONCALLSPARAMETERPASSING,CALLBYVALUEPARAMETERPASSING,CALLBYREFERENCERECURSIVEFUNCTIONEXERCISES

CHAPTER2:ALGORITHMSANALYSISINTRODUCTIONASYMPTOTICANALYSISBIG-ONOTATIONOMEGA-ΩNOTATIONTHETA-ΘNOTATIONCOMPLEXITYANALYSISOFALGORITHMSTIMECOMPLEXITYORDERDERIVINGTHERUNTIMEFUNCTIONOFANALGORITHMTIMECOMPLEXITYEXAMPLESMASTERTHEOREMMODIFIEDMASTERTHEOREMEXERCISE

CHAPTER3:APPROACHTOSOLVEALGORITHMDESIGNPROBLEMSINTRODUCTIONCONSTRAINTSIDEAGENERATION

Page 9:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

COMPLEXITIESCODINGTESTINGEXAMPLESUMMARY

CHAPTER4:ABSTRACTDATATYPEABSTRACTDATATYPE(ADT)DATA-STRUCTUREARRAYLINKEDLISTSTACKQUEUETREESBINARYTREEBINARYSEARCHTREES(BST)PRIORITYQUEUE(HEAP)HASH-TABLEDICTIONARY/SYMBOLTABLEGRAPHSGRAPHALGORITHMSSORTINGALGORITHMSCOUNTINGSORTENDNOTE

CHAPTER5:SEARCHINGINTRODUCTIONWHYSEARCHING?DIFFERENTSEARCHINGALGORITHMSLINEARSEARCH–UNSORTEDINPUTLINEARSEARCH–SORTEDBINARYSEARCHSTRINGSEARCHINGALGORITHMSHASHINGANDSYMBOLTABLESHOWSORTINGISUSEFULINSELECTIONALGORITHM?PROBLEMSINSEARCHINGEXERCISE

CHAPTER6:SORTINGINTRODUCTIONTYPEOFSORTINGBUBBLE-SORTMODIFIED(IMPROVED)BUBBLE-SORTINSERTION-SORTSELECTION-SORTMERGE-SORT

Page 10:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

QUICK-SORTQUICKSELECTBUCKETSORTGENERALIZEDBUCKETSORTHEAP-SORTTREESORTINGEXTERNALSORT(EXTERNALMERGE-SORT)COMPARISONSOFTHEVARIOUSSORTINGALGORITHMS.SELECTIONOFBESTSORTINGALGORITHMEXERCISE

CHAPTER7:LINKEDLISTINTRODUCTIONLINKEDLISTTYPESOFLINKEDLISTSINGLYLINKEDLISTDOUBLYLINKEDLISTCIRCULARLINKEDLISTDOUBLYCIRCULARLISTEXERCISE

CHAPTER8:STACKINTRODUCTIONTHESTACKABSTRACTDATATYPESTACKUSINGARRAY(MACRO)STACKUSINGARRAY(DYNAMICMEMORY)STACKUSINGARRAY(GROWINGCAPACITYIMPLEMENTATION)STACKUSINGARRAY(GROWING-REDUCINGCAPACITYIMPLEMENTATION)STACKUSINGLINKEDLISTPROBLEMSINSTACKPROSANDCONSOFARRAYANDLINKEDLISTIMPLEMENTATIONOFSTACK.USESOFSTACKEXERCISE

CHAPTER9:QUEUEINTRODUCTIONTHEQUEUEABSTRACTDATATYPEQUEUEUSINGARRAYQUEUEUSINGLINKEDLISTPROBLEMSINQUEUEEXERCISE

CHAPTER10:TREEINTRODUCTIONTERMINOLOGYINTREEBINARYTREE

Page 11:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TYPESOFBINARYTREESPROBLEMSINBINARYTREEBINARYSEARCHTREE(BST)PROBLEMSINBINARYSEARCHTREE(BST)EXERCISE

CHAPTER11:PRIORITYQUEUEINTRODUCTIONTYPESOFHEAPHEAPADTOPERATIONSOPERATIONONHEAPHEAP-SORTUSESOFHEAPPROBLEMSINHEAPEXERCISE

CHAPTER12:HASH-TABLEINTRODUCTIONHASH-TABLEHASHINGWITHOPENADDRESSINGHASHINGWITHSEPARATE-CHAININGPROBLEMSINHASHINGEXERCISE

CHAPTER13:GRAPHSINTRODUCTIONGRAPHREPRESENTATIONADJACENCYMATRIXADJACENCYLISTGRAPHTRAVERSALSDEPTHFIRSTTRAVERSALBREADTHFIRSTTRAVERSALPROBLEMSINGRAPHDIRECTEDACYCLICGRAPHTOPOLOGICALSORTMINIMUMSPANNINGTREES(MST)SHORTESTPATHALGORITHMSINGRAPHEXERCISE

CHAPTER14:STRINGALGORITHMSINTRODUCTIONSTRINGMATCHINGDICTIONARY/SYMBOLTABLEPROBLEMSINSTRINGMEMMOVEFUNCTIONEXERCISE

Page 12:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER15:ALGORITHMDESIGNTECHNIQUESINTRODUCTIONBRUTEFORCEALGORITHMGREEDYALGORITHMDIVIDE-AND-CONQUER,DECREASE-AND-CONQUERDYNAMICPROGRAMMINGREDUCTION/TRANSFORM-AND-CONQUERBACKTRACKINGBRANCH-AND-BOUNDA*ALGORITHMCONCLUSION

CHAPTER16:BRUTEFORCEALGORITHMINTRODUCTIONPROBLEMSINBRUTEFORCEALGORITHMCONCLUSION

CHAPTER17:GREEDYALGORITHMINTRODUCTIONPROBLEMSONGREEDYALGORITHM

CHAPTER18:DIVIDE-AND-CONQUER,DECREASE-AND-CONQUERINTRODUCTIONGENERALDIVIDE-AND-CONQUERRECURRENCEMASTERTHEOREMPROBLEMSONDIVIDE-AND-CONQUERALGORITHM

CHAPTER19:DYNAMICPROGRAMMINGINTRODUCTIONPROBLEMSONDYNAMICPROGRAMMINGALGORITHM

CHAPTER20:BACKTRACKINGANDBRANCH-AND-BOUNDINTRODUCTIONPROBLEMSONBACKTRACKINGALGORITHM

CHAPTER21:COMPLEXITYTHEORYANDNPCOMPLETENESSINTRODUCTIONDECISIONPROBLEMCOMPLEXITYCLASSESCLASSPPROBLEMSCLASSNPPROBLEMSCLASSCO-NPNP–HARD:NP–COMPLETEPROBLEMSREDUCTIONENDNOTE

Page 13:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER22:INTERVIEWSTRATEGYINTRODUCTIONRESUMENONTECHNICALQUESTIONSTECHNICALQUESTIONS

CHAPTER23:SYSTEMDESIGNSYSTEMDESIGNSYSTEMDESIGNPROCESSSCALABILITYTHEORYDESIGNSIMPLIFIEDFACEBOOKDESIGNFACEBOOKFRIENDSSUGGESTIONFUNCTIONDESIGNASHORTENINGSERVICELIKEBITLYSTOCKQUERYSERVERDESIGNABASICSEARCHENGINEDATABASEDESIGNABASICSEARCHENGINECACHINGDUPLICATEINTEGERINMILLIONSOFDOCUMENTSZOMATOYOUTUBEDESIGNIRCTCALARMCLOCKDESIGNFORELEVATOROFABUILDINGVALETPARKINGSYSTEMOODESIGNFORAMCDONALDSSHOPOBJECTORIENTEDDESIGNFORARESTAURANTOBJECTORIENTEDDESIGNFORALIBRARYSYSTEMSUGGESTASHORTESTPATHEXERCISE

APPENDIXAPPENDIXA

Page 14:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 15:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER0:HOWTOUSETHISBOOK

Page 16:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 17:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

WhatthisbookisaboutThisbookisaboutusageofdatastructuresandalgorithmsincomputerprogramming.Datastructuresarethewaysinwhichdataisarrangedincomputersmemory.Algorithmsaresetofinstructionstosolvesomeproblembymanipulatingthesedatastructures.DesigninganefficientalgorithmtosolveacomputerscienceproblemisaskillofComputerprogrammer.TheskillwhichtechcompanieslikeGoogle,Amazon,Microsoft,Facebook,Adobeandmanyothersarelookingfor inan interview.Oncewearecomfortablewithaprogramminglanguage, thenextstep is tolearnhowtowriteefficientalgorithms.ThisbookassumesthatyouareaClanguagedeveloper.YouarenotanexpertinClanguage,butyouarewellfamiliarwithconceptsofpointers,functions,arraysandrecursion.Atthestartofthisbook,wewillberevisingtheClanguagefundamentalsthatwillbeusedthroughoutthisbook.Wewillbelookingintosomeoftheproblemsinarraysandrecursiontoo.TheninthecomingchapterwewillbelookingintoComplexityAnalysis.Followedbythevariousdatastructures and their algorithms.Will look into a linked list, stack, queue, trees, heap,Hash-Table andgraphs.Wewillalsobelookingintosorting,searchingtechniques.Moreover, we will be looking into analysis of various algorithm techniques, such as brute forcealgorithms, greedy algorithms, divide & conquer algorithms, dynamic programming, reduction &backtracking.Intheend,wewillbelookingintosystemdesignthatwillgiveasystematicapproachtosolvethedesignproblemsinanInterview.

Page 18:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

PreparationPlansGiven the limited timeyouhavebeforeyournext interview, it is important tohaveasolidpreparationplan.Thepreparationplandependsuponthetimeandwhichcompaniesyouareplanningtotarget.Belowarethethree-preparationplanfor1Month,3Monthand5Monthdurations.

1MonthPreparationPlansBelowisalistoftopicsandapproximatetimeuserneedtotaketofinishthesetopics.Thesearethemostimportantchaptersthatmusttobepreparedbeforeappearingforaninterview.Thisplanshouldbeusedwhenyouhavealimitedtimebeforeaninterview.Thesechapterscover90%ofdata structures and algorithm interview questions. In this plan sincewe are reading about the variousADTinchapter4sowecanusethesedatatypeeasilywithoutknowingtheinternaldetailshowtheyareimplemented.Chapter24isforsystemdesign,youmustreadthischapterifyouarethreeormoreyearsofexperienced.Anyway,readingthischapterwillgivethereaderabroaderperspectiveofvariousdesigns.Time Chapters Explanation

Week1

Chapter 1: Introduction - ProgrammingOverviewChapter2:AlgorithmsAnalysisChapter 3: Approach To Solve AlgorithmDesignProblemsChapter4:AbstractDataType

You will get a basic understanding of how to findcomplexity of a solution. You will know how tohandlenewproblems.Youwill read about avarietyofdatatypesandtheiruses.

Week2Chapter5:SearchingChapter6:SortingChapter14:StringAlgorithms

Searching,SortingandStringalgorithmconsistsofamajorportionoftheinterviews.

Week3Chapter7:LinkedListChapter8:StackChapter9:Queue

Linkedlistsareoneofthefavouritesinaninterview.

Week4Chapter10:TreeChapter23:InterviewStrategyChapter24:SystemDesign

This portion youwill read about Trees and SystemDesign.You are good to go for interviews. Best ofluck.

3MonthPreparationPlanThisplanshouldbeusedwhenyouhavesome time toprepare foran interview.Thispreparationplanincludesnearlyeverythinginthisbookexceptvariousalgorithmtechniques.Algorithmproblemsthatarebasedondynamicprogramming,divide&conqueretc.WhichareaskedinvaryspecificcompanieslikeGoogle,Facebook,etc.Therefore,untilyouareplanningtofaceinterviewwiththemyoucanparkthesetopicsforsometimeandfocusontherestofthetopics.Again,samethingherewithsystemdesignproblems,themoreexperienceyouare,themoreimportantthischapterbecomes.However,ifyouareafresherfromcollege,thenalsoyoushouldreadthischapter.Time Chapters Explanation

Page 19:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Week1

Chapter 1: Introduction - ProgrammingOverviewChapter2:AlgorithmsAnalysisChapter 3: Approach To Solve AlgorithmDesignProblemsChapter4:AbstractDataType

Youwill get abasicunderstandingofhow to findcomplexity of a solution. You will know how tohandle new problems. You will read about avarietyofdatatypesandtheiruses.

Week 2 &Week3

Chapter5:SearchingChapter6:SortingChapter14:StringAlgorithms

Searching, sorting and string algorithmconsists ofamajorportionoftheinterviews.

Week 4 &Week5

Chapter7:LinkedListChapter8:StackChapter9:Queue

Linked lists are one of the favourites in aninterview.

Week 6 &Week7

Chapter10:TreeChapter11:Heap

This portion you will read about trees and heapdatastructures.

Week 8 &Week9

Chapter12:Hash-TableChapter13:Graphs

Hash-Table are used throughout this book invarious places but now it is time to understandhowHash-Tableareactuallyimplemented.Graphsare used to propose a solution many real lifeproblems.

Week10 Chapter23:InterviewStrategyChapter24:SystemDesign

Interview strategy and system design chapter arethefinalchaptersofthiscourse.

Week 11 &Week12 Revisionofthechapterslistedabove.

At this time, you need to revise all the chaptersthat we have seen in this book.Whatever is leftneeds to be completed and the exercise that maybeleftneedingtobesolvedinthisperiod.

5MonthPreparationPlanThispreparationplanismadeontopof3-monthplan.Inthisplan,thestudentsshouldlookforalgorithmdesign chapters. In addition, in the rest of the time they need to practice more and more fromwww.topcoder.com and other resources. If you are targeting google, Facebook, etc., then it is highlyrecommendedtojointopcoderandpracticeasmuchaspossible.Time Chapters Explanation

Week1Week2

Chapter 1: Introduction - ProgrammingOverviewChapter2:AlgorithmsAnalysisChapter3:ApproachToSolveAlgorithmDesignProblemsChapter4:AbstractDataType

You will get a basic understanding of how tofind complexity of a solution. You will knowhow to handle new problems. You will readaboutavarietyofdatatypesandtheiruses.

Week 3Week4Week5

Chapter5:SearchingChapter6:SortingChapter14:StringAlgorithms

Searching, sorting and string algorithm consistsofamajorportionoftheinterviews.

Week 6Week7Week8

Chapter7:LinkedListChapter8:StackChapter9:Queue

Linked lists are one of the favourites in aninterview.

Week9Week10

Chapter10:TreeChapter11:Heap Thisportionyouwillreadabouttrees

Week11Week12

Chapter12:Hash-TableChapter13:Graphs

Hash-Table are used throughout this book invarious places but now it is time to understandhow Hash-Table are actually implemented.

Page 20:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Graphsareusedtoproposeasolutionmanyreallifeproblems.

Week13Week14Week 15Week16

Chapter15:AlgorithmDesignTechniquesChapter16:BruteForceChapter17:GreedyAlgorithmChapter 18: Divide-And-Conquer, Decrease-And-ConquerChapter19:DynamicProgrammingChapter 20: Backtracking And Branch-And-BoundChapter 21: Complexity Theory And NpCompleteness

Thesechapterscontainvariousalgorithmstypesand their usage. Once the user is familiar withmostof this algorithm.Then thenext step is tostart solving topcoder problems fromhttps://www.topcoder.com/

Week 17Week18

Chapter22:InterviewStrategyChapter23:SystemDesign

Interviewstrategyandsystemdesignchapterarethefinalchaptersofthiscourse.

Week 19Week20

Revisionofthechapterslistedabove.

At this time,youneed to reviseall thechaptersthatwehaveseeninthisbook.Whateverisleftneedstobecompletedandtheexercisethatmaybeleftneedingtobesolvedinthisperiod.

Page 21:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

SummaryTheseare fewpreparationplans thatcanbe followed tocomplete thisbook therebypreparing for theinterview.Itishighlyrecommendedthattheusershouldreadtheproblemstatementfirst,thenheshouldtrytosolvetheproblemsbyhimselfandthenonlyheshouldlookintothesolutiontofindtheapproachofthebookpracticingmoreandmoreproblemsopenourthinkingcapacityandyouwillbeabletohandlenew problems in an interview. System design is a topic that is not asked much from a fresher fromcollege, but as you gain experience its importance increase. We will recommend practicing all theproblems given in this book, then solve more and more problems from online resources likewww.topcoder.com,www.careercup.com,www.geekforgeek.cometc.

Page 22:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 23:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER1:INTRODUCTION-PROGRAMMINGOVERVIEW

Page 24:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionThis chapter emphasizes on the fundamentals ofCProgramming language. Itwill talk about variables,pointers,recursion,arraysetc.

Page 25:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Variable"Variables"aresimplystoragelocationstoholddata.Foreveryvariable,somememoryisallocated.Thesizeof thismemorydependsonthetypeof thevariable.Forexample,2bytesareallocatedfor integertype,4bytesareallocatedforfloattype,etc.Program1.11.#include<stdio.h>2.3.intmain()4.5.intvar1,var2,var3;6.var1=100;7.var2=200;8.var3=var1+var2;9.printf("Adding%dand%dwillgive%d",var1,var2,var3);10.return0;11.Analysis:Line5:Memory isallocated forvariablesvar1,var2andvar3.Wheneverwedeclareavariable, thenmemoryisallocatedforstoringthevalueinthevariable.Inourexample,2bytesareallocatedforeachofthevariable.Line6&7:Value100isstoredinvariablevar1andvalue200isstoredinvariablevar2.Line8:Valueofvar1andvar2isaddedandstoredinvar3.Line9:Finally,thevalueofvar1,var2andvar3isprintedtoscreen.

Page 26:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

PointersPointersarenothingmorethanvariablesthatstorememoryaddressesofanothervariableandcanbeusedtoaccess thevalue storedat thoseaddresses.Variousoperators suchas*,&,and [], enableus tousepointers.Address-Thenumericlocationofaplaceinmemory.Anaddressofamemoryisusedbythecomputertoidentifydatastoredinitquickly.Justasthepostaladdressofahouseisusedtoidentifyahousebythepostalworker.Dereference -Apointerstoresanaddressofa location in thememory.Toget thevaluestored in thataddress,weneed todereference thepointer,meaningweneed togo to that location andget thevaluestoredthere.Program1.21.intmain()2.3.intvar;4.int*ptr;5.var=10;6.ptr=&var;7.8.printf("Valuestoredatvariablevaris%d\n",var);9.printf("Valuestoredatvariablevaris%d\n",*ptr);10.11.printf("Theaddressofvariablevaris%p\n",&var);12.printf("Theaddressofvariablevaris%p\n",ptr);13.return0;14.Analysis:Line3:Anintegertypevariablevariscreated.Line4:Apointertointptriscreated.Line6:Addressofvarisstoredinptr.Line8&9:Valuestoredinvariablevarisprintedtoscreen.*Operatorisusedtogetthevaluestoredatthepointerlocation.Line11&12:Memoryaddressofvarisprintedtothescreen.&operatorisusedtogettheaddressofavariable.PointtoRemember:

1.Youcandefineapointerbyincludinga*beforethenameofthevariable.(Pointerdeclaration)2.Youcangetthevaluestoredataddressbyadding*beforethevariablename.(Pointeruse)3.Youcangettheaddressofavariablebyusing&operator.

Page 27:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ArrayAnarray is adata structureused to storemultipledataelementsof the samedata type.All thedata isstoredsequentially.Thevaluestoredatanyindexcanbeaccessedinconstanttime.Program1.31.intmain()2.3.intarr[10];4.for(inti=0;i<10;i++)5.6.arr[i]=i;7.8.printArray(arr,10);9.Analysis:Line3:Definesanarrayofintegers.Thearrayisofsize10-whichmeansthatitcanstore10integersinsideit.Line 6: Array elements are accessed using subscript operator []. Lowest subscript is 0 and highestsubscriptis(sizeofarray–1).Value0to9isstoredinthearrayatindex0to9.Line8:ArrayanditssizearepassedtoprintArray()function.Program1.41.voidprintArray(intarr[],intcount)2.3.printf("Valuesstoredinarrayare:");4.for(inti=0;i<count;i++)5.6.printf("[%d]",arr[i]);7.8.Analysis:Line1:ArrayvariablearranditsvariablecountarepassedasargumentstoprintArray()function.Line4-7:Finally,arrayvaluesareprintedtoscreenusingtheprintffunctioninaloop.PointtoRemember:1.Arrayindexalwaysstartsfrom0indexandhighestindexissize-1.2.Thesubscriptoperatorhashighestprecedenceifyouwritearr[2]++.Thenthevalueofarr[2]willbe

incremented.Eachelementofthearrayhasamemoryaddress.Thefollowingprogramwillprintthevaluestoredinanarrayandtheiraddress.

Page 28:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Program1.51.voidprintArrayAddress(intarr[],intcount)2.3.printf("Valuesstoredinarrayare:");4.for(inti=0;i<count;i++)5.6.printf("Data:[%d]hasAddress:[%p]\n",arr[i],arr+i);7.8.Analysis:Line 6: Value stored in an array is printed. The address of the various elements in the array is alsoprinted.PointtoRemember:Forarrayelements,consecutivememorylocationisallocated.Program1.61.voidprintArrayUsingPointer(intarr[],intcount)2.3.printf("Valuesstoredinarrayare:");4.int*ptr=arr;5.for(inti=0;i<count;i++)6.7.printf("Data:[%d]hasAddress:[%p]\n",*ptr,ptr);8.ptr++;9.10.Analysis:Line4:Apointertoanintiscreatedanditwillpointtothearray.Line7:valuestoredinpointerisprintedtoscree.Line8:Pointerisincremented.

Page 29:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TwoDimensionalArrayWecandefinetwodimensionalormultidimensionalarray.Itisanarrayofarray.Program1.71.intmain()2.3.intarr[4][2];4.intcount=0;5.for(inti=0;i<4;i++)6.for(intj=0;j<2;j++)7.arr[i][j]=count++;8.9.print2DArray((int**)arr,4,2);10.print2DArrayAddress((int**)arr,4,2);11.1.voidprint2DArray(int*arr[],introw,intcol)2.3.for(inti=0;i<row;i++)4.for(intj=0;j<col;j++)5.printf("[%d]",*(arr+i*col+j));6.7.1.voidprint2DArrayAddress(int*arr[],introw,intcol)2.3.for(inti=0;i<row;i++)4.for(intj=0;j<col;j++)5.printf("Value:%d,Address:%p\n",*(arr+i*col+j),(arr+i*col+j));6.Analysis:·Anarrayiscreatedwithdimension4x2.Thearraywillhave4rowsand2columns.·Valueisassignedtothearray·Finallythevaluestoredinarrayisprintedtoscreenandtheaddressusedtostorevaluesisprintedby

usingprint2DArray()andprint2DarrayAddress()function.Wecandefineapointerarraysimilartoanarrayofinteger.Thearrayelementwillstoreapointerinsideit.Program1.81.voidprintArray(int*arr[],intcount)2.3.int*ptr;4.for(inti=0;i<count;i++)

Page 30:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

5.6.ptr=arr[i];7.printf("[%d]",*ptr);8.9.1.voidprintArrayAddress(int*arr[],intcount)2.3.int*ptr;4.for(inti=0;i<count;i++)5.6.ptr=arr[i];7.printf("Valueis:%d,Addressis:%p\n",*ptr,ptr);8.9.1.intmain()2.3.intone=1,two=2,three=3;4.int*arr[3];5.arr[0]=&one;6.arr[1]=&two;7.arr[2]=&three;8.printArray(arr,3);9.printArrayAddress(arr,3);10.Analysis:·Threevariables,one,twoandthreearedefined.·Pointerarrayarrisdefied.·Theaddressofone,twoandthreeisstoredinsidearrayarr.·printArray()andprintArrayAddress()functionsareusedtoprintvaluestoredinthearray.

Page 31:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ArrayInterviewQuestionsThefollowingsectionwilldiscussthevariousalgorithmsthatareapplicabletoarraysandwillfollowbylistofpracticeproblemswithsimilarapproaches.

SumArrayProgram:Writeafunctionthatwillreturnthesumofalltheelementsoftheintegerarraygivenarrayanditssizeasanargument.Program1.9intSumArray(intarr[],intsize)

inttotal=0;intindex=0;for(index=0;index<size;index++)total=total+arr[index];returntotal;

SequentialSearchWriteafunctionwhichwillsearchinanarraythatsomevalueispresentinthearrayornot.Program1.10:intSequentialSearch(intarr[],intsize,intvalue)

inti=0;for(i=0;i<size;i++)if(value==arr[i])returni;return-1;

Analysis:·Sincewehavenoideaaboutthedatastoredinarrayorifthedataisnotsortedthenwehavetosearch

thearrayinsequentialmanneronebyone.·Ifwefindthevalue,wearelookingforwereturnthatindex.·Else,wereturn-1index,aswedidnotfoundthevaluewearelookingfor.In the above example, the data are not sorted. If the data is sorted, a binary searchmay be done.Weexamine themiddlepositionat each step.Dependingupon thedata thatweare searching isgreateror

Page 32:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

smallerthanthemiddlevalue.Wewillsearcheithertheleftortherightportionofthearray.Ateachstep,weareeliminatinghalfofthesearchspacetherebymakingthisalgorithmveryefficientthelinearsearch.

BinarySearchProgram1.11:Binarysearchinasortedarray./*BinarySearchAlgorithm–IterativeWay*/intBinarySearch(intarr[],intsize,intvalue)

intlow=0,mid;inthigh=size-1;while(low<=high)mid=low+(high-low)/2;/*Toavoidtheoverflow*/if(arr[mid]==value)returnmid;elseif(arr[mid]<value)low=mid+1;elsehigh=mid-1;return-1;

Analysis:·Sincewehavedatasortedinincreasing/decreasingorder,wecanapplymoreefficientbinarysearch.

Ateachstep,wereduceoursearchspacebyhalf.·Ateachstep,wecomparethemiddlevaluewiththevaluewearesearching.Ifmidvalueisequaltothe

valuewearesearchingforthenwereturnthemiddleindex.·Ifthevalueissmallerthanthemiddlevalue,wesearchthelefthalfofthearray.·Ifthevalueisgreaterthanthemiddlevaluethenwesearchtherighthalfofthearray.·Ifwefindthevaluewearelookingforthenitsindexisreturnedor-1isreturnedotherwise.

RotatinganArraybyKpositions.Forexample,anarray[10,20,30,40,50,60]rotateby2positionsto[30,40,50,60,10,20]Program1.12voidrotateArray(int*a,intn,intk)

reverseArray(a,k);reverseArray(&a[k],n-k);reverseArray(a,n);

Page 33:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

voidreverseArray(int*a,intn)

for(inti=0,j=n-1;i<j;i++,j--)a[i]^=a[j]^=a[i]^=a[j];

1,2,3,4,5,6,7,8,9,10=>5,6,7,8,9,10,1,2,3,41,2,3,4,5,6,7,8,9,10=>4,3,2,1,10,9,8,7,6,5=>5,6,7,8,9,10,1,2,3,4Analysis:·Rotatingarrayisdoneintwopartstrick.Inthefirstpart,wefirstreverseelementsofarrayfirsthalfand

thensecondhalf.·Thenwereversethewholearraytherebycompletingthewholerotation.

Findthelargestsumcontiguoussubarray.Givenanarrayofpositiveandnegativeintegers,findacontiguoussubarraywhosesum(sumofelements)ismaximized.

Program1.13intmaxSubArraySum(inta[],intsize)

intmaxSoFar=0,maxEndingHere=0;for(inti=0;i<size;i++)maxEndingHere=maxEndingHere+a[i];if(maxEndingHere<0)maxEndingHere=0;if(maxSoFar<maxEndingHere)maxSoFar=maxEndingHere;returnmaxSoFar;

Analysis:·Maximumsubarrayinanarrayisfoundinasinglescan.Wekeeptrackofglobalmaximumsumsofar

andthemaximumsum,whichincludethecurrentelement.·Whenwefindglobalmaximumvaluesofarislessthanthemaximumvaluecontainingcurrentvaluewe

updatetheglobalmaximumvalue.·Finallyreturntheglobalmaximumvalue.

Page 34:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

StructureStructuresareusedwhenwewanttoprocessdataofmultipledatatypesasasingleentity.Program1.14:DemonstratingStructure1.structcoord2.intx;3.inty;4.;5.intmain()6.7.structcoordpoint;8.point.x=10;9.point.y=10;10.printf("Xaxiscoordvalueis%d\n",point.x);11.printf("Yaxiscoordvalueis%d\n",point.y);12.printf("Sizeofstructureis%dbytes\n",sizeof(point));13.return0;14.Output:Xaxiscoordvalueis10Yaxiscoordvalueis10Sizeofstructureis8bytesAnalysis:Line1-4:Wehavedeclaredstructure"coord",whichcontaintwoelementsinsideit.Thetwoelementsxandycorrespondingtox-axisandy-axiscoordinates.Line8:Wehavedeclaredavariable"point"oftype"structcoord”.Line9-10:Wehaveassignedcoordinate(10,10),toxandyelementofthe"point".Variouselementsofastructureareassessedusingthedot(.)operator.Line11-12:Weareprinting thevalue stored in thex andy elements of thepoint that is of type structcoord.Line13:Weareprintingthesizeofstructpoint.Sincestructureconsistsofmorethanoneelement,thenthesizeofastructureisthesumofalltheelementsinsideit.

Page 35:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

PointertostructurePointerscanbeusedtoaccessthevariouselementsofastructure.Thevariouselementsofastructureareaccessedbypointerusing->operator.Program1.15:Pointertostructure1.#include<stdio.h>2.structstudent3.introllNo;4.char*firstName;5.char*lastName;6.;7.intmain()8.9.inti=0;10.structstudentstud;11.structstudent*ptrStud;12.ptrStud=&stud;13.ptrStud->rollNo=1;14.ptrStud->firstName="john";15.ptrStud->lastName="smith";16. printf("Roll No: %d Student Name: %s %s ", ptrStud->rollNo, ptrStud->firstName, ptrStud->lastName);17.18.return0;19.Analysis:Line2-6:Wehavedeclaredastructstudentthatcontainrollno,firstandlastnameofastudent.Line12:Wehavedeclaredapointertostructstudent.Line13-15:PointerptrStudispointingtostud.WehaveusedptrStudtoassignavaluetostructstud.Wehaveused->operatortoaccessthevariouselementsofthestructurepointedbyptrStud.Note: If we have used the stud to assignwewould have used "." operator. The same structurewhenaccessedusingpointerweuseindirectionoperator"->".Line16:Wehavefinallyprintedallthevariouselementsofstructurevariablestud.Note:Inthesamewayyoucanuse->operatortoaccesselementsoftheUnion.

Page 36:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DynamicMemoryAllocationIn c language, dynamic memory is allocated using the malloc(), calloc() and realloc() functions. Thedynamicmemoryrequiredtobefreedusingthefree()function.

MallocfunctionDefinitionofthemallocfunctionisasbelow.void*malloc(size_tsize);Itallocatesamemoryblockoflength"size"bytesandreturnapointertotheblock.ItwillreturnNULLifthesystemdoesnothaveenoughmemory.TheCstandarddefinesvoid*isagenericpointerthatisrequiredtobecastedtotherequiredtype.MostCcompilersneedthiscasting.However,thelatestANSICstandarddoesnotrequire.E.g.int*p=(int*)malloc(sizeof(int));

CallocfunctionDefinitionofcallocfunctionisasbelow.void*calloc(size_tnum,size_tsize);Itallocatesamemoryblockoflength"num*size"bytesandreturnapointertotheblock.ItwillreturnNULLifthesystemdoesnothaveenoughmemory.Onethingmoreitdoesthat,itinitializeseverybytetozero.

ReallocfunctionDefinitionofreallocfunctionisasbelow.void*realloc(void*ptr,size_tnewSize);Itisusedtochangethememoryblocksizeofapreviouslyallocatedblockofmemorypointedbyptr.ItreturnsamemoryblockofthenewSize.Iftheblocksizeifincreased,thenthecontentoftheoldmemoryblockiscopiedtoanewlyallocatedregion.Ifthepointerreturnedbythefunctionisdifferentfromtheoldpointerptr.Thenptrwillnolongerpointtoavalidlocation.Soingeneralyoushouldnotuseptronceitispassedtorealloc()function.IfptrisNULL,reallocworkssameasmalloc().Note:Again,youneed tocast the returnvalueofmalloc/calloc/reallocbeforeusing it. int*i= (int*)malloc(size);

FreeFunctionThememory that is allocatedusingmalloc/calloc/reallocneed tobe freedusing a free() function.The

Page 37:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

syntaxofthefree()functionisasbelow.voidfree(void*pointer);Apointer topreviously allocatedmemory ispassed to free() function.The free() functionwill put theallocatedmemoryblockbacktoheapsection.

Page 38:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

FunctionFunctionsareusedtoprovidemodularitytotheprogram.Byusingfunction,wecandividecomplextasksintosmallermanageabletasks.Theuseofthefunctionisalsotoavoidduplicatecode.Forexample,wecandefineafunctionsum()whichtaketwointegersandreturntheirsum.Thenwecanusethisfunctionmultipletimeswheneverwewantsumoftwointegers.Program1.16:DemonstratingFunctionCalls1.#include<stdio.h>2./*functiondeclaration*/3.intsum(intnum1,intnum2);4.intmain()5.6./*localvariabledefinition*/7.intx=10;8.inty=20;9.intresult;10./*callingafunctiontofindsum*/11.result=sum(x,y);12.printf("Sumis:%d\n",result);13.return0;14.15./*functionreturningthesumoftwonumbers*/16.intsum(intnum1,intnum2)17.18./*localvariabledeclaration*/19.intresult;20.result=num1+num2;21.returnresult;22.Output:Sumis:30Analysis:Line3:functiondeclarationofsum()functionLine11:sumfunctioniscalledfromthismainbypassingvariablexandywithvalue10and20atthispointcontrolflowwillgotoLine16.Line16:variablespassedtosumfunctionarecopiedintonum1andnum2localvariables.Line20&21: thesumiscalculatedandsaved inavariable result.And the result is returned.Controlflowcomesbacktolinenumber11.Line11-12:returnvalueofthesumfunctionissavedinalocalvariableresultandprintedtothescreen.

Page 39:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ConceptofStackAstackisamemoryinwhichvaluesarestoredandretrievedin“lastinfirstout”manner.Dataisaddedtostackusingpushoperationanddataistakenoutofstackusingpopoperation.

1.Initiallythestackwasempty.Thenwehaveaddedvalue1tostackusingpush(1)operator.2.Similarly,push(2)andpush(3)3.Popoperationtakethetopofthestack.Stackdataisaddedanddeletedin“lastin,firstout”manner.4.Firstpop()operationwilltake3outofthestack.5.Similarly,otherpopoperationwilltake2then1outofthestack6.Intheend,thestackisemptywhenalltheelementsaretakenoutofthestack.

Page 40:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

SystemstackandFunctionCallsWhenthefunctioniscalled,thecurrentexecutionisstoppedandthecontrolgoestothecalledfunction.Afterthecalledfunctionexits/returns,theexecutionresumesfromthepointatwhichtheexecutionwasstopped.Togettheexactpointatwhichexecutionshouldberesumed,theaddressofthenextinstructionisstoredinthestack.Whenthefunctioncallcompletetheaddressatthetopofthestackistakenout.Program1.171.voidfun2()2.3.printf("fun2line1\n");4.5.6.voidfun1()7.8.printf("fun1line1\n");9.fun2();10.printf("fun1line2\n");11.12.13.intmain()14.15.printf("mainline1\n");16.fun1();17.printf("mainline2\n");18.Output:mainline1fun1line1fun2line1fun1line2mainline2Analysis:Line13:Everyprogramstartswithmain()function.Line15:Thisisthefirststatementthatwillbeexecuted.Andwewillget“mainline1”asoutput.Line16:fun1()iscalled.Beforecontrolgoestofun1()thennextinstructionthatisaddressofline17isstoredinthesystemstack.Line6:Controlgoestofun1()function.Line8:Thisisthefirststatementinsidefun1(),thiswillprint“fun1line1”tooutput.Line9:fun2()iscalledfromfun1().Beforecontrolgoestofun2()addressofthenextinstructionthatisaddressofline10isaddedtothesystemstack.

Page 41:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Line1:Controlgoestofun2()function.Line3:“fun2line1”isprintedtoscreen.Line10:Whenfun2exits,controlcomeback to fun1.Moreover, theprogramreads thenext instructionfromthestack,andline10isexecuted.Andprint“fun1line2”toscreen.Line17:When fun1 exits, control comesback to themain function.Program reads thenext instructionfromthestack,linenumber17isexecuted,andfinally“mainline2”isprintedtoscreen.Pointstoremember:1.Functionsareimplementedusingastack.2.Whenafunctioniscalledtheaddressofthenextinstructionispushedintothestack.3.Whenafunctionisfinishedtheaddressoftheexecutionistakenoutofthestack.

Page 42:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Parameterpassing,CallbyvalueArgumentscanbepassedfromonefunctiontootherusingparameters.Bydefault,alltheparametersarepassedbyvalue.Thatmeansaseparatecopyiscreatedinsidethecalledfunctionandthevariableinthecallingfunctionremainsunchanged.Program1.181.voidincrement(intvar)2.3.var++;4.5.6.intmain()7.8.inti=10;9.printf("Valueofibeforeincrementis:%d\n",i);10.increment(i);11.printf("Valueofibeforeincrementis:%d\n",i);12.Output:Valueofibeforeincrementis:10Valueofibeforeincrementis:10Analysis:Line8:variable”i”isdeclaredandvalue10isinitializedtoit.Line9:valueif”i”isprinted.Line10:incrementfunctioniscalled.Whenafunctioniscalledthevalueoftheparameteriscopiedintoanothervariableofthecalledfunction.Flowofcontrolgoestolineno1.Line 3: value of var is incremented by 1. However, remember, it is just a copy inside the incrementfunction.Line11:Whenthefunctionexits,thevalueof”i”isstill10.Pointstoremember:1.Passbyvaluejustcreatesacopyofvariable.2.Passbyvalue,valuebeforeandafterthefunctioncallremainsame.

Page 43:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Parameterpassing,CallbyReferenceIfyouneedtochangethevalueoftheparameterinsidethefunction,thenyoushouldusecallbyreference.Clanguagebydefaultpassesbyvalue.Therefore,tomakeithappen,youneedtopasstheaddressofavariableandchangingthevalueofthevariableusingthisaddressinsidethecalledfunction.Program1.191.voidincrement(int*ptr)2.3.(*ptr)++;4.5.intmain()6.7.inti=10;8.printf("Valueofibeforeincrementis:%d\n",i);9.increment(&i);10.printf("Valueofibeforeincrementis:%d\n",i);11.Output:Valueofibeforeincrementis:10Valueofibeforeincrementis:11Analysis:Line9:Addressof“i” ispassed to thefunction increment.Function increment takesapointer to intasargument.Line3:Variableattheaddressptrisaccessedanditsvalueisincremented.Line10:Finally,incrementedvalueisprintedtoscreen.Pointstoremember:1.Callbyreferenceisimplementedindirectlybypassingtheaddressofavariabletothefunction.

Page 44:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

RecursiveFunctionArecursivefunctionisafunctionthatcallsitself,directlyorindirectly.A recursive function consists of two parts: TerminationCondition andBody (which include recursiveexpansion).1.TerminationCondition:A recursive function always contains oneormore terminating condition.A

conditioninwhichrecursivefunctionisprocessingasimplecaseanddonotcallitself.2.Body(includingrecursiveexpansion):Themainlogicoftherecursivefunctioncontainedinthebody

ofthefunction.Italsocontainstherecursionexpansionstatementthatinturncallsthefunctionitself.Threeimportantpropertiesofrecursivealgorithmare:1)Arecursivealgorithmmusthaveaterminationcondition.2)Arecursivealgorithmmustchangeitsstate,andmovetowardstheterminationcondition.3)Arecursivealgorithmmustcallitself.Note:Thespeedofarecursiveprogramisslowerbecauseofstackoverheads.If thesametaskcanbedoneusingan iterativesolution(loops), thenweshouldpreferan iterativesolution(loops) inplaceofrecursiontoavoidstackoverhead.Note:Withoutterminationcondition,therecursivefunctionmayrunforeverandwillfinallyconsumeallthestackmemory.

FactorialProgram1.20:FactorialCalculation.N!=N*(N-1)….2*1.1.intfactorial(unsignedinti)2.3./*TerminationCondition*/4.if(i<=1)5.return1;6./*Body,RecursiveExpansion*/7.returni*factorial(i-1);8.Analysis:Eachtimefunctionfniscallingfn-1.TimeComplexityisO(N)

PrintBase10IntegersProgram1.211.voidprintInt(unsignedintnumber)2.3.chardigit=number%10+'0';4.if(number/=10)

Page 45:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

5.printInt(number/10);6.printf("%c",digit);7.Analysis:Line3:Eachtimeremainderiscalculatedandstoreditscharequivalentindigit.Line4-5:ifthenumberisgreaterthan10thenthenumberdividedby10ispassedtoprintInt()function.Line6:Numberwillbeprintedwithhigherorderfirstthenthelowerorderdigits.TimeComplexityisO(N)

PrintBase16IntegersProgram1.22:Genericprinttosomespecificbasefunction.1.voidprintInt(unsignedintnumber,constintbase)2.3.char*conversion="0123456789ABCDEF";4.chardigit=number%base;5.if(number/=base)6.printInt(number,base);7.printf("%c",conversion[digit]);8.Analysis:Line1:basevalueisalsoprovidedalongwiththenumber.Line4:remainderofthenumberiscalculatedandstoredindigit.Line5-6:ifthenumberisgreaterthanbasethen,numberdividedbybaseispassedasanargumenttotheprintInt()functionrecursively.Line7:Numberwillbeprintedwithhigherorderfirstthenthelowerorderdigits.TimeComplexityisO(N)

IntegertoStringProgram1.231.char*intToStr(char*p,unsignedintnumber)2.3.chardigit=number%10+'0';4.if(number/=10)5.p=intToStr(p,number);6.*p++=digit;7.return(p);8.Analysis:Line1:characterbufferp ispassedasargumentandnumber ispassed,whichneed tobeconverted tostring.

Page 46:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Line3:leastsignificantdigitofthenumberisconvertedintocorrespondingcharacter.Line4-5: if thenumber isgreater than10 then,numberdividedby10 ispassedas anargument to theintToStr()functionrecursively.Line6:Thecharacterisstoredinthebufferphigherorderfirst,thenthelowerorderdigits.TimeComplexityisO(N)

TowerofHanoiTheTowerofHanoi(alsocalledtheTowerofBrahma)WearegiventhreerodsandNnumberofdisks,initiallyallthedisksareaddedtofirstrod(theleftmostone)indecreasingsizeorder.Theobjectiveistotransfertheentirestackofdisksfromfirsttowertothirdtower(therightmostone),movingonlyonediskatatimeandneveralargeroneontoasmaller.

Program1.241.voidtowerOfHanoi(intnum,charsrc,chardst,chartemp)2.3.if(num<1)4.return;5.6.towerOfHanoi(num-1,src,temp,dst);7.printf("\nMovedisk%dfrompeg%ctopeg%c",num,src,dst);8.towerOfHanoi(num-1,temp,dst,src);9.1.intmain()2.3.intnum=4;4.printf("ThesequenceofmovesinvolvedintheTowerofHanoiare:\n");5.towerOfHanoi(num,'A','C','B');6.return0;7.Analysis:TowerOfHanoiproblemifwewanttomoveNdisksfromsourcetodestination,thenwefirst

Page 47:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

moveN-1disksfromsourcetotemp,thenmovethelowestNthdiskfromsourcetodestination.ThenwillmoveN-1disksfromtemptodestination.

Greatestcommondivisor(GCD)Program1.251.intGCD(intm,intn)2.3.if(m<n)4.return(GCD(n,m));5.if(m%n==0)6.return(n);7.return(GCD(n,m%n));8.Analysis:Euclid’salgorithmisusedtofindgcd.GCD(n,m)==GCD(m,nmodm)

FibonaccinumberProgram1.261.intfibonacci(intn)2.3.if(n<=1)4.returnn;5.returnfibonacci(n-1)+fibonacci(n-2);6.Analysis:Fibonaccinumberarecalculatedbyaddingsumoftheprevioustwonumber.Thereisaninefficiencyinthesolutionwewilllookbettersolutionincomingchapters.

AllpermutationsofanintegerarrayProgram1.271.voidprintArray(intarr[],intcount)2.3.printf("Valuesstoredinarrayare:");4.for(inti=0;i<count;i++)5.6.printf("%d",arr[i]);7.8.printf("\n");9.10.voidswap(int*arr,intx,inty)11.inttemp=arr[x];12.arr[x]=arr[y];13.arr[y]=temp;14.return;

Page 48:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

15.16.voidpermutation(int*arr,inti,intlength)17.if(length==i)18.printArray(arr,length);19.return;20.21.intj=i;22.for(j=i;j<length;j++)23.swap(arr,i,j);24.permutation(arr,i+1,length);25.swap(arr,i,j);26.27.return;28.29.intmain()30.31.intarr[5];32.for(inti=0;i<5;i++)33.34.arr[i]=i;35.36.permutation(arr,0,5);37.Analysis:In permutation function at each recursive call number at index, “i” is swapped with all thenumbersthatarerightofit.Sincethenumberisswappedwithallthenumbersinitsrightonebyoneitwillproduceallthepermutationpossible.

BinarysearchusingrecursionProgram1.281./*BinarySearchAlgorithm–RecursiveWay*/2.intBinarySearchRecursive(intarr[],intlow,inthigh,intvalue)3.4.if(low>high)5.return-1;6.intmid=low+(high-low)/2;/*Toavoidtheoverflow*/7.if(arr[mid]==value)8.returnmid;9.elseif(arr[mid]<value)10.returnBinarySearchRecursive(arr,mid+1,high,value);11.else12.returnBinarySearchRecursive(arr,low,mid-1,value);13.

Page 49:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Analysis:Similar iterativesolutionwehadalreadyseen.Nowletus lookinto therecursivesolutionof thesameprobleminthissolutionalso,wearedivingthesearchspaceintohalfanddoingthesamewhatwehaddoneintheiterativesolution.

Page 50:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercises1.Findaverageofalltheelementsinanarray.2.Findthesumofalltheelementsofatwodimensionalarray.3.Findthelargestelementinthearray.4.Findthesmallestelementinthearray.5.Findthesecondlargestnumberinthearray.6.Printall themaxima’s inanarray. (Avalue isamaximumif thevaluebeforeandafter its indexare

smallerthanitisordoesnotexist.)Hint:a)Starttraversingarrayfromtheendandkeeptrackofthemaxelement.b)Ifweencounteranelement>max,printtheelementandupdatemax.

7.Printalternateelementsinanarray.8.Givenanarraywithvalue0or1,writeaprogramtosegregate0ontheleftsideand1ontherightside.9.Givenalistofintervals,mergealloverlappingintervals.

Input:[1,4],[3,6],[8,10]Output:[1,6],[8,10]

10.Writeafunctionthatwilltakeintervalsasinputandtakescareofoverlappingintervals.11.Reverse an array in-place. (You cannot use any additional array inotherwardsSpaceComplexity

shouldbeO(1).)Hint:Usetwovariable,startandend.Startsetto0andendsetto(n-1).Incrementstartanddecrementend.Swapthevaluesstoredatarr[start]andarr[end].Stopwhenstartisequaltoendorstartisgreaterthanend.

12.Givenanarrayof0sand1s.Weneedtosortitsothatallthe0sarebeforeallthe1s.Hint:Usetwovariable,startandend.Startsetto0andendsetto(n-1).Incrementstartanddecrementend.Swapthevaluesstoredatarr[start]andarr[end]onlywhenarr[start]==1andarr[end]==0.Stopwhenstartisequaltoendorstartisgreaterthanend.

13.Givenanarrayof0s,1sand2s.Weneedtosortitsothatallthe0sarebeforeallthe1sandallthe1s

arebefore2s.Hint:Sameasabovefirstthink0sand1sasonegroupandmoveallthe2sontherightside.Thendoasecondpassoverthearraytosort0sand1s.

14.Findtheduplicateelementsinanarrayofsizenwhereeachelementisintherange0ton-1.

Hint:Approach1:Compareeachelementwithalltheelementsofthearray(usingtwoloops)O(n2)solutionApproach2:MaintainaHash-Table.Setthehashvalueto1ifweencountertheelementforthefirsttime.Whenwesamevalueagainwecanseethatthehashvalueisalready1sowecanprintthatvalue.

Page 51:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

O(n)solution,butadditionalspaceisrequired.Approach3:Wewillexploittheconstraint"everyelementisintherange0ton-1".Wecantakeanarrayarr[]ofsizenandsetalltheelementsto0.Wheneverwegetavaluesayval1.Wewillincrementthevalueatarr[var1]indexby1.Intheend,wecantraversethearrayarrandprinttherepeatedvalues.AdditionalSpaceComplexitywillbeO(n)whichwillbeless thanHash-Tableapproach.

15.Findthemaximumelementinasortedandrotatedarray.Complexity:O(logn)

Hint:Usebinarysearchalgorithm.16.Givenanarraywith'n'elements&avalue'x',findtwoelementsinthearraythatsumsto'x'.

Hint:Approach1:Sortthearray.Approach2:UsingaHash-Table.

17.Write a function to find the sum of every number in an int number. Example: input= 1984, output

shouldbe32(1+9+8+4).18.WriteafunctiontocomputeSum(N)=1+2+3+…+N.

Page 52:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 53:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER2:ALGORITHMSANALYSIS

Page 54:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionComputer programmer learn by experience. We learn by seeing solved problems and solving newproblemsbyourselves.Studyingvariousproblem-solvingtechniquesandbyunderstandinghowdifferentalgorithmsaredesignedhelpsustosolvethenextproblemthatisgiventous.Byconsideringanumberofdifferentalgorithms,wecanbegintodeveloppatternsothatthenexttimeasimilarproblemarises,wearebetterabletosolveit.Whenanintervieweraskstodevelopaprograminaninterviewer,whatarethestepsthatanintervieweeshouldfollow.Wewillbetakingasystematicapproachtohandletheproblemandfinallyreachingtothesolution.

AlgorithmAnalgorithmisasetofstepstoaccomplishatask.Analgorithminacomputerprogramisasetofstepsappliedoverasetofinputtoproduceasetofoutput.Knowledgeofalgorithmhelpsustogetourdesiredresultfasterbyapplyingtherightalgorithm.Themostimportantpropertiesofanalgorithmare:1.Correctness:The algorithm should be correct. It should be able to process all the given inputs and

providecorrectoutput.2.Efficiency:Thealgorithmshouldbeefficientinsolvingproblems.Algorithmiccomplexityisdefinedashowfastaparticularalgorithmperforms.ComplexityisrepresentedbyfunctionT(n)-timeversustheinputsizen.

Page 55:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

AsymptoticanalysisAsymptoticanalysisisusedtocomparetheefficiencyofalgorithmindependentlyofanyparticulardatasetorprogramminglanguage.Wearegenerallyinterestedintheorderofgrowthofsomealgorithmandnotinterestedintheexacttimerequiredforrunninganalgorithm.ThistimeisalsocalledAsymptotic-runningtime.

Page 56:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Big-ONotationDefinition:“f(n)isbig-Oofg(n)”orf(n)=O(g(n)),iftherearetwo+veconstantscandn0suchthatf(n)≤cg(n)foralln≥n0,Inotherwords,cg(n)isanupperboundforf(n)foralln≥n0Thefunctionf(n)growthisslowerthancg(n)

Example:n2+n=O(n2)

Page 57:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Omega-ΩNotationDefinition:“f(n)isomegaofg(n).”orf(n)=Ω(g(n))iftherearetwo+veconstantscandn0suchthatcg(n)≤f(n)foralln≥n0Inotherwords,cg(n)islowerboundforf(n)Functionf(n)growthisfasterthancg(n)

Findrelationshipoff(n)=ncandg(n)=cnF(n)=Ω(g(n))

Page 58:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Theta-ΘNotationDefinition:“f(n)isthetaofg(n).”orf(n)=Θ(g(n))iftherearethree+veconstantsc1,c2andn0suchthatc1g(n)≤f(n)≤c2g(n)foralln≥n0g(n)isanasymptoticallytightboundonf(n).Functionf(n)growsatthesamerateasg(n).

Example:n3+n2+n=Ɵ(n2)Example:n2+n=Ɵ(n2)Findrelationshipoff(n)=2n2+nandg(n)=n2f(n)=O(g(n))f(n)=Ɵ(g(n))f(n)=Ω(g(n))Note:-AsymptoticAnalysisisnotperfect,butthatisthebestwayavailableforanalysingalgorithms.Forexample, say thereare twosortingalgorithms first take f(n)=10000nlognand f(n)=n2 time.Theasymptoticanalysissaysthatthefirstalgorithmisbetter(asitignoresconstants)butactuallyforasmallset of data when n is small then 10000, the second algorithm will perform better. To consider thisdrawbackofasymptoticanalysiscaseanalysisofthealgorithmisintroduced.

Page 59:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Complexityanalysisofalgorithms1)WorstCase complexity: It is the complexityof solving theproblem for theworst input of sizen. Itprovidestheupperboundforthealgorithm.Thisisthemostcommonanalysisdone.2)AverageCasecomplexity:Itisthecomplexityofsolvingtheproblemonanaverage.Wecalculatethetimeforallthepossibleinputsandthentakeanaverageofit.3)BestCasecomplexity:Itisthecomplexityofsolvingtheproblemforthebestinputofsizen.

Page 60:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TimeComplexityOrderAlistofcommonlyoccurringalgorithmTimeComplexityinincreasingorder:Name NotationConstant O(1)Logarithmic O(logn)Linear O(n)N-LogN O(n.logn)Quadratic O(n2)Polynomial O(nc)cisaconstant&c>1Exponential O(cn)cisaconstant&c>1FactorialorN-power-N O(n!)orO(nn)

ConstantTime:O(1)Analgorithmissaidtoruninconstanttimeregardlessoftheinputsize.Examples:1.Accessingnthelementofanarray2.Pushandpopofastack.3.EnqueueandDequeueofaqueue.4.AccessinganelementofHash-Table.5.Bucketsort

LinearTime:O(n)Analgorithmissaidtoruninlineartimeiftheexecutiontimeofthealgorithmisdirectlyproportionaltotheinputsize.Examples:1.Arrayoperationslikesearchelement,findmin,findmaxetc.2.Linkedlistoperationsliketraversal,findmin,findmaxetc.Note:whenweneedtosee/traverseallthenodesofadata-structureforsometaskthencomplexityisnolessthanO(n)

LogarithmicTime:O(logn)Analgorithmissaidtoruninlogarithmictimeiftheexecutiontimeofthealgorithmisproportionaltothelogarithm of the input size. Each step of an algorithm, a significant portion of the input is pruned outwithouttraversingit.Example:1.BinarysearchNote:Wewillreadaboutthesealgorithmsinthisbook.

N-LogNTime:O(nlog(n))Analgorithmissaidtoruninlogarithmictimeiftheexecutiontimeofanalgorithmisproportionaltothe

Page 61:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

productofinputsizeandlogarithmoftheinputsize.Example:1.Merge-Sort2.Quick-Sort(Averagecase)3.Heap-SortNote:Quicksortisaspecialkindofalgorithmtosortalistofnumbers.Itsworst-casecomplexityisO(n2)andaveragecasecomplexityisO(n.logn)

QuadraticTime:O(n2)Analgorithmissaidtoruninlogarithmictimeiftheexecutiontimeofanalgorithmisproportionaltothesquareoftheinputsize.Examples:1.Bubble-Sort2.Selection-Sort3.Insertion-Sort

Page 62:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DerivingtheRuntimeFunctionofanAlgorithm

Constants

Eachstatementtakesaconstanttimetorun.TimeComplexityisO(1)

Loops

The running time of a loop is a product of running time of the statement inside a loop and number ofiterationsintheloop.TimeComplexityisO(n)

NestedLoop

Therunningtimeofanestedloopisaproductofrunningtimeofthestatementsinsideloopmultipliedbyaproductofthesizeofalltheloops.TimeComplexityisO(nc)Wherecisanumberofloops.Fortwoloops,itwillbeO(n2)

Consecutive Statements

Justaddtherunningtimesofalltheconsecutivestatements

If-Else Statement

Considertherunningtimeofthelargerofifblockorelseblock.Moreover,ignoretheotherone.

Logarithmicstatement

Ifeachiterationtheinputsizeofdecreasesbyaconstantmultiplefactors.O(logn)

Page 63:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TimeComplexityExamplesExample1intfun(intn)

intm=0;for(inti=0;i<n;i++)m+=1;returnm;

TimeComplexity:O(n)Example2intfun(intn)

inti=0,j=0,m=0;for(i=0;i<n;i++)for(j=0;j<n;j++)m+=1;returnm;

TimeComplexity:O(n2)Example3intfun(intn)

inti=0,j=0,m=0;for(i=0;i<n;i++)for(j=0;j<i;j++)m+=1;returnm;

TimeComplexity:O(N+(N-1)+(N-2)+...)==O(N(N+1)/2)==O(n2)Example4intfun(intn)

inti=0,m=0;i=1;while(i<n)m+=1;i=i*2;

Page 64:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

returnm;

Eachtimeproblemspaceisdividedintohalf.TimeComplexity:O(log(n))Example5intfun(intn)

inti=0,m=0;i=n;while(i>0)m+=1;i=i/2;returnm;

Sameasaboveeachtimeproblemspaceisdividedintohalf.TimeComplexity:O(log(n))Example6intfun(intn)

inti=0,j=0,k=0,m=0;i=n;for(i=0;i<n;i++)for(j=0;j<n;j++)for(k=0;k<n;k++)m+=1;returnm;

Outerloopwillrunfornnumberofiterations.Ineachiterationoftheouterloop,innerloopwillrunforniterationsoftheirown.Finalcomplexitywillben*n*nTimeComplexity:O(n3)Example7intfun(intn)

inti=0,j=0,k=0,m=0;i=n;for(i=0;i<n;i++)for(j=0;j<n;j++)m+=1;

Page 65:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

for(i=0;i<n;i++)for(k=0;k<n;k++)m+=1;returnm;

These two groups of for loop are in consecutive so their complexity will add up to form the finalcomplexityoftheprogram.TimeComplexity:T(n)=O(n2)+O(n2)=O(n2)Example8intfun(intn)

inti=0,j=0,m=0;

for(i=0;i<n;i++)for(j=0;j<sqrt(n);j++)m+=1;returnm;

TimeComplexity:O(n*√n)=O(n3/2)Example9intfun(intn)

inti=0,j=0,m=0;

for(i=n;i>0;i/=2)for(j=0;j<i;j++)m+=1;returnm;

Eachtimeproblemspaceisdividedintohalf.TimeComplexity:O(log(n))Example10intfun(intn)

inti=0,j=0,m=0;

for(i=0;i<n;i++)for(j=i;j>0;j--)

Page 66:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

m+=1;returnm;

O(N+(N-1)+(N-2)+...)=O(N(N+1)/2)//arithmeticprogression.TimeComplexity:O(n2)Example11intfun(intn)

inti=0,j=0,k=0,m=0;

for(i=0;i<n;i++)for(j=i;j<n;j++)for(k=j+1;k<n;k++)m+=1;

returnm;

TimeComplexity:O(n3)Example12intfun(intn)

inti=0,j=0,m=0;

for(i=0;i<n;i++)for(;j<n;j++)m+=1;returnm;

Thinkcarefullyonceagainbeforefindingasolution,jvalueisnotresetateachiteration.TimeComplexity:O(n)Example13intfun(intn)

inti=1,j=0,m=0;

for(i=1;i<=n;i*=2)for(j=0;j<=i;j++)m+=1;

Page 67:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

returnm;Theinnerloopwillrunfor1,2,4,8,…ntimesinsuccessiveiterationoftheouterloop.TimeComplexity:T(n)=O(1+2+4+….+n/2+n)=O(n)

Page 68:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

MasterTheoremThemastertheoremsolvesrecurrencerelationsoftheform:T(n)=aT(n/b)+f(n)Wherea≥1andb>1."n"isthesizeoftheproblem."a"isanumberofsubproblemintherecursion.“n/b”isthesizeofeachsub-problem."f(n)"isthecostofthedivisionoftheproblemintosubproblemormergeofresultsofsubproblemstogettheresult.Itispossibletodetermineanasymptotictightboundinthesethreecases:Case1:when )andconstantЄ>1,thenthefinalTimeComplexitywillbe:

Case2:when )andconstantk≥0,thenthefinalTimeComplexitywillbe:

)Case3:when andconstantЄ>1,thenthefinalTimeComplexitywillbe:T(n)=Ɵ(f(n))

Example14:TakeanexampleofMerge-Sort,T(n)=2T(n/2)+nSol:-Logba=log22=1

)Case2appliesand )T(n)=Ɵ(nlog(n))Example15:BinarySearchT(n)=T(n/2)+O(1)Sol:-Logba=log21=0

)

Page 69:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Case2appliesand )T(n)=Ɵ(log(n))Example16:BinarytreetraversalT(n)=2T(n/2)+O(1)Sol:-Logba=log22=1F(n)=1= )Case1appliesandT(n)=Ɵ(n)Example17:TakeanexampleT(n)=T(n/2)+n2Sol:-Logba=log22=1f(n)=n2=Case3appliesandT(n)=Ɵ(f(n))T(n)=O(n2)Example18:TakeanexampleT(n)=4T(n/2)+n2Sol:-Logba=log24=2f(n)=n2= )Case2appliesandT(n)= )T(n)=Ɵ(n2logn)

Page 70:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ModifiedMastertheoremThisisashortcuttosolvingthesameproblemeasilyandfast.IftherecurrencerelationisintheformofT(n)=aT(n/b)+dxs

Example19:T(n)=2T(n/2)+n2Sol:-r=log22s=2Case3:log22<sT(n)=Ɵ(f(n))=Ɵ(n2)

Example20:T(n)=T(n/2)+2nSol:-r=log21=0s=1Case3T(n)=Ɵ(n)Example21:T(n)=16T(n/4)+nSol:-r=2s=1Case1T(n)=Ɵ(n2)Example22:T(n)=2T(n/2)+nlognSol:-Thereislogninf(n)sousemastertheoremshortcutwillnotword.T(n)=nlog(n)= )

)=Ɵ(nlog(n))Example23:T(n)=2T(n/4)+n0.5Sol:-r=log42=0.5=s

Page 71:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Case2:)=Ɵ(n0.5log1.5n)

Example24:T(n)=2T(n/4)+n0.49Sol:-Case1:

=Ɵ(n0.5)Example25:T(n)=3T(n/3)+√nSol:-r=log33=1s=½Case1T(n)=Ɵ(n)Example26:T(n)=3T(n/4)+nlognSol:-Thereislogninf(n)soseeifmastertheorem.f(n)=nlogn= )Case3:T(n)=Ɵ(nlog(n))Example27:T(n)=3T(n/3)+n/2Sol:-r=1=sCase2:T(n)=Ɵ(nlog(n))

Page 72:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise1.Trueorfalse

a)5n+10n2=O(n2)b)nlogn+4n=O(n)c)log(n2)+4log(logn)=O(logn)d)12n1/2+3=O(n2)e)3n+11n2+n20=O(2n)

2.Whatisthebest-caseruntimeComplexityofsearchinganarray?3.Whatistheaverage-caseruntimeComplexityofsearchinganarray?

Page 73:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 74:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER3:APPROACHTOSOLVEALGORITHMDESIGNPROBLEMS

Page 75:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionKnowthetheoreticalknowledgeofthealgorithmisessential,butitisnotsufficient.Youneedtohaveasystematicapproachtosolveaproblem.Ourapproachisfundamentallydifferenttosolveanyalgorithmdesign question.Wewill follow a systematic five-step approach to reach to our solution.Master thisapproachandyouwillbebetterthanmostofthecandidatesininterviews.Fivestepsforsolvingalgorithmdesignquestionsare:1.Constraints2.IdeasGeneration3.Complexities4.Coding5.Testing

Page 76:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ConstraintsSolving a technical question is not just about knowing the algorithms and designing a good softwaresystem.The interviewerwants to knowyou approach towards any given problem.Many peoplemakemistakes as they do not ask clarifying questions about a given problem.They assumemany things andbeginworkingwiththat.Thereisdata,whichismissingthatyouneedtocollectfromyourinterviewerbeforebeginningtosolveaproblem.Inthisstep,youwillcapturealltheconstraintsabouttheproblem.Weshouldnevertrytosolveaproblemthatisnotcompletelydefined.Interviewquestionsarenotlikeexampaperwhereallthedetailsaboutaproblem arewell defined. In the interview, the interviewer actually expects you to ask questions andclarifytheproblem.Forexample:Whentheproblemstatementsaysthatwriteanalgorithmtosortnumbers.Thefirstinformationyouneedtocaptureiswhatkingofdata.LetussupposeinterviewerrespondwiththeanswerInteger.Thesecondinformationthatyouneedtoknowwhatisthesizeofdata.Youralgorithmdiffersiftheinputdatasizeif100integersor1billionintegers.BasicguidelinefortheConstraintsforanarrayofnumbers:1.Howmanynumbersofelementsinthearray?2.Whatistherangeofvalueineachelement?Whatistheminandmaxvalue?3.Whatisthekindofdataineachelementisitanintegerorafloatingpoint?4.Doesthearraycontainuniquedataornot?BasicguidelinefortheConstraintsforanarrayofstring:1.Howmanynumbersofelementsinthearray?2.Whatisthelengthofeachstring?Whatistheminandmaxlength?3.Doesthearraycontainuniquedataornot?BasicguidelinefortheConstraintsforaGraph1.Howmanynodesarethereinthegraph?2.Howmanyedgesarethereinthegraph?3.Isitaweightedgraph?Whatistherangeofweights?4.Isthegraphdirectedorundirected?5.Isthereisaloopinthegraph?6.Istherenegativesumloopinthegraph?7.Doesthegraphhaveself-loops?We have already seen this in graph chapter that depending upon the constraints the algorithm appliedchangesandsoisthecomplexityofthesolution.

Page 77:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IdeaGenerationWehavecoveredalotoftheoreticalknowledgeinthisbook.Itisimpossibletocoverallthequestionsasnewonesarecreatedeveryday.Therefore,weshouldknowhowtohandlenewproblems.Evenifyouknowthesolutionofaproblemaskedbytheinterviewerthenalsoyouneedtohaveadiscussionwiththeinterviewerandreachtothesolution.Youneedtoanalysetheproblemalsobecausetheinterviewermaymodifyaquestionalittlebitandtheapproachtosolveitwillvary.Well,howtosolveanewproblem?Thesolutiontothisproblemisthatyouneedtodoalotofpracticeandthemoreyoupracticethemoreyouwillbeabletosolveanynewquestion,whichcomeinfrontofyou.Whenyouhavesolvedenoughproblems,youwillbeabletoseeapatterninthequestionsandabletosolvenewproblemseasily.Followingisthestrategythatyouneedtofollowtosolveanunknownproblem:1.Trytosimplifythetaskinhand.2.Tryafewexamples3.Thinkofasuitabledata-structure.4.Thinkaboutsimilarproblemsyouhavealreadysolved.

TrytosimplifythetaskinhandLetuslookintothefollowingproblem:Husbandsandtheirwivesarestandinginrandominaline.TheyhavebeennumberedforhusbandsH1,H2,H3and soon.And their correspondingwiveshavenumberW1,W2,W3and soon.Youneed toarrangethemsothatH1willstandfirst,followedbyW1,thenH2followedbyW2andsoon.Atthefirstlook,itlooksdifficult,butitisasimpleproblem.Trytofindarelationofthefinalposition.P(Hi)=i*2-1P(Wi)=i*2TherestofthealgorithmweareleavingyoutodosomethinglikeInsertion-Sortandyouaredone.

TryafewexamplesInthesameaboveproblemifyouhavetrieditwithsomeexamplefor3husbandandwifepairthenyoumayhavereached to thesameformula thatwehaveshownin theprevioussection.Sometimethinkingsomemoreexamplestrytosolvetheproblemathand.

Thinkofasuitabledata-structureForsomeproblems,itisstraightforwardwhichdatastructureismostsuitable.Forexample,ifwehaveaproblemfindingmin/maxofsomegivenvalue,thenprobablyheapisthedatastructurewearelookingfor.Wehaveseenanumberofdatastructurethroughoutthisbook.Inaddition,wehavetofigureoutwhichdata-structurewillsuiteourneed.Letuslookintoaproblem:Wearegivenastreamofdataatanytimewecanbeaskedtotellthemedianvalueofthedataandmaybewecanbeaskedtopopmediandata.

Page 78:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Wecanthinkaboutsomesortoftree,maybebalancedtreewheretherootisthemedian.Waitbutitisnotsoeasytomakesurethetreeroottobeamedian.Aheapcangiveusminimumormaximumsowecannotgetthedesiredresultfromittoo.However,whatifweuse twoheaponemaxheap andonemin heap.The smaller valueswill go tomin heap and thebiggervalueswillgotomaxheap.Inaddition,wecankeepthecountofhowmanyelementsarethereintheheap.Therestofthealgorithmyoucanthinkyourself.For every new problem think about the data structure, you know and may be one of them or somecombinationofthemwillsolveyourproblem.ThinkaboutsimilarproblemsyouhavealreadysolvedLetussupposeyouaregiventwolinkedlistheadpointerandtheymeetatsomepointandneedtofindthepointof intersection.However, inplaceoftheendofboththelinkedlist tobeanullpointer thereisaloop.Youknowhowtofindintersectionpointoftwointersectinglinkedlist,youknowhowtofindifalinkedlist have a loop (three-pointer solution). Therefore, you can apply both of these solutions to find thesolutionoftheprobleminhand.

Page 79:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ComplexitiesSolving a problem is not just finding a correct solution. The solution should be fast and should havereasonablememory requirement.Youhavealready readaboutBig-Onotation in thepreviouschapters.You shouldbe able todoBig-Oanalysis. In caseyou think the solutionyouhaveprovided is not thatoptimalandthereissomemoreefficientsolution,thenthinkagainandtrytofigureoutthisinformation.MostinterviewersexpectthatyoushouldbeabletofindthetimeandSpaceComplexityofthealgorithms.YoushouldbeabletocomputethetimeandSpaceComplexityinstantly.Wheneveryouaresolvingsomeproblem,youshouldfindthecomplexityassociatedwithitfromthisyouwouldbeabletochoosethebestsolutions.Insomeproblemsthereissometrade-offsbetweenspaceandTimeComplexity,soyoushouldknowthesetrade-offs.Sometimetakingsomebitmorespacesavesalotoftimeandmakeyouralgorithmmuchfaster.

Page 80:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CodingAt this point, you have already captured all the constraints of the problem, proposed few solutions,evaluatedthecomplexitiesofthevarioussolutionsandpickedtheonesolutiontodofinalcoding.Neverever,jumpintocodingbeforediscussingconstraints,Ideagenerationandcomplexitywiththeinterviewer.WeareaccustomedtocodinginanIDElikevisualstudio.Somanypeoplestrugglewhenaskedtowritecodeonawhiteboardorsomeblanksheet.Therefore,weshouldhavealittlepracticetothecodingonasheetofpaper.Youshouldthinkbeforecodingbecausethereisnobackbuttoninsheetofpaper.Alwaystrytowritemodularcode.Smallfunctionsneedtobecreatedsothatthecodeiscleanandmanaged.Ifthere is a swap function so just use this function and tell the interviewer that youwill write it later.Everybodyknowsthatyoucanwriteswapcode.

Page 81:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TestingOncethecodeiswritten,youarenotdone.Itismostimportantthatyoutestyourcodewithseveralsmalltest cases. It shows that you understand the importance of testing. It also gives confidence to yourinterviewerthatyouarenotgoingtowriteabuggycode.Onceyouaredonewith,yourcodingitisagoodpracticethatyougothroughyourcodelinebylinewithsomesmalltestcase.Thisisjusttomakesureyourcodeisworkingasitissupposedtowork.Youshouldtestfewtestcases.Normaltestcases:Thesearethepositivetestcases,whichcontainthemostcommonscenario,andfocusisontheworkingofthebaselogicofthecode.Forexample,ifwe`aregoingtowritesomealgorithmforlinkedlist,thenthismaycontainwhatwillhappenwhenalinkedlistwith3or4nodesisgivenasinput.Thesetestcasesyoushouldalwaysruninyourheadbeforesayingthecodeisdone.Edgecases:Theseare the testcases,whicharegoing to test theboundariesof thecode.For thesamelinkedlistalgorithm,edgecasesmaybehowthecodebehaveswhenanemptylistispassedorjustonenodeispassed.Thesetestcasesyoushouldalwaysruninyourheadbeforesayingthecodeisdone.Edgecasesmayhelptomakeyourcodemorerobust.Justfewchecksneedtobeaddedtothecodetotakecareofthecondition.Loadtesting:Inthiskindoftest,yourcodewillbetestedwithahugedata.Thiswillallowustotestifyourcodeisslowortoomuchmemoryintensive.Alwaysfollowthesefivestepsnever jumptocodingbeforedoingconstraintanalysis, ideageneration,andComplexityAnalysis:.Atleastnever,missthetestingphase.

Page 82:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ExampleLetussupposetheintervieweraskyoutogiveabestsortingalgorithm.Some interviewee will directly jump to Quick-SortO(nlogn). Oops, mistake you need to ask manyquestionsbeforebeginningtosolvethisproblem.Questions1:Whatisthetypeofdata?Aretheyintegers?Answer:Yes,theyareintegers.Questions2:Howmuchdataarewegoingtosort?Answer:Maybethousands.Questions3:Whatexactlyisthisdataabout?Answer:Theystoreaperson’sageQuestions4:Whatkindofdata-structureusedtoholdthisdata?Answer:DataaregivenintheformofsomearrayQuestions5:Canwemodifythegivendata-structure?Inaddition,many,manymore…?Answer:No,youcannotmodifythedatastructureprovidedOkfromthefirstanswer,wewilldeducethatthedataisinteger.Thedataisnotsobigitjustcontainsafewthousandentries.Thethirdanswerisinterestingfromthiswededucethattherangeofdatais1-150.Dataisprovidedinanarray.Fromfifthsanswerwededucethatwehavetocreateourowndatastructureandwecannotmodifythearrayprovided.Sofinally,weconclude,wecanjustusebucketsorttosortthedata.Therangeisjust1-150soweneedjust151-capacityintegralarray.DataisunderthousandssowedonothavetoworryaboutdataoverflowandwegetthesolutioninlineartimeO(N).Note:Wewillreadsortinginthecomingchapters.

Page 83:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

SummaryAtthispoint,youknowtheprocessofhandlingnewproblemsverywell.Inthecomingchapterwewillbelookingintoalotofvariousdatastructureandtheproblemstheysolve.Ahugenumberofproblemsaresolved in thisbook.However, is recommendedso first try tosolve thembyyourself, then lookfor thesolution.Alwaysthinkaboutthecomplexityoftheproblem.Intheinterviewinteractionisthekeytogetproblemdescribedcompletelyanddiscussyourapproachwiththeinterviewer.

Page 84:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 85:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER4:ABSTRACTDATATYPE

Page 86:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Abstractdatatype(ADT)Anabstractdatatype(ADT)isalogicaldescriptionofhowweviewthedataandtheoperationsthatareallowedonit.ADTisdefinedasauserpointofviewofadatatype.ADTconcernsaboutthepossiblevaluesofthedataandwhatareinterfaceexposedbyit.ADTdoesnotconcernabouttheactualimplementationofthedatastructure.Forexample,auserwantstostoresomeintegersandfindameanofit.Doesnottalkabouthowexactlyitwillbeimplemented.

Page 87:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Data-StructureDatastructuresareconcreterepresentationsofdataandaredefinedasaprogrammerpointofview.Data-structurerepresentshowdatawillbestoredinmemory.Alldata-structureshavetheirownprosandcons.Dependingupontheproblemathand,wepickadata-structurethatisbestsuitedforit.Forexample,wecanstoredatainanarray,alinked-list,stack,queue,tree,etc.

Page 88:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Array

Array represent a collection of multiple elements of the same datatype. Arrays are fixed size datastructure,thesizeofthisdatastructuremustbeknownatcompiletimeandcannotbechangedafterthat.Arraysarethemostcommondatastructureusedtostoredata.Aswecannotchangethesizeofanarray,wegenerallydeclarelargesizearraytohandleanyfuturedataexpansion.Thisendsupincreatinglargesizearray,wheremostofthespaceisunused.

ArrayADTOperationsBelowistheAPIofarray:Insert(x,k):addsanelementatkthpositionIfwewant to just store value k at index x, andwedo not care about the value already stored in thatlocationthanthisoperationisdoneinO(1)constanttime.However, if we care about the previous values stored in an array, so insertions and deletions of anelementistimeconsumingaswehavetoshiftotherelementsbyonepositionrespectively.Inthiscase,insertionanddeletiontakeO(n)time.Delete(k):deleteelementatkthpositionIfwewanttomarkthatthereisnovaluestoredatindexk,thisoperationisdoneinO(1)constanttime.However, if we care about the other values stored in an array, so deletions of an element are timeconsumingaswehave to shift other elementsbyoneposition respectively. In this case,deletion takesO(n)time.FindKth(k):findelementatpositionkThebiggestadvantageofthearrayisthatifweknowindexofanelementthenitcanbeaccessedinO(1)TimeComplexity.WejustneedtoreturnA[k].Find(x):findpositionofelementIfthearrayisunsorted,thenfind(x)anelementwilltakeO(n)TimeComplexity.Ifthearrayissorted,thenfind(x)isfastusingbinarysearchandwilltakeO(logn)TimeComplexity.PrintList():displayalltheelementsinthelistPrintListJustrunthroughthearrayandprintoneelementatatime.Usesoneloop.LineartimeO(n).IsEmpty():checkifnumberofelementsarezeroSearchingifthereisnoelementstoredinarrayalsotakelineartimeO(n).

Page 89:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

LinkedList

Linkedlistsaredynamicdatastructureandmemoryisallocatedatruntime.Theconceptoflinkedlistisnottostoredatacontiguously.Uselinksthatpointtothenextelements.Performance wise linked lists are slower than arrays because there is no direct access to linked listelements.Thelinkedlistisausefuldatastructurewhenwedonotknowthenumberofelementstobestoredaheadoftime.Therearemanyflavoursoflinkedlist:linear,circular,doubly,anddoublycircular.

LinkedListADTOperationsBelowistheAPIofLinkedlist.Insert(k):addsktothestartofthelistInsertanelementat thestartof the list. Justcreateanewelementandmovepointers.So that thisnewelementbecomesthenewelementofthelist.ThisoperationwilltakeO(1)constanttime.Delete():deleteelementatthestartofthelistDeleteanelementatthestartofthelist.Wejustneedtomoveonepointer.ThisoperationwillalsotakeO(1)constanttime.PrintList():displayalltheelementsofthelist.Startwiththefirstelementandthenfollowthepointers.ThisoperationwilltakeO(N)time.Find(k):findthepositionofelementwithvaluekStartwiththefirstelementandfollowthepointeruntilwegetthevaluewearelookingfororreachtheendofthelist.ThisoperationwilltakeO(N)time.Note:binarysearchdoesnotworkonlinkedlists.FindKth(k):findelementatpositionkStartfromthefirstelementandfollowthelinksuntilyoureachthekthelement.ThisoperationwilltakeO(N)time.IsEmpty():checkifthenumberofelementsinthelistarezero.JustchecktheheadpointerofthelistitshouldbeNull.Whichmeanslistisempty.ThisoperationwilltakeO(1)time.

Page 90:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Stack

StackisaspecialkindofdatastructurethatfollowsLast-In-First-Out(LIFO)strategy.Thismeansthattheelementthatisaddedtostacklastwillbethefirsttoberemoved.Thevariousapplicationsofstackare:1.Recursion:recursivecallsarepreformedusingsystemstack.2.Postfixevaluationofexpression.3.Backtracking4.Depth-firstsearchoftreesandgraphs.5.Convertingadecimalnumberintoabinarynumberetc.

StackADTOperationsPush(k):AddsanewitemtothetopofthestackPop():Removeanelementfromthetopofthestackandreturnitsvalue.Top():ReturnsthevalueoftheelementatthetopofthestackSize():ReturnsthenumberofelementsinthestackIsEmpty():determineswhetherthestackisempty.Itreturns1ifthestackisemptyorreturn0.Note:AlltheaboveStackoperationsareimplementedinO(1)TimeComplexity.

Page 91:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Queue

AqueueisaFirst-In-First-Out(FIFO)kindofdatastructure.Theelementthatisaddedtothequeuefirstwillbethefirsttoberemovedfromthequeueandsoon.Queuehasthefollowingapplicationuses:1.Accesstosharedresources(e.g.,printer)2.Multiprogramming3.Messagequeue

QueueADTOperations:Enqueue():Addanewelementtothebackofthequeue.Dequeue():removeanelementfromthefrontofthequeueandreturnitsvalue.Front():returnthevalueoftheelementatthefrontofthequeue.Size():returnsthenumberofelementsinsidethequeue.IsEmpty():returns1ifthequeueisemptyotherwisereturn0Note:AlltheaboveQueueoperationsareimplementedinO(1)TimeComplexity.

Page 92:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TreesTreeisahierarchicaldatastructure.Thetopelementofa treeiscalledtherootof thetree.Except therootelement,everyelementinatreehasaparentelement,andzeroormorechildelements.Thetreeisthemostusefuldatastructurewhenyouhavehierarchicalinformationtostore.Therearemanytypesoftrees,forexample,binary-tree,Red-blacktree,AVLtree,etc.

Page 93:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BinaryTreeAbinarytreeisatypeoftreeinwhicheachnodehasatmosttwochildren(0,1or2)whicharereferredasleftchildandrightchild.

Page 94:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BinarySearchTrees(BST)

Abinarysearchtree(BST)isabinarytreeonwhichnodesareorderedinthefollowingway:1.Thekeyintheleftsubtreeislessthanthekeyinitsparentnode.2.Thekeyintherightsubtreeisgreaterorequalthekeyinitsparentnode.

BinarySearchTreeADTOperationsInsert(k):Insertanelementkintothetree.Delete(k):Deleteanelementkfromthetree.Search(k):Searchaparticularvaluekintothetreeifitispresentornot.FindMax():Findthemaximumvaluestoredinthetree.FindMin():Findtheminimumvaluestoredinthetree.TheaverageTimeComplexityofall theaboveoperationsonabinarysearchtree isO(logn), thecasewhenthetreeisbalanced.Theworst-caseTimeComplexitywillbeO(n)whenthetreeisskewed.Abinarytreeisskewedwhentreeisnotbalanced.Therearetwotypesofskewedtree.1.RightSkewedbinarytree:Abinarytreeinwhicheachnodeishavingeitheronlyarightchildorno

childatall.2.LeftSkewedbinarytree:Abinarytreeinwhicheachnodeishavingeitheronlyaleftchildornochild

atall.

BalancedBinarysearchtreeTherearefewbinarysearchtree,whichalwayskeepsthemselvesbalanced.MostimportantamongthemareRed-BlackTree(RB-Tree)andAVLtree.Thestandardtemplatelibrary(STL)isimplementedusingthisRed-BlackTree(RB-Tree).

Page 95:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

PriorityQueue(Heap)

Priorityqueueisimplementedusingabinaryheapdatastructure.Inaheap,therecordsarestoredinanarraysothateachkeyislargerthanitstwochildrenkeys.Eachnodeintheheapfollowthesamerulethattheparentvalueisgreaterthanitschildren.Therearetwotypesoftheheapdatastructure:1.Maxheap:eachnodeshouldbegreaterthanorequaltoeachofitschildren.2.Minheap:eachnodeshouldbesmallerthanorequaltoeachofitschildren.Aheapisausefuldatastructurewhenyouwanttogetmax/minonebyonefromdata.Heap-Sortusesmaxheaptosortdatainincreasing/decreasingorder.

HeapADTOperationsInsert()-Addinganewelementtotheheap.TheTimeComplexityofthisoperationisO(log(n))Extract()-Extractingmaxformaxheapcase(orminforminheapcase).TheTimeComplexityofthisoperationisO(log(n))Heapify()–Toconvertalistofnumbersinanarrayintoaheap.ThisoperationhasaTimeComplexityO(n)Delete()–Deleteanelementfromtheheap.TheTimeComplexityofthisoperationisO(log(n))

Page 96:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Hash-Table

AHash-Table isadatastructure thatmapskeys tovalues.Eachpositionof theHash-Table iscalledaslot.TheHash-Tableusesahash function tocalculatean indexofanarrayof slots.Weuse theHash-Tablewhenthenumberofkeysactuallystoredissmallrelativelytothenumberofpossiblekeys.Theprocessofstoringobjectsusingahashfunctionisasfollows:1.CreateanarrayofsizeMtostoreobjects,thisarrayiscalledHash-Table.2.Findahashcodeofanobjectbypassingitthroughthehashfunction.3.TakemoduleofhashcodebythesizeofHash-Tabletogettheindexofthetablewhereobjectswillbestored.4.Finallystoretheseobjectsinthedesignatedindex.TheprocessofsearchingobjectsinHash-Tableusingahashfunctionisasfollows:1.Findahashcodeoftheobjectwearesearchingforbypassingitthroughthehashfunction.2.Takemoduleofhashcodeby thesizeofHash-Table toget the indexof the tablewhereobjectsarestored.3.Finally,retrievetheobjectfromthedesignatedindex.

Hash-TableAbstractDataType(ADT)ADTofHash-Tablecontainsthefollowingfunctions:Insert(x):Addobjectxtothedataset.Delete(x):Deleteobjectxfromthedataset.Search(x):Searchobjectxindataset.TheHash-Tableisausefuldatastructureforimplementingdictionary.TheaveragetimetosearchforanelementinaHash-TableisO(1).AHashTablegeneralizesthenotionofanarray.

Page 97:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Dictionary/SymbolTableAsymboltableisamappingbetweenastring(key)andavalue,whichcanbeofanydatatype.Avaluecanbeanintegersuchasoccurrencecount,dictionarymeaningofawordandsoon.

BinarySearchTree(BST)forStringsBinarySearchTree(BST)isthesimplestwaytoimplementsymboltable.Simplestringcomparefunctioncan be used to compare two strings. If all the keys are random, and the tree is balanced. Then on anaveragekeylookupcanbedoneinlogarithmictime.

Hash-TableTheHash-Table is another data structure,which can be used for symbol table implementation.BelowHash-Tablediagram,wecanseethenameofthatpersonistakenasthekey,andtheirmeaningisthevalueofthesearch.Thefirstkeyisconvertedintoahashcodebypassingittoappropriatehashfunction.InsidehashfunctionthesizeofHash-Tableisalsopassed,whichisusedtofindtheactualindexwherevalueswillbestored.Finally,thevaluethatismeaningofnameisstoredintheHash-Table,oryoucanstoreareferencetothestringwhichstoremeaningcanbestoredintotheHash-Table.

Page 98:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Hash-Tablehasanexcellentlookupofconstanttime.Let us supposewewant to implement autocomplete the box feature ofGoogle search.When you typesomestringtosearchingooglesearch,itproposesomecompletestringevenbeforeyouhavedonetyping.BSTcannotsolvethisproblemasrelatedstringscanbeinbothrightandleftsubtree.TheHash-Tableisalsonotsuitedfor this job.OnecannotperformapartialmatchorrangequeryonaHash-Table.Hash function transforms string to a number.Moreover, a good hash functionwill give adistributedhashcodeevenforpartialstringandthereisnowaytorelatetwostringsinaHash-Table.Trie and Ternary Search tree are a special kind of tree, which solves partialmatch, and range queryproblemwell.

TrieTrieisatree,inwhichwestoreonlyonecharacterateachnode.Thisfinalkeyvaluepairisstoredintheleaves.EachnodehasKchildren,oneforeachpossiblecharacter.Forsimplicitypurpose,letusconsiderthatthecharactersetis26,correspondstodifferentcharactersofEnglishalphabets.Trie is an efficient data structure. Using Trie, we can search the key in O(M) time.WhereM is themaximumstringlength.Trieisalsosuitableforsolvingpartialmatchandrangequeryproblems.

TernarySearchTrie/TernarySearchTreeTrieshavingaverygoodsearchperformanceofO(M)whereMisthemaximumsizeofthesearchstring.However,trieshavingveryhighspacerequirement.EverynodeTriecontainreferencestomultiplenodes,each reference corresponds to possible characters of the key. To avoid this high space requirementTernarySearchTrie(TST)isused.

Page 99:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

A TST avoid the heavy space requirement of the traditional Trie while still keeping many of itsadvantages. In aTST, eachnode contains a character, an endofkey indicator, and threepointers.Thethree pointers are corresponding to current char hold by the node(equal), characters less than andcharactergreaterthan.TheTimeComplexityofternarysearchtreeoperationisproportionaltotheheightoftheternarysearchtree.Intheworstcase,weneedtotraverseupto3timesthatmanylinks.However,thiscaseisrare.Therefore,TSTisaverygoodsolutionforimplementingSymbolTable,Partialmatchandrangequery.

Page 100:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Graphs

Agraphisadatastructurewhichrepresentsanetwork,thatconnectsacollectionofnodescalledvertices,andthereconnections,callededges.Anedgecanbeseenasapathbetweentwonodes.Theseedgescanbeeitherdirectedorundirected.Ifapathisdirectedthenyoucanmoveonlyinonedirection,whileinanundirectedpathyoucanmoveinboththedirections.

Page 101:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

GraphAlgorithms

Depth-FirstSearch(DFS)TheDFSalgorithmwestartfromstartingpointandgointodepthofgraphuntilwereachadeadendandthenmoveup toparentnode(Backtrack). InDFS,weusestack toget thenextvertex tostartasearch.Alternatively,wecanuserecursion(systemstack)todothesame.

Page 102:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Breadth-FirstSearch(BFS)InBFS algorithm, a graph is traversed in layer-by-layer fashion. The graph is traversed closer to thestartingpoint.ThequeueisusedtoimplementBFS.

Page 103:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

SortingAlgorithms

Sortingistheprocessofplacingelementsfromacollectionintoascendingordescendingorder.Sortingarrangesdataelementsinordersothatsearchingbecomeeasier.TherearegoodsortingfunctionsavailablewhichdoessortinginO(nlogn)time,sointhisbookwhenweneedsortingwewillusesort()functionandwillassumethatthesortingisdoneinO(nlogn)time.

Page 104:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CountingSortCountingsortisthesimplestandmostefficienttypeofsorting.Countingsorthasastrictrequirementofapredefinedrangeofdata.Like,sorthowmanypeopleareinwhichagegroup.Weknowthattheageofpeoplecanvarybetween1and130.

Ifweknowtherangeofinput,thensortingcanbedoneusingcountinginO(n+k).

Page 105:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

EndnoteThis chapter have provided a brief introduction of the various data structures, algorithms and theircomplexities.Inthecomingchapterswewilllookintoallthesedatastructureindetails.Ifyouknowtheinterface of the various data structures, then you can use them while solving other problems withoutknowingtheinternaldetailshowtheyareimplemented.

Page 106:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 107:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER5:SEARCHING

Page 108:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionInComputerScience,Searchingisthealgorithmicprocessoffindingaparticulariteminacollectionofitems.Theitemmaybeakeywordinafile,arecordinadatabase,anodeinatreeoravalueinanarrayetc.

Page 109:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

WhySearching?Imagineyouareinalibrarywithmillionsofbooks.Youwanttogetaspecificbookwithspecifictitle.Howwill you find?Youwill just start searching by initial letter of the book title. Then you continuematchingwithawholebooktitleuntilyoufindyourdesiredbook.(Bydoingthissmallheuristicyouhavereducedthesearchspacebyafactorof26,considerwehaveanequalnumberofbookswhosetitlebeginwithparticularchar.)Similarly,computerstores lotsof informationand to retrieve this informationefficiently,weneedveryefficientsearchingalgorithms.Tomakesearchingefficient,wekeepthedatainsomeproperorder.Therearecertainwaysoforganizingthedata.Ifyoukeepthedatainproperorder,itiseasytosearchrequiredelement.Forexample,Sortingisoneoftheprocessformakingdataorganized.

Page 110:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DifferentSearchingAlgorithms·LinearSearch–UnsortedInput·LinearSearch–SortedInput·BinarySearch(SortedInput)·StringSearch:Tries,SuffixTrees,TernarySearch.·HashingandSymbolTables

Page 111:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

LinearSearch–UnsortedInputWhenelementsofanarrayarenotorderedorsortedandwewant tosearchforaparticularvalue,weneedtoscanthefullarrayunlesswefindthedesiredvalue.Thiskindofalgorithmknownasunorderedlinear search.Themajor problemwith this algorithm is less performance or highTimeComplexity inworstcase.Example5.1intlinearSearchUnsorted(intarr[],intsize,intvalue)

inti=0;for(i=0;i<size;i++)if(value==arr[i])returni;return-1;

TimeComplexity:O(n).Asweneedtotraversethecompletearrayinworstcase.Worstcaseiswhenyourdesiredelementisatthelastpositionofthearray.Here,‘n’isthesizeofthearray.SpaceComplexity:O(1).Noextramemoryisusedtoallocatethearray.

Page 112:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

LinearSearch–SortedIf elements of the array are sorted either in increasing order or in decreasing order, searching for adesiredelementwillbemuchmoreefficientthanunorderedlinearsearch.Inmanycases,wedonotneedtotraversethecompletearray.Followingexampleexplainswhenyouencounteragreaterelementfromthe increasing sorted array, you stop searching further. This is how this algorithm saves the time andimprovestheperformance.Example5.2intlinearSearchSorted(intarr[],intsize,intvalue)

inti=0;for(i=0;i<size;i++)if(value==arr[i])returni;elseif(value<arr[i])return-1;return-1;

TimeComplexity:O(n).Asweneedtotraversethecompletearrayinworstcase.Worstcaseiswhenyour desired element is at the last position of the sorted array. However, in the average case thisalgorithmismoreefficienteventhoughthegrowthrateissameasunsorted.SpaceComplexity:O(1).Noextramemoryisusedtoallocatethearray.

Page 113:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BinarySearchHowdowesearchawordinadictionary?Ingeneral,wegotosomeapproximatepage(mostlymiddle)andstartsearchingfromthatpoint. Ifweseethewordthatwearesearchingissamethenwearedonewiththesearch.Else,ifweseethepageisbeforetheselectedpages,thenapplythesameprocedureforthefirsthalfotherwisetothesecondhalf.BinarySearchalsoworksinthesameway.Wegetthemiddlepointfromthesortedarrayandstartcomparingwiththedesiredvalue.Note:Binarysearchrequiresthearraytobesortedotherwisebinarysearchcannotbeapplied.Example5.3/*BinarySearchAlgorithm–IterativeWay*/intBinarysearch(intarr[],intsize,intvalue)

intlow=0;inthigh=size-1;intmid;while(low<=high)mid=low+(high-low)/2;/*Toavoidtheoverflow*/if(arr[mid]==value)returnmid;elseif(arr[mid]<value)low=mid+1;elsehigh=mid-1;return-1;

TimeComplexity:O(logn).Wealwaystakehalfinputandthrowingouttheotherhalf.SotherecurrencerelationforbinarysearchisT(n)=T(n/2)+c.Usingmastertheorem(divideandconquer),wegetT(n)=O(logn)SpaceComplexity:O(1)Example5.4/*BinarySearchAlgorithm–RecursiveWay*/intBinarySearchRecursive(intarr[],intlow,inthigh,intvalue)

if(low>high)return-1;intmid=low+(high-low)/2;/*Toavoidtheoverflow*/if(arr[mid]==value)returnmid;elseif(arr[mid]<value)

Page 114:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

returnBinarySearchRecursive(arr,mid+1,high,value);elsereturnBinarySearchRecursive(arr,low,mid-1,value);

TimeComplexity:O(logn).SpaceComplexity:O(logn)forsystemstackinrecursion

Page 115:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

StringSearchingAlgorithmsReferStringchapter.

Page 116:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

HashingandSymbolTablesReferHash-Tablechapter.

Page 117:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

HowsortingisusefulinSelectionAlgorithm?Selectionproblemscanbeconvertedtosortingproblems.Oncethearrayissorted,itiseasytofindtheminimum/maximum(ordesiredelement)fromthesortedarray.Themethod‘SortingandthenSelecting’isinefficientforselectingasingleelement,butitisefficientwhenmanyselectionsneedtobemadefromthearray. It is because only one initial expensive sort is needed, followed by many cheap selectionoperations.Forexample,ifwewanttogetthemaximumelementfromanarray.Aftersortingthearray,wecansimplyreturnthelastelementfromthearray.Whatifwewanttogetsecondmaximum.Now,wedonothavetosort thearrayagainandwecanreturn thesecondlastelementfromthesortedarray.Similarly,wecanreturnthekthmaximumelementbyjustonescanofthesortedlist.Sowiththeabovediscussion,sortingisusedtoimprovetheperformance.IngeneralthismethodrequiresO(nlogn)(forsorting)time.Withtheinitialsorting,wecanansweranyqueryinonescan,O(n).

Page 118:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinSearching

PrintDuplicatesinArrayGivenanarrayofnnumbers,printtheduplicateelementsinthearray.Firstapproach:Exhaustive searchorBrute force, for eachelement in array find if there is someotherelementwiththesamevalue.Thisisdoneusingtwoforloop,firstlooptoselecttheelementandsecondlooptofinditsduplicateentry.Example5.5voidprintRepeating(intarr[],intsize)

inti,j;printf("Repeatingelementsare");for(i=0;i<size;i++)for(j=i+1;j<size;j++)if(arr[i]==arr[j])printf("%d",arr[i]);

TheTimeComplexityisO(n2)andSpaceComplexityisO(1)Secondapproach:Sorting,Sortalltheelementsinthearrayandafterthisinasinglescan,wecanfindtheduplicates.Example5.6voidprintRepeating(intarr[],intsize)

inti;Sort(arr,size);printf("Repeatingelementsare");for(i=1;i<size;i++)if(arr[i]==arr[i-1])printf("%d",arr[i]);

SortingalgorithmstakeO(n.log(n))timeandsinglescantakeO(n)time.TheTimeComplexityofanalgorithmisO(n.log(n)) andSpaceComplexityisO(1)Thirdapproach:Hash-Table,usingHash-Table,wecankeeptrackoftheelementswehavealreadyseenandwecanfindtheduplicatesinjustonescan.Example5.7

Page 119:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

voidprintRepeating(intarr[],intsize)

HashTableh;inti;printf("Repeatingelementsare");for(i=0;i<size;i++)if(findValue(h,arr[i]))printf("%d",arr[i]);elseaddValue(h,arr[i]);

Hash-TableinsertandfindtakeconstanttimeO(1)sothetotalTimeComplexityofthealgorithmisO(n)time.SpaceComplexityisalsoO(n)Forthapproach:Counting,thisapproachisonlypossibleifweknowtherangeoftheinput.Ifweknowthat,theelementsinthearrayareintherange0ton-1.Wecanreserveandarrayoflengthnandwhenweseeanelementwecanincreaseitscount.Injustonesinglescan,weknowtheduplicates.Ifweknowtherangeoftheelements,thenthisisthefastestwaytofindtheduplicates.Example5.8voidprintRepeating(intarr[],intsize)

int*count=(int*)calloc(sizeof(int),size);inti;printf("Repeatingelementsare");for(i=0;i<size;i++)if(count[arr[i]]==1)printf("%d",arr[i]);elsecount[arr[i]]++;

Counting approach just uses an array so insert and find take constant time O(1) so the total TimeComplexityofthealgorithmisO(n)time.SpaceComplexityforcreatingcountarrayisalsoO(n)

Findmax,appearingelementinanarrayGivenanarrayofnnumbers,findtheelement,whichappearsmaximumnumberoftimes.Firstapproach:Exhaustive search orBrute force, for each element in array find howmany times this

Page 120:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

particularvalueappears inarray.Keep trackof themaxCountandwhensomeelementcount isgreaterthanmaxCountthenupdatethemaxCount.Thisisdoneusingtwoforloop,firstlooptoselecttheelementandsecondlooptocounttheoccurrenceofthatelement.TheTimeComplexityisO(n2),andSpaceComplexityisO(1)Example5.9intgetMax(intarr[],intsize)

inti,j;intmax=arr[0],count=1,maxCount=1;

for(i=0;i<size;i++)count=1;for(j=i+1;j<size;j++)if(arr[i]==arr[j])count++;if(count>maxCount)max=arr[i];maxCount=count;returnmax;

Secondapproach:Sorting,Sortalltheelementsinthearrayandafterthisinasinglescan,wecanfindthecounts.SortingalgorithmstakeO(n.log(n))timeandsinglescantakeO(n)time.TheTimeComplexityofanalgorithmisO(n.log(n)) andSpaceComplexityisO(1)Example5.10intgetMax(intarr[],intsize)

intmax=arr[0],maxCount=1,curr=arr[0],currCount=1;inti;Sort(arr,size);for(i=1;i<size;i++)if(arr[i]==arr[i-1])currCount++;elsecurrCount=1;curr=arr[i];

Page 121:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if(currCount>maxCount)maxCount=currCount;max=curr;returnmax;

Thirdapproach:Counting,Thisapproachisonlypossibleifweknowtherangeoftheinput.Ifweknowthat,theelementsinthearrayareintherange0ton-1.Wecanreserveandarrayoflengthnandwhenweseeanelementwecanincreaseitscount.Injustonesinglescan,weknowtheduplicates.Ifweknowtherangeoftheelements,thenthisisthefastestwaytofindthemaxcount.Counting approach just uses array so to increase count take constant time O(1) so the total TimeComplexityofthealgorithmisO(n)time.SpaceComplexityforcreatingcountarrayisalsoO(n)Example5.11#defineN100intgetMax(intarr[],intsize)

intmax=arr[0],maxCount=1;int*count=(int*)calloc(sizeof(int),N);inti;

for(i=0;i<size;i++)count[arr[i]]++;if(count[arr[i]]>maxCount)maxCount=count[arr[i]];max=arr[i];returnmax;

Majoritye lementinanArrayGivenanarrayofnelements.Findthemajorityelement,whichappearsmorethann/2times.Return0incasethereisnomajorityelement.Firstapproach:Exhaustive search orBrute force, for each element in array find howmany times thisparticularvalueappears inarray.Keep trackof themaxCountandwhensomeelementcount isgreaterthanmaxCountthenupdatethemaxCount.Thisisdoneusingtwoforloop,firstlooptoselecttheelement

Page 122:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

andsecondlooptocounttheoccurrenceofthatelement.Oncewehave the final,maxCountwe can see if it is greater than n/2, if it is greater thanwehave amajorityifnotwedonothaveanymajority.TheTimeComplexityisO(n2)+O(1)=O(n2)andSpaceComplexityisO(1)Example5.12intgetMajority(intarr[],intsize)

inti,j;intmax=0,count=0,maxCount=0;for(i=0;i<size;i++)for(j=i+1;j<size;j++)if(arr[i]==arr[j])count++;if(count>maxCount)max=arr[i];maxCount=count;if(maxCount>size/2)returnmax;elsereturn0;

Secondapproach:Sorting,Sortalltheelementsinthearray.Ifthereisamajoritythanthemiddleelementattheindexn/2mustbethemajoritynumber.Sojustsinglescancanbeusedtofinditscountandseeifthemajorityisthereornot.SortingalgorithmstakeO(n.logn)timeandsinglescantakeO(n)time.TheTimeComplexityofanalgorithmisO(n.logn) andSpaceComplexityisO(1)Example5.13intgetMajority(intarr[],intsize)

intmajIndex=size/2,count=1;inti;intcandidate;Sort(arr,size);candidate=arr[majIndex];count=0;for(i=0;i<size;i++)

Page 123:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if(arr[i]==candidate)count++;if(count>size/2)returnarr[majIndex];elsereturn0;

Thirdapproach: This is a cancelation approach (Moore’sVotingAlgorithm), if all the elements standagainstthemajorityandeachelementiscancelledwithoneelementofmajorityifthereismajoritythenmajorityprevails.·Setthefirstelementofthearrayasmajoritycandidateandinitializethecounttobe1.·Startscanningthearray.

oIfwegetsomeelementwhosevaluesameasamajoritycandidate,thenweincreasethecount.oIfwegetanelementwhosevalueisdifferentfromthemajoritycandidate,thenwedecrementthe

count.oIfcountbecome0,thatmeanswehaveanewmajoritycandidate.Makethecurrentcandidateas

majoritycandidateandresetcountto1.oAttheend,wewillhavetheonlyprobablemajoritycandidate.

·Nowscanthroughthearrayonceagaintoseeifthatcandidatewefoundabovehaveappearedmorethann/2times.

Countingapproachjustscansthrowarraytwotimes.TheTimeComplexityofthealgorithmisO(n)time.SpaceComplexityforcreatingcountarrayisalsoO(1)Example5.14intgetMajority(intarr[],intsize)

intmajIndex=0,count=1;inti;intcandidate;for(i=1;i<size;i++)if(arr[majIndex]==arr[i])count++;elsecount--;if(count==0)majIndex=i;count=1;candidate=arr[majIndex];count=0;

Page 124:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

for(i=0;i<size;i++)if(arr[i]==candidate)count++;if(count>size/2)returnarr[majIndex];elsereturn0;

FindthemissingnumberinanArrayGivenanarrayofn-1elements,whichareintherangeof1ton.Therearenoduplicatesinthearray.Oneoftheintegerismissing.Findthemissingelement.Firstapproach:ExhaustivesearchorBruteforce,foreachvalueintherange1ton,findifthereissomeelementinarraywhichhavethesamevalue.Thisisdoneusingtwoforloop,firstlooptoselectvalueintherange1tonandthesecondlooptofindifthiselementisinthearrayornot.TheTimeComplexityisO(n2)andSpaceComplexityisO(1)Example5.15intfindMissingNumber(intarr[],intsize)

inti,j,found=0;for(i=1;i<=size;i++)found=0;for(j=0;j<size;j++)if(arr[j]==i)found=1;break;if(found==0)returni;

Secondapproach:Sorting,Sortalltheelementsinthearrayandafterthisinasinglescan,wecanfindtheduplicates.SortingalgorithmstakeO(n.logn)timeandsinglescantakeO(n)time.TheTimeComplexityofanalgorithmisO(n.logn)andSpaceComplexityisO(1)

Page 125:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Thirdapproach:Hash-Table,usingHash-Table,wecankeeptrackoftheelementswehavealreadyseenandwecanfindthemissingelementinjustonescan.Hash-TableinsertandfindtakeconstanttimeO(1)sothetotalTimeComplexityofthealgorithmisO(n)time.SpaceComplexityisalsoO(n)Forthapproach:Counting,weknowtherangeoftheinputsocountingwillwork.Asweknowthat, theelementsinthearrayareintherange0ton-1.Wecanreserveandarrayoflengthnandwhenweseeanelementwecanincreaseitscount.Injustonesinglescan,weknowthemissingelement.Counting approach just uses an array so insert and find take constant time O(1) so the total TimeComplexityofthealgorithmisO(n)time.SpaceComplexityforcreatingcountarrayisalsoO(n)Fifthapproach:Youareallowedtomodifythegiveninputarray.Modifythegiveninputarrayinsuchawaythatinthenextscanyoucanfindthemissingelement.Whenyouscanthroughthearray.Whenatindex“index”,thevaluestoredinthearraywillbearr[index]soadd thenumber“n+1” toarr[arr[ index]].Alwaysread thevaluefromthearrayusingareminderoperator“%”.Whenyouscanthearrayforthefirsttimeandmodifiedallthevalues,thenonesinglescanyou can see if there is some value in the arraywhich is smaller than “n+1” that index is themissingnumber.Inthisapproach,thearrayisscannedtwotimesandtheTimeComplexityofthisalgorithmisO(n).SpaceComplexityisO(1)Sixthapproach:Summationformulatofindthesumofnnumbersfrom1ton.Subtractthevaluesstoredinthearrayandyouwillhaveyourmissingnumber.TheTimeComplexityofthisalgorithmisO(n).SpaceComplexityisO(1)Seventhapproach:XORapproachtofindthesumofnnumbersfrom1ton.XORthevaluesstoredinthearrayandyouwillhaveyourmissingnumber.TheTimeComplexityofthisalgorithmisO(n).SpaceComplexityisO(1).Example5.16intfindMissingNumber(intarr[],intsize,intrange)

inti;intxorSum=0;//gettheXORofallthenumbersfrom1torangefor(i=1;i<=range;i++)xorSum^=i;

//loopthroughthearrayandgettheXORofelementsfor(i=0;i<size;i++)

Page 126:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

xorSum^=arr[i];returnxorSum;

Note: Same problem can be asked in many forms (sometimes you have to do the xor of the rangesometimeyoudonot):1.Therearenumbers in the rangeof1-noutofwhichall appears single timebutone that appear two

times.2.All theelements in the range1-nareappearing16 timesandoneelementappear17 times.Find the

elementthatappears17times.

FindPairinanArrayGivenanarrayofnnumbers,findtwoelementssuchthattheirsumisequalto“value”Firstapproach:Exhaustive searchorBrute force, for eachelement in array find if there is someotherelement, which sum up to the desired value. This is done using two for loop, first loop to select theelementandsecondlooptofindanotherelement.TheTimeComplexityisO(n2) andSpaceComplexityisO(1)Example5.17intFindPair(int*arr,intsize,intvalue)

inti,j;for(i=0;i<size;i++)for(j=i+1;j<size;j++)if((arr[i]+arr[j])==value)printf("Thepairis%d,%d",arr[i],arr[j]);return1;return0;

Secondapproach:Sorting,Stepsareasfollows:1.Sortalltheelementsinthearray.2.Taketwovariablefirstandsecond.Variablefirst=0andsecond=size-13.Computesum=arr[first]+arr[second]4.Ifthesumisequaltothedesiredvalue,thenwehavethesolution5.Ifthesumislessthanthedesiredvalue,thenwewillincreasefirst6.Ifthesumisgreaterthanthedesiredvalue,thenwewilldecreasethesecond7.Werepeattheaboveprocesstillwegetthedesiredpairorwegetfirst>=second(don’thaveapair)SortingalgorithmstakeO(n.logn)timeandsinglescantakeO(n)time.

Page 127:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TheTimeComplexityofanalgorithmisO(n.logn)andSpaceComplexityisO(1)Example5.18intFindPair(int*arr,intsize,intvalue)

intfirst=0,second=size-1;intcurr;Sort(arr,size);

while(first<second)curr=arr[first]+arr[second];if(curr==value)printf("Thepairis%d,%d",arr[first],arr[second]);return1;elseif(curr<value)first++;elsesecond--;return0;

Thirdapproach:Hash-Table,usingHash-Table,wecankeeptrackoftheelementswehavealreadyseenandwecanfindthepairinjustonescan.1.Foreachelement,insertthevalueinHashtable.Letsaycurrentvalueisarr[index]2.Ifthevalue-arr[index]isalreadyinaHashtable.3.Ifvalue-arr[index]isintheHashtablethenwehavethedesiredpair.4.Else,proceedtothenextentryinthearray.Hash-TableinsertandfindtakeconstanttimeO(1)sothetotalTimeComplexityofthealgorithmisO(n)time.SpaceComplexityisalsoO(n)Example5.19intFindPair(int*arr,intsize,intvalue)

HashTableh;inti;for(i=0;i<size;i++)if(findValue(h,value-arr[i]))printf("Thepairis%d,%d",arr[i],value-arr[i]);

Page 128:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

return1;addValue(h,arr[i]);return0;

Forthapproach:Counting,Thisapproachisonlypossibleifweknowtherangeoftheinput.Ifweknowthat,theelementsinthearrayareintherange0ton-1.Wecanreserveandarrayoflengthnandwhenweseeanelementwecanincreaseitscount.InplaceoftheHashtableintheaboveapproach,wewillusethisarrayandwillfindoutthepair.Counting approach just uses an array so insert and find take constant time O(1) so the total TimeComplexityofthealgorithmisO(n)time.SpaceComplexityforcreatingcountarrayisalsoO(n)

FindthePairintwoArraysGiventwoarrayXandY.Findapairofelements(xi,yi)suchthatxi∈Xandyi∈Ywherexi+yi=value.Firstapproach:ExhaustivesearchorBrute force, loop throughelementxiofXandsee ifyoucanfind(value–xi)inY.Twoforloop.TheTimeComplexityisO(n2)andSpaceComplexityisO(1)Secondapproach:Sorting,SortalltheelementsinthesecondarrayY.ForeachelementifXyoucanseeifthatelementisthereinYbyusingbinarysearch.SortingalgorithmstakeO(m.logm)andsearchingwilltakeO(n.logm) time.TheTimeComplexityofanalgorithmisO(n.logm)orO(m.logm)andSpaceComplexityisO(1)Thirdapproach:Sorting,Stepsareasfollows:1.SorttheelementsofbothXandYinincreasingorder.2.TakethesumofthesmallestelementofXandthelargestelementofY.3.Ifthesumisequaltovalue,wegotourpair.4.Ifthesumissmallerthanvalue,takenextelementofX5.Ifthesumisgreaterthanvalue,takethepreviouselementofYSortingalgorithmstakeO(n.logn)+O(m.logm)forsortingandsearchingwilltakeO(n+m) time.TheTimeComplexityofanalgorithmisO(n.logn)SpaceComplexityisO(1)Forthapproach:Hash-Table,Stepsareasfollows:1.ScanthroughalltheelementsinthearrayYandinsertthemintoHashtable.2.NowscanthroughalltheelementsofarrayX,letussupposethecurrentelementisxiseeifyoucan

find(value-xi)intheHashtable.3.Ifyoufindthevalue,yougotyourpair.4.Ifnot,thengotothenextvalueinthearrayX.

Page 129:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Hash-TableinsertandfindtakeconstanttimeO(1)sothetotalTimeComplexityofthealgorithmisO(n)time.SpaceComplexityisalsoO(n)Fifthapproach: Counting, This approach is only possible ifwe know the range of the input. Same asHashtableimplementationjustuseasimplearrayinplaceofHashtableandyouaredone.Counting approach just uses an array so insert and find take constant time O(1) so the total TimeComplexityofthealgorithmisO(n)time.SpaceComplexityforcreatingcountarrayisalsoO(n).

TwoelementswhosesumisclosesttozeroGivenanArrayof integers,both+veand-ve.Youneed tofind the twoelementssuch that theirsumisclosesttozero.Firstapproach:ExhaustivesearchorBruteforce,foreachelementinarrayfindtheotherelementwhosevaluewhenaddedwillgiveminimumabsolutevalue.Thisisdoneusingtwoforloop,firstlooptoselecttheelementandsecondlooptofindtheelementthatshouldbeaddedtoitsothattheabsoluteofthesumwillbeminimumorclosetozero.TheTimeComplexityisO(n2)andSpaceComplexityisO(1)Example5.20voidminAbsSumPair(intarr[],intsize)

intl,r,minSum,sum,minFirst,minSecond;

/*Arrayshouldhaveatleasttwoelements*/if(size<2)printf("InvalidInput");return;

/*Initializationofvalues*/minFirst=0;minSecond=1;minSum=abs(arr[0]+arr[1]);

for(l=0;l<size-1;l++)for(r=l+1;r<size;r++)sum=abs(arr[l]+arr[r]);if(sum<minSum)

Page 130:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

minSum=sum;minFirst=l;minSecond=r;printf("Thetwoelementswithminimumsumare%d&%d",arr[minFirst],arr[minSecond]);

Secondapproach:SortingStepsareasfollows:1.Sortalltheelementsinthearray.2.TaketwovariablefirstIndex=0andsecondIndex=size-13.Computesum=arr[firstIndex]+arr[secondIndex]4.Ifthesumisequaltothe0thenwehavethesolution5.Ifthesumislessthanthe0thenwewillincreasefirst6.Ifthesumisgreaterthanthe0thenwewilldecreasethesecond7.Werepeattheaboveprocess3to6,tillwegetthedesiredpairorwegetfirst>=secondExample5.21voidminAbsSumPair(intarr[],intsize)

intl,r,minSum,sum,minFirst,minSecond;/*Arrayshouldhaveatleasttwoelements*/if(size<2)printf("InvalidInput");return;Sort(arr,size);/*Initializationofvalues*/minFirst=0;minSecond=size-1;minSum=abs(arr[minFirst]+arr[minSecond]);for(l=0,r=size-1;l<r;)sum=(arr[l]+arr[r]);if(abs(sum)<minSum)minSum=abs(sum);minFirst=l;minSecond=r;

Page 131:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if(sum<0)l++;elseif(sum>0)r++;elsebreak;printf("Thetwoelementswithminimumsumare%d&%d",arr[minFirst],arr[minSecond]);

FindmaximainabitonicarrayAbitonicarraycomprisesofan increasingsequenceof integers immediately followedbyadecreasingsequenceofintegers.Sincetheelementsaresortedinsomeorder,weshouldgoforalgorithmsimilartobinarysearch.Thestepsareasfollows:1.Taketwovariableforstoringstartandendindex.Variablestart=0andend=size-12.Findthemiddleelementofthearray.3.Seeifthemiddleelementisthemaxima.Ifyes,returnthemiddleelement.4.Alternatively,Ifthemiddleelementinincreasingpart,thenweneedtolookforinmid+1andend.5.Alternatively,ifthemiddleelementisinthedecreasingpart,thenweneedtolookinthestartandmid-

1.6.Repeatstep2to5untilwegetthemaxima.Example5.22intSearchBotinicArrayMax(intarr[],intsize)

intstart=0,end=size-1,mid;intmaximaFound=0;if(size<3)printf("error");return0;while(start<=end)mid=(start+end)/2;if(arr[mid-1]<arr[mid]&&arr[mid+1]<arr[mid])//maximamaximaFound=1;break;elseif(arr[mid-1]<arr[mid]&&arr[mid]<arr[mid+1])//increasingstart=mid+1;

Page 132:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

elseif(arr[mid-1]>arr[mid]&&arr[mid]>arr[mid+1])//decreasingend=mid-1;elsebreak;if(maximaFound==0)printf("error");return0;returnarr[mid];

SearchelementinabitonicarrayAbitonicarraycomprisesofan increasingsequenceof integers immediately followedbyadecreasingsequenceofintegers.Tosearchanelementinabitonicarray:1.Findtheindexormaximumelementinthearray.Byfindingtheendofincreasingpartofthearray,using

modifiedbinarysearch.2.Oncewehavethemaximumelement,searchthegivenvalueinincreasingpartofthearrayusingbinary

search.3.Ifthevalueisnotfoundinincreasingpart,searchthesamevalueindecreasingpartofthearrayusing

binarysearch.Example5.23intSearchBitonicArray(intarr[],intsize,intkey)

intmax=FindMaxBitonicArray(arr,size);

intk=BinarySearch(arr,0,max,key,true);if(k!=-1)returnk;elsereturnBinarySearch(arr,max+1,size-1,key,false);

intFindMaxBitonicArray(intarr[],intsize)

intstart=0,end=size-1,mid;if(size<3)

Page 133:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

printf("error");return0;while(start<=end)mid=(start+end)/2;if(arr[mid-1]<arr[mid]&&arr[mid+1]<arr[mid])//maximareturnmid;elseif(arr[mid-1]<arr[mid]&&arr[mid]<arr[mid+1])//increasingstart=mid+1;elseif(arr[mid-1]>arr[mid]&&arr[mid]>arr[mid+1])//increasingend=mid-1;elsebreak;printf("error");return0;

intBinarySearch(intarr[],intstart,intend,intkey,intisInc)

intmid;if(end<start)return-1;mid=(start+end)/2;if(key==arr[mid])returnmid;if(isInc&&key<arr[mid]||!isInc&&key>arr[mid])returnBinarySearch(arr,start,mid-1,key,isInc);elsereturnBinarySearch(arr,mid+1,end,key,isInc);

Page 134:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

OccurrencecountsinsortedArrayGivenasortedarrayarr[]findthenumberofoccurrencesofanumber.Firstapproach:Bruteforce,Traversethearrayandinlineartimewewillgettheoccurrencecountofthenumber.Thisisdoneusingoneloop.TheTimeComplexityisO(n)andSpaceComplexityisO(1).Example5.24intfindKeyCount(intarr[],intsize,intkey)

inti,count=0;for(i=0;i<size;i++)if(arr[i]==key)count++;returncount;

Secondapproach:Sincewehavesortedarray,weshouldthinkaboutsomebinarysearch.1.First,weshouldfindthefirstoccurrenceofthekey.2.Thenweshouldfindthelastoccurrenceofthekey.3.Takethedifferenceofthesetwovaluesandyouwillhavethesolution.Example5.25intfindKeyCount(intarr[],intsize,intkey)

intfirstIndex,lastIndex;firstIndex=findFirstIndex(arr,0,size-1,key);lastIndex=findLastIndex(arr,0,size-1,key);return(lastIndex-firstIndex+1);

intfindFirstIndex(intarr[],intstart,intend,intkey)

intmid;if(end<start)return-1;

mid=(start+end)/2;

if(key==arr[mid]&&(mid==start||arr[mid-1]!=key))

Page 135:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

returnmid;if(key<=arr[mid])//<=isusthenumber.tinsortedarray.returnfindFirstIndex(arr,start,mid-1,key);elsereturnfindFirstIndex(arr,mid+1,end,key);

intfindLastIndex(intarr[],intstart,intend,intkey)

intmid;if(end<start)return-1;

mid=(start+end)/2;

if(key==arr[mid]&&(mid==end||arr[mid+1]!=key))returnmid;

if(key<arr[mid])//<returnfindLastIndex(arr,start,mid-1,key);elsereturnfindLastIndex(arr,mid+1,end,key);

SeparateevenandoddnumbersinArrayGiven an array of even and odd numbers, write a program to separate even numbers from the oddnumbers.Firstapproach:allocateaseparatearray,thenscanthroughthegivenarray,andfillevennumbersfromthestartandoddnumbersfromtheend.Secondapproach:Algorithmisasfollows.1.Initializethetwovariableleftandright.Variableleft=0andright=size-1.2.Keepincreasingtheleftindexuntiltheelementatthatindexiseven.3.Keepdecreasingtherightindexuntiltheelementatthatindexisodd.4.Swapthenumberatleftandrightindex.

Page 136:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

5.Repeatsteps2to4untilleftislessthanright.Example5.26voidswap(int*first,int*second)

inttemp=*first;*first=*second;*second=temp;

voidseperateEvenAndOdd(intarr[],intsize)

intleft=0,right=size-1;

while(left<right)if(arr[left]%2==0)left++;elseif(arr[right]%2==1)right--;elseswap(&arr[left],&arr[right]);left++;right--;

Stockpurchase-sellproblemGivenanarray,whosenthelementisthepriceofthestockonnthday.Youareaskedtobuyonceandsellonce,onwhatdateyouwillbebuyingandatwhatdateyouwillbesellingtogetmaximumprofit.

OrGivenanarrayofnumbers,youneedtomaximizethedifferencebetweentwonumbers,suchthatyoucansubtractthenumber,whichappearbeforeformthenumberthatappearafterit.Firstapproach:Bruteforce,foreachelementinarrayfindifthereissomeotherelementwhosedifferenceismaximum.Thisisdoneusingtwoforloop,firstlooptoselect,buydateindexandthesecondlooptofinditssellingdateentry.TheTimeComplexityisO(n2)andSpaceComplexityisO(1)

Page 137:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Secondapproach:Anothercleversolutionistokeeptrackofthesmallestvalueseensofarfromthestart.Ateachpoint,wecanfindthedifferenceandkeeptrackofthemaximumprofit.Thisisalinearsolution.TheTimeComplexityof thealgorithmisO(n) time.SpaceComplexity forcreatingcountarray isalsoO(1)Example5.27voidmaxProfit(intstocks[],intsize)

intbuy=0,sell=0;intcurMin=0;intcurrProfit=0;intmaxProfit=0;inti;

for(i=0;i<size;i++)if(stocks[i]<stocks[curMin])curMin=i;

currProfit=stocks[i]-stocks[curMin];

if(currProfit>maxProfit)buy=curMin;sell=i;maxProfit=currProfit;printf("\nPurchasedayis-%datprice%d",buy,stocks[buy]);printf("\nSelldayis-%datprice%d",sell,stocks[sell]);

FindamedianofanarrayGivenanarrayofnumbersofsizen,ifalltheelementsofthearrayaresortedthenfindtheelement,whichlieattheindexn/2.Firstapproach:Sortthearrayandreturntheelementinthemiddle.SortingalgorithmstakeO(n.logn).TheTimeComplexityofanalgorithmisO(n.logn)andSpaceComplexityisO(1)Example5.28

Page 138:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

intgetMedian(intarr[],intsize)

sort(arr,size);returnarr[size/2];

Second approach: Use QuickSelect algorithm. This algorithm we will look into the next chapter. InQuickSortalgorithmjustskiptherecursivecallthatwedonotneed.TheaverageTimeComplexityofthisalgorithmwillbeO(1)

Findmedianoftwosortedarrays.Firstapproach:Keeptrackof theindexofboththearray,saytheindexareiand j.keep increasing theindexofthearraywhicheverhaveasmallervalue.Useacountertokeeptrackoftheelementsthatwehavealreadytraced.TheTimeComplexityofanalgorithmisO(n)andSpaceComplexityisO(1)Example5.29intfindMedian(intarrFirst[],intsizeFirst,intarrSecond[],intsizeSecond)

//cealingfunction.intmedianIndex=((sizeFirst+sizeSecond)+(sizeFirst+sizeSecond)%2)/2;inti=0,j=0;intcount=0;while(count<medianIndex-1)if(i<sizeFirst-1&&arrFirst[i]<arrSecond[j])i++;elsej++;

count++;

if(arrFirst[i]<arrSecond[j])returnarrFirst[i];elsereturnarrSecond[j];

Findkthelementoftwosortedarrays.FindkthSmallestElementintheUnionofTwoSortedArrays

Page 139:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example5.301.#defineERROR-999;2.intmin(inta,intb)3.4.returna>b?b:a;5.6.intfind_kth(intfirst[],intsecond[],intsizeFirst,intsizeSecond,intk)7.8.if(sizeFirst+sizeSecond<k)9.returnERROR;10.11.if(sizeFirst==0)12.returnsecond[k-1];13.14.if(sizeSecond==0)15.returnfirst[k-1];16.17.if(k==1)18.returnmin(first[0],second[0]);19.20./*Nowdivideandconquer*/21.inti=min(sizeFirst,k/2);22.intj=min(sizeSecond,k/2);23.24.if(first[i-1]>second[j-1])25.returnfind_kth(first,second+j,i,sizeSecond-j,k-j);26.else27.returnfind_kth(first+i,second,sizeFirst-i,j,k-i);28.

Search01ArrayGivenanarrayof0’sand1’s.Allthe0’scomebefore1’s.Writeanalgorithmtofindtheindexofthefirst1.

OrYou are given an array which contains either 0 or 1, and they are in sorted order Ex. a[ ] = 1,1,1,1,0,0,0Howwillyoucountnoof1`sand0's?Firstapproach:BinarySearch,sincethearrayissortedusingbinarysearchtofindthedesiredindex.TheTimeComplexityofanalgorithmisO(logn)andSpaceComplexityisO(1)Example5.31intBinarySearch01Wrapper(intarr[],intsize)

Page 140:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if(size==1&&arr[0]==1)return0;

returnBinarySearch01(arr,0,size-1);

intBinarySearch01(intarr[],intstart,intend)

intmid;if(end<start)return-1;

mid=(start+end)/2;

if(1==arr[mid]&&0==arr[mid-1])returnmid;

if(0==arr[mid])returnBinarySearch01(arr,mid+1,end);elsereturnBinarySearch01(arr,start,mid-1);

SearchinsortedrotatedArrayGivenasortedarrayofnintegerswhichisrotatedanunknownnumberoftimes.Findanelementinthearray.Firstapproach:Sincethearrayissorted,wecanusemodifiedbinarysearchtofindtheelement.TheTimeComplexityofanalgorithmisO(logn)andSpaceComplexityisO(1)Example5.32intBinarySearchRotateArray(intarr[],intstart,intend,intkey)

intmid;if(end<start)return-1;

mid=(start+end)/2;

if(key==arr[mid])

Page 141:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

returnmid;if(arr[mid]>arr[start])if(arr[start]<=key&&key<arr[mid])returnBinarySearchRotateArray(arr,start,mid-1,key);elsereturnBinarySearchRotateArray(arr,mid+1,end,key);elseif(arr[mid]<key&&key<=arr[end])returnBinarySearchRotateArray(arr,mid+1,end,key);elsereturnBinarySearchRotateArray(arr,start,mid-1,key);

intBinarySearchRotateArrayWrapper(intarr[],intsize,intkey)

returnBinarySearchRotateArray(arr,0,size-1,key);

FirstRepeatedelementinthearrayGivenanunsortedarrayofnelements,findthefirstelement,whichisrepeated.Firstapproach:Exhaustive searchorBrute force, for eachelement in array find if there is someotherelementwiththesamevalue.Thisisdoneusingtwoforloop,firstlooptoselecttheelementandsecondlooptofinditsduplicateentry.TheTimeComplexityisO(n2)andSpaceComplexityisO(1)Example5.33intFirstRepeated(int*arr,intsize)

inti,j;for(i=0;i<size;i++)

Page 142:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

for(j=i+1;j<size;j++)if(arr[i]==arr[j])returnarr[i];

return0;

Secondapproach:Hash-Table,usingHash-Table,wecankeeptrackofthenumberoftimesaparticularelement came in the array. First scan just populate the Hashtable. In the second, scan just look theoccurrenceof theelements in theHashtable. Ifoccurrence ismoreforsomeelement, thenwehaveoursolutionandthefirstrepeatedelement.Hash-TableinsertandfindtakeconstanttimeO(1)sothetotalTimeComplexityofthealgorithmisO(n)time.SpaceComplexityisalsoO(n)formaintaininghash.

Page 143:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TransformArrayHowwouldyouswapelementsofanarraylike[a1a2a3a4b1b2b3b4]toconvertitinto[a1b1a2b2a3b3a4b4]?

Approach:·Firstswapelementsinthemiddlepair·Nextswapelementsinthemiddletwopairs·Nextswapelementsinthemiddlethreepairs·Iteraten-1steps.

Ex:withn=4.a1a2a3a4b1b2b3b4a1a2a3b1a4b2b3b4a1a2b1a3b2a4b3b4a1b1a2b2a3b3a4b4Example5.34voidtransformArrayAB1(intarr[],intsize)

intN=size/2,i,j;for(i=1;i<N;i++)for(j=0;j<i;j++)swap(&arr[N-i+2*j],&arr[N-i+2*j+1]);

voidswap(int*a,int*b)

intt=*a;*a=*b;*b=t;

Find2ndlargestnumberinanarraywithminimumcomparisonsSupposeyouaregivenanunsortedarrayofndistinctelements.Howwillyouidentifythesecondlargestelementwithminimumnumberofcomparisons?First approach: Find the largest element in the array. Then replace the last element with the largestelement.Thensearchthesecondlargestelementinttheremainingn-1elements.Thetotalnumberofcomparisonsis:(n-1)+(n-2)

Page 144:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Secondapproach:Sortthearrayandthengivethe(n-1)element.Thisapproachisstillmoreinefficient.Third approach: Using priority queue / Heap. This approach we will look into heap chapter. UsebuildHeap() function tobuildheapfromthearray.This isdone inncomparisons.Arr[0] is the largestnumber,andthegreateramongarr[1]andarr[2]isthesecondlargest.Thetotalnumberofcomparisonsare:(n-1)+1=n

CheckiftwoarraysarepermutationofeachotherGiventwointegerarrays.Youhavetocheckwhethertheyarepermutationofeachother.Firstapproach:Sorting,Sortall theelementsofboth thearraysandCompareeachelementofboth thearraysfrombeginningtoend.Ifthereisnomismatch,returntrue.Otherwise,false.SortingalgorithmstakeO(n.logn)timeandcomparisontakeO(n)time.TheTimeComplexityofanalgorithmisO(n.logn)andSpaceComplexityisO(1)Example5.35intcheckPermutation(intarray1[],intsize1,intarray2[],intsize2)

if(size1!=size2)return0;

sort(array1,size1);sort(array2,size2);

for(inti=0;i<size1;i++)if(array1[i]!=array2[i])return0;return1;

Secondapproach:Hash-Table(Assumption:Noduplicates).Stepsare:1.CreateaHash-Tableforalltheelementsofthefirstarray.2.TraversetheotherarrayfrombeginningtotheendandsearchforeachelementintheHash-Table.3.IfalltheelementsarefoundintheHash-Table,returntrueotherwisereturnfalse.Hash-TableinsertandfindtakeconstanttimeO(1)sothetotalTimeComplexityofthealgorithmisO(n)time.SpaceComplexityisalsoO(n)TimeComplexity=O(n)(ForcreationofHash-Tableandlook-up),SpaceComplexity=O(n)(ForcreationofHash-Table).

Page 145:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example5.36intcheckPermutation(intarray1[],intsize1,intarray2[],intsize2)

inti;if(size1!=size2)return0;Hashtableh;

for(i=0;i<size1;i++)insert(h,array1[i]);

for(i=0;i<size2;i++)if(!containsValue(h,array2[i]))returnfalse;returntrue;

RemoveduplicatesinanintegerarrayFirstapproach:SortingStepsareasfollows:1.Sortthearray.2. Take two pointers.A subarraywill be createdwith all unique elements starting from 0 to the first

pointer(Thefirstpointerpointstothelastindexofthesubarray).Thesecondpointeriteratesthroughthearrayfrom1totheend.Uniquenumberswillbecopiedfromthesecondpointerlocationtofirstpointerlocationandthesameelementsareignored.

TimeComplexitycalculation:Timetosortthearray=O(nlogn).Timetoremoveduplicates=O(n).OverallTimeComplexity=O(nlogn).NoadditionalspaceisrequiredsoSpaceComplexityisO(1).

Example5.37intremoveDuplicates(intarray[],intsize)

intj=0;inti;if(size==0)return0;sort(array,size);

for(i=1;i<size;i++)if(array[i]!=array[j])

Page 146:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

j++;array[j]=array[i];returnj+1;

Searchingforanelementina2-dsortedarrayGivena2dimensionalarray.Eachrowandcolumnaresortedinascendingorder.Howwouldyoufindanelementinit?Thealgorithmworksas:1.Startwithelementatlastcolumnandfirstrow2.Iftheelementisthevaluewearelookingfor,returntrue.3. If theelement isgreater than thevalueweare lookingfor,go to theelementatpreviouscolumnbut

samerow.4.Iftheelementislessthanthevaluewearelookingfor,gototheelementatnextrowbutsamecolumn.5.Returnfalse,iftheelementisnotfoundafterreachingtheelementofthelastrowofthefirstcolumn.

Conditionrow<r&&column>=0isfalse.Runningtime=O(N).Example5.38intFindElementIn2DArray(int*arr[],intr,intc,intvalue)

introw=0;intcolumn=c-1;

while(row<r&&column>=0)if(arr[row][column]==value)return1;elseif(arr[row][column]>value)column--;elserow++;return0;

Page 147:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise1.Given an array of n elements, find the first repeated element.Which of the followingmethodswill

workforus(andwhichofthemethodwillnotworkforus).Ifamethodwork,thenimplementsit.·Bruteforceexhaustivesearch.·UseHash-Tabletokeepanindexoftheelementsandusethesecondscantofindtheelement.·Sortingtheelements.·Ifweknowtherangeoftheelementthenwecanusecountingtechnique.

Hint:Whenorderinwhichelementsappearininputisimportant,wecannotusesorting.

2.Givenanarrayofn elements,write analgorithm to find three elements in anarraywhose sum is a

givenvalue.

Hint:Trytodothisproblemusingabruteforceapproach.Thentrytoapplythesortingapproachalongwithabruteforceapproach.TheTimeComplexitywillbeO(n2)

3. Given an array of –ve and +ve numbers, write a program to separate –ve numbers from the +ve

numbers.4.Givenanarrayof1’sand0’s,writeaprogramtoseparate0’sfrom1’s.

Hint:QuickSelect,counting5.Givenanarrayof0’s,1’sand2’s,writeaprogramtoseparate0’s,1’sand2’s.6.Givenanarraywhoseelementsismonotonicallyincreasingwithbothnegativeandpositivenumbers.

Writeanalgorithmtofindthepointatwhichlistbecomespositive.7.Givenasortedarray,findagivennumber.Iffoundreturntheindexifnot,findtheindexofthatnumber

ifitisinsertedintothearray.8.Findmaxinsortedrotatedarray.9.Findmininthesortedrotatedarray.

Page 148:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 149:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER6:SORTING

Page 150:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionSorting is the process of placing elements from a collection into ascending or descending order. Forexample,whenweplaycards,sortcards,accordingtotheirvaluesothatwecanfindtherequiredcardeasily.Whenwegotosomelibrary,thebooksarearrangedaccordingtostreams(Algorithm,Operatingsystems,Networkingetc.).Sortingarrangesdataelementsinordersothatsearchingbecomeeasier.Whenbooksarearrangedinproperindexingorder,thenitiseasytofindabookwearelookingfor.ThischapterdiscussesalgorithmsforsortingasetofN items.Understandingsortingalgorithmsare thefirststeptowardsunderstandingalgorithmanalysis.Manysortingalgorithmsaredevelopedandanalysed.A sorting algorithm likeBubble-Sort, Insertion-Sort and Selection-Sort are easy to implement and aresuitableforthesmallinputset.However,forlargedatasettheyareslow.A sorting algorithm like Merge-Sort, Quick-Sort and Heap-Sort are some of the algorithms that aresuitableforsortinglargedataset.However,theyareoverkillifwewanttosortthesmalldataset.Somealgorithm,whichissuitablewhenwehavesomerangeinformationoninputdata.Some other algorithm is there to sort a huge data set that cannot be stored inmemory completely, forwhichexternalsortingtechniqueisdeveloped.Beforewestartadiscussionofthevariousalgorithmsonebyone.First,weshouldlookatcomparisonfunctionthatisusedtocomparetwovalues.Lessfunctionwillreturn1ifvalue1islessthanvalue2otherwise,itwillreturn0.intless(intvalue1,intvalue2)

returnvalue1<value2;Morefunctionwillreturn1ifvalue1ismorethanvalue2otherwiseitwillreturn0.intmore(intvalue1,intvalue2)

returnvalue1>value2;The value in various sorting algorithms is compared using one of the above functions and it will beswappeddependinguponthereturnvalueofthesefunctions.Ifmore()comparisonfunctionisused,thensortedoutputwillbeincreasinginorderandifless()isusedthanresultingoutputwillbeindescendingorder.

Page 151:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TypeofSortingInternalSorting:Alltheelementscanbereadintomemoryatthesametimeandsortingisperformedinmemory.

1.Selection-Sort2.Insertion-Sort3.Bubble-Sort4.Quick-Sort

ExternalSorting:Inthis,thedatasetissobigthatitisimpossibletoloadthewholedatasetintomemorysosortingisdoneinchunks.

1.Merge-SortThreethingstoconsiderinchoosing,sortingalgorithmsforapplication:

1.Numberofelementsinlist2.Anumberofdifferentordersoflistrequired3.Theamountoftimerequiredtomovethedataornotmovethedata

Page 152:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Bubble-SortBubble-Sortistheslowestalgorithmforsorting,butitisheavilyused,asitiseasytoimplement.InBubble-Sort,wecompareeachpairofadjacentvalues.Wewanttosortvaluesinincreasingordersoifthesecondvalueislessthanthefirstvaluethenweswapthesetwovalues.Otherwise,wewillgotothenextpair.Thus,smallervaluesbubbletothestartof thearray.WewillhaveNnumberofpassestoget thearraycompletelysorted.Afterthefirstpass,thelargestvaluewillbeintherightmostposition.

Example6.11.voidBubbleSort(int*arr,intsize)2.3.inti,j,temp;4.for(i=0;i<(size-1);i++)5.6.for(j=0;j<size-i-1;j++)7.8.if(more(arr[j],arr[j+1]))9.10./*Swapping*/11.temp=arr[j];12.arr[j]=arr[j+1];13.arr[j+1]=temp;14.15.16.17.Analysis:Line4:Theouterforloopsrepresentsthenumberofswapsthataredoneforcomparisonofdata.Line 6: The inner loop is actually used to do the comparison of data. At the end of each inner loop

Page 153:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

iteration,thelargestvalueismovedtotheendofthearray.Inthefirstiterationthelargestvalue,intheseconditerationthesecondlargestandsoon.Line 8: more() function is used for comparison whichmeans when the value of the first argument isgreaterthanthevalueofthesecondargumentthenperformaswap.Bythiswearesortinginincreasingorderifwehave,theless()functioninplaceofmore()thanwewillgetdecreasingordersorting.Havealookintomore()functionincaseyouforgotintmore(intvalue1,intvalue2)

returnvalue1>value2;ComplexityAnalysis:Eachtimetheinnerloopexecutefor(n-1),(n-2),(n-3)…(n-1)+(n-2)+(n-3)+.....+3+2+1=n(n-1)/2Worstcaseperformance O(n2)Averagecaseperformance O(n2)SpaceComplexity O(1)asweneedonlyonetempvariableStableSorting Yes

Page 154:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Modified(improved)Bubble-SortWhenthereisnomoreswapinonepassoftheouterloop.Itindicatesthatalltheelementsarealreadyinordersoweshouldstopsorting.ThissortingimprovementinBubble-Sortisextremelyusefulwhenweknowthat,exceptfewelementsrestofthearrayisalreadysorted.Example6.21.voidBubbleSort(int*arr,intsize)2.3.inti,j,temp,swapped=1;4.for(i=0;i<(size-1)&&swapped;i++)5.6.swapped=0;7.for(j=0;j<size-i-1;j++)8.9.if(more(arr[j],arr[j+1]))10.11./*Swapping*/12.temp=arr[j];13.arr[j]=arr[j+1];14.arr[j+1]=temp;15.swapped=1;16.17.18.19.Byapplyingthisimprovement,bestcaseofthisalgorithm,whenanarrayisnearlysorted,isimproved.BestcaseisO(n)ComplexityAnalysis:Worstcaseperformance O(n2)Averagecaseperformance O(n2)SpaceComplexity O(1)Adaptive:Whenarrayisnearlysorted O(n)StableSorting Yes

Page 155:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Insertion-Sort

Insertion-SortTimeComplexityisO(n2)whichissameasBubble-Sortbutperformabitbetterthanit.Itisthewaywearrangeourplayingcards.Wekeepasortedsubarray.Eachvalueisinsertedintoitsproperpositioninthesortedsub-arrayintheleftofit.

Example6.31.voidinsertion(int*arr,intsize)2.3.inttemp,j;4.for(inti=1;i<size;i++)5.6.temp=arr[i];7.for(j=i;j>0&&more(arr[j-1],temp));j--)8.9.arr[j]=arr[j-1];10.11.arr[j]=temp;12.13.Analysis:Line4:Theouterloopisusedtopickthevaluewewanttoinsertintothesortedleftarray.

Page 156:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Line6:Thevaluewewanttoinsertwehavepickedandsavedinatempvariable.Line7-10:Thesearethelines,whichareimplementingtheinnerloopanddoingthecomparisonusingthemore()function.Thevaluesareshiftedtotherightuntilwefindtheproperpositionofthetempvalueforwhichwearedoingthisiteration.Line11:Thisistheline,whichweareactuallyplacingthetempvalueintotheproperposition.Line4-12:Ineachiterationoftheouterloop,thelengthofthesortedarrayincreasebyone.Whenweexittheouterloop,thewholearrayissorted.ComplexityAnalysis:WorstcaseTimeComplexity O(n2)BestcaseTimeComplexity O(n)AveragecaseTimeComplexity O(n2)SpaceComplexity O(1)Stablesorting Yes

Page 157:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Selection-SortSelection-Sortsearchesthewholeunsortedarrayandputthelargestvalueattheendofit.Thisalgorithmis having the same Time Complexity, but performs better than both bubble and Insertion-Sort as lessnumberofcomparisonsrequired.ThesortedarrayiscreatedbackwardinSelection-Sort.

Example6.4:1.voidSelectionSort(int*arr,intsize)2.3.inti,j,max,temp;4.for(i=0;i<size-1;i++)5.6.max=0;7.for(j=1;j<size-1-i;j++)8.9.if(arr[j]>arr[max])10.11.max=j;12.13.14.temp=arr[size-1-i];15.arr[size-1-i]=arr[max];16.arr[max]=temp;17.18.Analysis:Line4-17: It is theouter loop,which isused topick the largestvaluefromtheunsortedarray. Ineachiteration,thelargestvaluewillbeplacedattheendofthearray.Line6:Theindexofthemaxvalueisalwayssettothebeginningofthearrayandwewilliteratethroughthearraytofindtheproperindex.Line7-10:Thesearetheinnerlooplinestofindtheproperindexofthemaximum.

Page 158:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Line14-17:Thisisthefinalreplacementofthemaximumvaluetotheproperlocation.Thesortedarrayiscreatedbackward.ComplexityAnalysis:WorstCaseTimeComplexity O(n2)BestCaseTimeComplexity O(n2)AveragecaseTimeComplexity O(n2)SpaceComplexity O(1)StableSorting NoThesamealgorithmcanbeimplementedbycreatingthesortedarrayinthefrontofthearray.Example6.5:1.voidSelectionSort(int*arr,intsize)2.3.inti,j,min,temp;4.for(i=0;i<size-1;i++)5.6.min=i;7.for(j=i+1;j<size;j++)8.9.if(arr[j]<arr[min])10.11.min=j;12.13.14.temp=arr[i];15.arr[i]=arr[min];16.arr[min]=temp;17.18.

Page 159:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Merge-Sort

Example6.6:1.#include<stdio.h>23.voidmerge(int*arr,int*tempArray,intlowerIndex,intmiddleIndex,intupperIndex)4.5.intlowerStart=lowerIndex;6.intlowerStop=middleIndex;7.intupperStart=middleIndex+1;8.intupperStop=upperIndex;9.intcount=lowerIndex;10.while(lowerStart<=lowerStop&&upperStart<=upperStop)11.12.if(arr[lowerStart]<arr[upperStart])13.tempArray[count++]=arr[lowerStart++];14.else15.tempArray[count++]=arr[upperStart++];16.17.while(lowerStart<=lowerStop)18.19.tempArray[count++]=arr[lowerStart++];20.21.while(upperStart<=upperStop)22.23.tempArray[count++]=arr[upperStart++];24.25.for(inti=lowerIndex;i<=upperIndex;i++)26.arr[i]=tempArray[i];27.

Page 160:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

1.voidmergeSrt(int*arr,int*tempArray,intlowerIndex,intupperIndex)2.3.if(lowerIndex>=upperIndex)4.return;5.intmiddleIndex=(lowerIndex+upperIndex)/2;6.mergeSrt(arr,tempArray,lowerIndex,middleIndex);7.mergeSrt(arr,tempArray,middleIndex+1,upperIndex);8.merge(arr,tempArray,lowerIndex,middleIndex,upperIndex);9.1.voidmergeSort(int*arr,intsize)2.3.int*tempArray=(int*)malloc(size*sizeof(int));4.mergeSrt(arr,tempArray,0,size-1);5.1.voidprintArray(int*arr,intsize)2.3.for(inti=0;i<size;i++)4.printf("%d",arr[i]);5.1.intmain()2.3.intarr[10]=3,4,2,1,6,5,7,8,1,1;4.mergeSort(arr,10);5.printArray(arr,10);6.·TheTimeComplexityofMerge-SortisO(nlogn)inall3cases(best,averageandworst)asMerge-Sort

alwaysdividesthearrayintotwohalvesandtakelineartimetomergetwohalves.·Itrequirestheequalamountofadditionalspaceastheunsortedlist.Hence,itisnotatallrecommended

forsearchinglargeunsortedlists.·ItisthebestSortingtechniqueforsortingLinkedLists.ComplexityAnalysis:WorstCaseTimeComplexity O(nlogn)BestCaseTimeComplexity O(nlogn)AverageTimeComplexity O(nlogn)SpaceComplexity O(n)StableSorting Yes

Page 161:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 162:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Quick-Sort

Example6.7:1.intmain()2.3.intarr[10]=4,5,3,2,6,7,1,8,9,10;4.printArray(arr,sizeof(arr)/sizeof(int));5.quickSort(arr,sizeof(arr)/sizeof(int));6.printArray(arr,sizeof(arr)/sizeof(int));7.1.voidswap(intarr[],intfirst,intsecond)2.3.inttemp=arr[first];4.arr[first]=arr[second];5.arr[second]=temp;

Page 163:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

6.1.voidprintArray(intarr[],intsize)2.3.for(inti=0;i<size;i++)4.printf("%d",arr[i]);5.printf("\n");6.1.voidquickSort(intarr[],intsize)2.3.quickSortUtil(arr,0,size-1);4.1.voidquickSortUtil(intarr[],intlower,intupper)2.3.if(upper<=lower)4.return;5.6.intpivot=arr[lower];7.8.intstart=lower;9.intstop=upper;10.11.while(lower<upper)12.13.while(arr[lower]<=pivot)14.15.lower++;16.17.while(arr[upper]>pivot)18.19.upper--;20.21.if(lower<upper)22.23.swap(arr,upper,lower);24.25.26.swap(arr,upper,start);//upperisthepivotposition27.28.quickSortUtil(arr,start,upper-1);//pivot-1istheupperforleftsubarray.29.quickSortUtil(arr,upper+1,stop);//pivot+1isthelowerforrightsubarray.30.·ThespacerequiredbyQuick-Sortisveryless,onlyO(nlogn)additionalspaceisrequired.

Page 164:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

·Quicksortisnotastablesortingtechnique,soitmightchangetheoccurrenceoftwosimilarelementsinthelistwhilesorting.

ComplexityAnalysis:WorstCaseTimeComplexity O(n2)BestCaseTimeComplexity O(nlogn)AverageTimeComplexity O(nlogn)SpaceComplexity O(nlogn)StableSorting No

Page 165:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

QuickSelectQuickselectisverysimilartoQuick-Sortinplaceofsortingthewholearraywejustignoretheone-halfofthearrayateachstepofQuick-Sortandjustfocusontheregionofarrayonwhichweareinterested.Example6.8:1.voidquickSelect(intarr[],intlower,intupper,intk)2.3.if(upper<=lower)4.return;5.6.intpivot=arr[lower];7.8.intstart=lower;9.intstop=upper;10.11.while(lower<upper)12.13.while(arr[lower]<=pivot)14.15.lower++;16.17.while(arr[upper]>pivot)18.19.upper--;20.21.if(lower<upper)22.23.swap(arr,upper,lower);24.25.26.27.swap(arr,upper,start);//upperisthepivotposition28.if(k<upper)29.quickSelect(arr,start,upper-1,k);//pivot-1istheupperforleftsubarray.30.if(k>upper)31.quickSelect(arr,upper+1,stop,k);//pivot+1isthelowerforrightsubarray.32.1.intquickSelect(int*a,intcount,intindex)2.3.quickSelect(a,0,count-1,index-1);4.returna[index-1];5.ComplexityAnalysis:

Page 166:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

WorstCaseTimeComplexity O(n2)BestCaseTimeComplexity O(logn)AverageTimeComplexity O(logn)SpaceComplexity O(nlogn)

Page 167:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BucketSortBucket sort is the simplest andmost efficient typeof sorting.Bucket sort has a strict requirementof apredefinedrangeofdata.Like,sorthowmanypeopleareinwhichagegroup.Weknowthattheageofpeoplecanvarybetween1and130.

Example6.9:1.voidBucketSort(intarray[],intn,intrange)2.3.inti,j;4.int*count=(int*)malloc(range*sizeof(int));5.6.for(i=0;i<range;i++)7.8.count[i]=0;9.10.11.for(i=0;i<n;i++)12.13.count[array[i]]++;14.15.16.j=0;17.18.for(i=0;i<range;i++)19.20.for(;count[i]>0;(count[i])--)21.22.array[j++]=i;23.24.25free(count);26Analysis:Line4:Wehavecreatedacountarraytostorecounts.Line6-9:countarrayelementsareinitializedtozero.

Page 168:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Line11-14:Indexcorrespondingtoinputarrayisincremented.Line:18-24:Finally,theinformationstoredincountarrayissavedinthearray.ComplexityAnalysis:Datastructure ArrayWorstcaseperformance O(n+k)Averagecaseperformance O(n+k)WorstcaseSpaceComplexity O(k)Wherek-isnumberofdistinctelements.n–isthetotalnumberofelementsinarray.

Page 169:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

GeneralizedBucketSortTherearecaseswhentheelementfallingintoabucketarenotuniquebutareinthesamerange.Whenwewanttosortanindexofaname,wecanusethepointerbuckettostorenames.

The buckets are already sorted and the elements inside each bucket can be kept sorted by using anInsertion-Sortalgorithm.Weareleavingthisgeneralizedbucketsortimplementationtothereaderofthisbook. The similar data structure will be defined in the coming chapter of Hash-Table using separatechaining.

Page 170:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Heap-SortHeap-SortwehavealreadystudiedintheHeapchapter.ComplexityAnalysis:Datastructure ArrayWorstcaseperformance O(nlogn)Averagecaseperformance O(nlogn)WorstcaseSpaceComplexity O(1)

Page 171:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TreeSortingIn-order traversalof thebinarysearchtreecanalsobeseenasasortingalgorithm.Wewillsee this inbinarysearchtreesectionoftreechapter.ComplexityAnalysis:WorstCaseTimeComplexity O(n2)BestCaseTimeComplexity O(nlogn)AverageTimeComplexity O(nlogn)SpaceComplexity O(n)StableSorting Yes

Page 172:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ExternalSort(ExternalMerge-Sort)Whendataneedtobesortedishuge.Moreover,itisnotpossibletoloaditcompletelyinmemory(RAM)forsuchadatasetweuseexternalsorting.Specificdata issortedusingexternalMerge-Sortalgorithm.Firstdataarepickedinchunksanditissortedinmemory.Thenthissorteddataiswrittenbacktodisk.Wholedata are sorted in chunksusingMerge-Sort.Nowweneed to combine these sorted chunks intofinalsorteddata.Thenwecreatequeuesforthedata,whichwillreadfromthesortedchunks.Eachchunkwillhaveitsownqueue.Wewillpopfromthisqueueandthesequeuesareresponsibleforreadingfromthesortedchunks.LetussupposewehaveKdifferentchunksofsorteddataeachoflengthM.ThethirdstepisusingaMin-Heap,whichwilltakeinputdatafromeachofthisqueue.Itwilltakeoneelement from each queue. The minimum value is taken from the Heap and added to the final sortedelementoutput.ThenqueuefromwhichthisminelementisinsertedintheheapwillagainpoppedandonemoreelementfromthatqueueisaddedtotheHeap.Finally,whenthedataisexhaustedfromsomequeuethatqueueisremovedfromtheinputlist.Finally,wewillgetasorteddatacameoutfromtheheap.Wecanoptimizethisprocessfurtherbyaddinganoutputbuffer,whichwillstoredatacomingoutofHeapandwilldoalimitednumberofthewriteoperationinthefinalDiskspace.

Note:Noonewillbeaskingtoimplementexternalsortinginaninterview,butitisgoodtoknowaboutit.

Page 173:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Comparisonsofthevarioussortingalgorithms.

Sort AverageTime BestTime WorstTime Space Stability

Bubble-Sort O(n2) O(n2) O(n2) O(1) Stable

ModifiedBubble-Sort O(n2) O(n) O(n2) O(1) Stable

Selection-Sort O(n2) O(n2) O(n2) O(1) Unstable

Insertion-Sort O(n2) O(n) O(n2) O(1) Stable

Heap-Sort O(n*log(n)) O(n*log(n)) O(n*log(n)) O(1) Unstable

Merge-Sort O(n*log(n)) O(n*log(n)) O(n*log(n)) O(n) Stable

Quick-Sort O(n*log(n)) O(n*log(n)) O(n2)O(n)worstcaseO(log(n))averagecase Unstable

BucketSort O(nk) O(nk) O(nk) O(nk) Stable

Page 174:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

SelectionofBestSortingAlgorithmNosortingalgorithmisperfect.Eachofthemhastheirownprosandcons.Letusreadonebyone:Quick-Sort:Whenyoudonotneedastablesortandaveragecaseperformancemattersmorethanworst-case performance.Whendata is random,weprefer theQuick-Sort.Average caseTimeComplexity ofQuick-Sort isO(nlogn)andworst-caseTimeComplexity isO(n2).SpaceComplexityofQuick-Sort isO(logn)auxiliarystorage,whichisstackspaceusedinrecursion.Merge-Sort:When you need a stable sort andTimeComplexity ofO(nlogn),Merge-Sort is used. Ingeneral,Merge-Sort is slower than Quick-Sort because of lot of copy happening in themerge phase.TherearetwousesofMerge-SortwhenwewanttomergetwosortedlinkedlistsandMerge-Sortisusedinexternalsorting.Heap-Sort:Whenyoudonotneedastablesortandyoucaremoreaboutworst-caseperformance thanaverage case performance. It has guaranteed to beO(nlogn) time complexity, and usesO(1) auxiliaryspace,meaningthatyouwillnotunpredictablyrunoutofmemoryonverylargeinputs.Insertion-Sort:Whenweneedastablesort,WhenNisguaranteedtobesmall,includingasthebasecaseofaQuick-SortorMerge-Sort.Worst-caseTimeComplexityisO(n2),ithasaverysmallconstant,soforsmaller input size it performs better thanMerge-Sort orQuick-Sort. It is also usefulwhen the data isalreadypre-sortedinthiscaseitsbestcaserunningtimeisO(N).Bubble-Sort:Whereweknow thedata is verynearly sorted.Sayonly twoelements areout of place.Theninonepass,BubbleSortwillmakethedatasortedandinthesecondpass,itwillseeeverythingissortedandthenexit.Onlytakes2passesofthearray.Selection-Sort:BestWorstAverageCaserunningtimeallO(n2).Itisonlyusefulwhenyouwanttodosomethingquick.Theycanbeusedwhenyouarejustdoingsomeprototyping.Counting-Sort:Whenyouaresortingdatawithinalimitedrange.Radix-Sort:Whenlog(N)issignificantlylargerthanK,whereKisthenumberofradixdigits.Bucket-Sort:Whenyourinputismoreorlessuniformlydistributed.Note:Astablesortisonethathasguaranteednottoreorderelementswithidenticalkeys.

Page 175:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise1.Givenatextfile,printthewordswiththeirfrequency.Nowprintthekthwordintermoffrequency.

Hint:·Firstapproachmaybeyoucanusethesortingandreturnthekthelement.·Secondapproach:Youcanusethekthelementquickselectalgorithm.·Thirdapproach:YoucanuseHashtableorTrietokeeptrackofthefrequency.UseHeaptogetthe

Kthelement2.GivenK input streams of number in sorted order.You need tomake a single output stream,which

containsall theelementsof theKstreamsinsortedorder.The inputstreamssupportReadNumber()operationandoutputstreamsupportWriteNumber()operation.Hint:·ReadthefirstnumberfromalltheKinputstreamsandaddthemtoaPriorityQueue.(Nodesshould

keeptrackoftheinputstream)·DequeueoneelementatatimefromPQ,Putthiselementvaluetotheoutputstream,Readtheinput

streamnumberandfromthesameinputstreamaddanotherelementtoPQ.·Ifthestreamisempty,justcontinue·RepeatuntilPQisempty.

3.GivenK sorted arrays of fixed lengthM.Also, given a final output array of lengthM*K.Give an

efficientalgorithmtomergeallthearraysintothefinalarray,withoutusinganyextraspace.Hint:youcanusetheendofthefinalarraytomakePQ.

4.Howwillyousort1PBnumbers?1PB=1000TB.5.Whatwillbethecomplexityoftheabovesolution?6.Anyotherimprovementonquestion3solutionifthenumberofcoresiseight.7.GivenanintegerarraythatsupportthreefunctionfindMin,findMax,findMedian.Sortthearray.8.Givenapileofpatient filesofHigh,midand lowpriority.Sort these files such thathigherpriority

comesfirst,thenmidandlastlowpriority.Hint:Bucketsort.

9.WriteprosandconsofHeap-Sort,Merge-SortandQuick-Sort.10.Givenarotated-sortedarrayofNintegers.(Thearraywassortedthenitwasrotatedsomearbitrary

numberoftimes.)Ifalltheelementsinthearraywereuniquethefindtheindexofsomevalue.Hint:Modifiedbinarysearch

11. In the problem9,what if there are repetitions allowed and you need to find the index of the first

occurrenceoftheelementintherotated-sortedarray.

Page 176:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

12.Mergetwosortedarraysintoasinglesortedarray.Hint:UsemergemethodofMerge-Sort.

13.Givenanarraycontain0’sand1’s,sortthearraysuchthatallthe0’scomebefore1’s.14.GivenanarrayofEnglishcharacters,sortthearrayinlineartime.15.Writeamethodtosortanarrayofstringssothatalltheanagramsarenexttoeachother.

·Loopthroughthearray.·Foreachword,sortthecharactersandaddittothehashmapwithkeysassortedwordandvalueas

theoriginalword.Attheendoftheloop,youwillgetallanagramsasthevaluetoakey(whichissortedbyitsconstituentchars).

·Iterateoverthehashmap,printallvaluesofakeytogetherandthenmovetothenextkey.SpaceComplexity:O(n),TimeComplexity:O(n)

Page 177:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 178:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER7:LINKEDLIST

Page 179:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionLetussupposewehaveanarraythatcontainsfollowingfiveelements1,2,4,5,6.Wewanttoinsertanelementwithvalue“3”inbetween“2”and“4”.Inthearray,wecannotdosoeasily.Weneedtocreateanotherarraythatislongenoughtostorethecurrentvaluesandonemorespacefor“3”.Thenweneedtocopy these elements in the new space. This copy operation is inefficient. To remove this fixed lengthconstraintlinkedlistisused.

Page 180:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

LinkedListThelinkedlistisalistofitems,callednodes.Nodeshavetwoparts,valuepartandlinkpart.Valuepartisused tostores thedata.Thevaluepartof thenodecanbeeitherabasicdata-type likean integerorsomeotherdata-typelikestructure.Thelinkpartisapointer,whichisusedtostoreaddressesofthenextelementinthelist.

Page 181:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TypesofLinkedlistTherearedifferenttypesoflinkedlists.Themaindifferenceamongthemishowtheirnodesrefertoeachother.

SinglyLinkedListEachnode(Exceptthelastnode)hasareferencetothenextnodeinthelinkedlist.Thelinkportionofnodecontainstheaddressofthenextnode.ThelinkportionofthelastnodecontainsthevalueNULL.

DoublyLinkedlistThenodeinthistypeoflinkedlisthasreferencetobothpreviousandthenextnodeinthelist.

CircularLinkedListThistypeissimilartothesinglylinkedlistexceptthatthelastelementpointstothefirstnodeofthelist.Thelinkportionofthelastnodecontainstheaddressofthefirstnode.

Thevariouspartsoflinkedlist1.Head:Headisapointerthatholdstheaddressofthefirstnodeinthelinkedlist.2.Nodes:Itemsinthelinkedlistarecallednodes.3.Value:Thedatathatisstoredineachnodeofthelinkedlist.4.Link:Linkpartofthenodeisusedtostoretheaddressofthenode.

a.Wewilluse“next”and“prev”tostoreaddressofnextorpreviousnode.

Page 182:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

SinglyLinkedList

LookatNodeinthisexample,itsvaluepartisoftypeint(itcanbeofsomeotherdata-type).Thelinkisnamedasnextinthebelowstructure.WehavetypedeftheNode*toNodePtrsothatourcodelooksclean.structNode

intvalue;Node*next;

;typedefNode*NodePtr;

Note:Forasinglylinked,weshouldalwaystestthesethreetestcasesbeforesayingthatthecodeisgoodtogo.Thisonenodeandzeronodecaseisusedtocatchboundarycases.Itisalwaystotakecareofthesecasesbeforesubmittingcodetothereviewer.

·Zeroelement/Emptylinkedlist.·Oneelement/Justsinglenodecase.·Generalcase.

Note:Anyprogramthatislikelytochangetheheadpointeristobepassedasadoublepointer.Basic operation of a linked list requires traversing a linked list. The various operations that we canperformonlinkedlists,manyoftheseoperationsrequirelisttraversal:

·Insertanelementinthelist,thisoperationisusedtocreatealinkedlist.·Printvariouselementsofthelist.·Searchanelementinthelist.·Deleteanelementfromthelist.·Reversealinkedlist.

YoucannotuseHeadtotraversealinkedlistbecauseifweusethehead,thenwelosethenodesofthelist.Wehavetouseanotherpointervariableofsamedata-typeasthehead.

InsertelementinlinkedlistAnelementcanbeinsertedintoalinkedlistinvariousorders.Someoftheexamplecasesarementionedbelow:

1.Insertionofanelementatthestartoflinkedlist

Page 183:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

2.Insertionofanelementattheendoflinkedlist3.Insertionofanelementatthe2ndpositioninlinkedlist4.Insertelementinsortedorderinlinkedlist

Example7.11.structNode2.intvalue;3.Node*next;4.;5.typedefNode*NodePtr;1.intInsertNode(NodePtr*ptrHead,intvalue)2.3.printf("InsertNode:%d",value);4.NodePtrtempPtr=(NodePtr)malloc(sizeof(Node));5.if(!tempPtr)6.return-1;7.tempPtr->value=value;8.tempPtr->next=*ptrHead;9.*ptrHead=tempPtr;10.return1;11.

Page 184:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Analysis:Line1:DoublepointerptrHeadispassedtothefunctionasargument,aswewanttoassignthenewnodetotheheadofthelinkedlist.Line3:Valuepassedasargumentisprintedtostandardoutput.Line4:MemoryisallocatedforthenewnodeofthelistandispointedbytrmpPtr.Line5-6:Hereitischeckedifthesystemisabletoallocatememoryifmalloc()succeededinallocatingmemory it returns theaddressof thatmemory location.Moreover, ifmalloc() fails toallocatememory,thenitreturnsNULL.Line7:ThevaluepassedasargumentisstoredinthememorypointedbytempPtrLine8:Thenewnodenextpointerwillpointtotheheadoftheoriginallist.Line9:Theheadof theoriginal listwillnowstartpointing to tempPtr.Therebyaddinganodeat thebeginningofthelinkedlistisdone.

TraversingLinkedListExample7.2:Printvariouselementsofalinkedlist1.voidPrintList(NodePtrhead)2.3.while(head)4.5.printf("value%d\n",head->value);6.head=head->next;7.8.Analysis:Line1:Thisfunctiontakestheheadofthelistasinputargument.Line3:Onthisline,wearecheckingiftheheadisnotNULL.Iftheheadisnotnullthenwhileblockwillexecute.Line5:Itprintsvaluestoredasthevalueofthecurrentnode.Line6:Atthisline,weareincrementingtheheadpointer,sothatitwillpointtothenextelementofthelinkedlist.

Completecodeforlistcreationandprintingthelist.Example7.3:1.intmain()2.3.NodePtrhead=NULL;4.intarr[5]=1,2,3,4,5;5.inti;6.for(i=0;i<5;i++)7.8.InsertNode(&head,arr[i]);

Page 185:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

9.10.return0;11.Analysis:Line3:Headpointerof the list is createdand it is assigned thevalueNULL.Headpointing toNULLmeansthelistisempty.Line4:Inthis,wehavecreatedanarrayof5elements.Theseelementswillbesortedinthelist.Line6-9:ValuestoredinarrayarestoredinlistbycallingInsertNodefunction.

InsertanelementattheendoflinkedlistgivenHeadpointerExample7.6:InsertanelementattheendoflinkedlistgivenHeadpointer1.intInsertAtEnd(NodePtr*ptrHead,intvalue)2.3.printf("insertelement%d\n",value);4.NodePtrhead=*ptrHead;5.NodePtrtempNode=(NodePtr)malloc(sizeof(Node));6.if(!tempNode)7.return-1;8.tempNode->value=value;9.tempNode->next=NULL;10.if(head==NULL)11.12.tempNode->next=*ptrHead;13.*ptrHead=tempNode;14.return1;15.16.while(head->next!=NULL)17.18.head=head->next;19.20.tempNode->next=head->next;21.head->next=tempNode;22.return1;23.Analysis:Line3-14:Newnodeiscreatedandthevalueisstoredinsideit.Ifthelistisempty,thenitwillbepointedbytheheadpointerptrHead.Line16-19:Willtraverseuntiltheendofthelist.Line20-21:Finally,newnodeisaddedtotheendofthelist.Note:Thisoperationisun-efficientaseachtimeyouwanttoinsertanelementyouhavetotraversetotheendofthelist.Therefore,thecomplexityofcreationofthelistisn2.Sohowtomakeitefficientwehave

Page 186:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

tokeep trackof the last elementbykeepinga tail pointer.Therefore, if it is required to always insertelementattheendoflinkedlist,sothatwewillkeeptrackofthetailpointeralso.

InsertionofanelementattheendInsertionofanelementattheendoflinkedlist(givenheadpointer,andtailpointer)

Example7.5:1.intInsertNode(NodePtr*ptrHead,NodePtr*ptrTail,intvalue)2.3.printf("InsertNode::%d",value);4.NodePtrtempPtr=(NodePtr)malloc(sizeof(Node));5.if(!tempPtr)6.return-1;7.tempPtr->value=value;8.tempPtr->next=NULL;

Page 187:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

9.if(*ptrHead==NULL)10.11.*ptrTail=*ptrHead=tempPtr;12.13.else14.15.NodePtrtail=*ptrTail;16.tail->next=tempPtr;17.*ptrTail=tempPtr;18.19.return1;20.Analysis:Line4-8:NewlinkedlistnodeiscreatedandthevaluestoredinsideitanditsnextpointstoNULL.Line9-12:Ifthelinkedlistisempty.ThenthenewnodewillbepointedbyptrTailandptrHead.Line15-17:Iflinkedlistisnotempty,thenlistptrHeadwillnotchange.OnlytheptrTailwillbechangedanditwillpointtothisnewnode.

SortedInsertInsertanelementinsortedorderinlinkedlistgivenHeadpointer

Example7.4:

Page 188:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

1.intSortedInsert(NodePtr*ptrHead,intvalue)2.3.NodePtrcurr=*ptrHead;4.NodePtrtempNode=(NodePtr)malloc(sizeof(Node));5.printf("Insertelement%d\n",value);6.if(!tempNode)7.return-1;8.tempNode->value=value;9.tempNode->next=NULL;10.if(curr==NULL||curr->value>value)11.12.tempNode->next=*ptrHead;13.*ptrHead=tempNode;14.return1;15.16.while(curr->next!=NULL&&17.curr->next->value<value)18.19.curr=curr->next;20.21.tempNode->next=curr->next;22.curr->next=tempNode;23.return1;24.Analysis:Line3:Headofthelistisstoredincurrpointer.Line4-9:Anewemptynodeofthelinkedlistiscreated.Itisinitializedbystoringanargumentvalueintoitsvalue.Nextofthenodewillpointtonull.Line10-15:Itchecksifthelistwasemptyorifthevaluestoredinthefirstnodeisgreaterthanthecurrentvalue.Thenthisnewcreatednodewillbeaddedtothestartofthelist.Line16-20:Weiteratethroughthelisttofindtheproperpositiontoinsertthenode.Line21-23:Finally,thenodewillbeaddedtothelist.

SearchElementinaLinked-ListSearchelementinlinkedlist.Givenaheadpointerandvalue.Returns1ifvaluefoundinlistelsereturns0.Searchinasinglelinkedlistcanbeonlydoneinonedirection.Sinceallelementsinthelisthasreferencetothenextiteminthelist.Therefore,traversaloflinkedlistislinearinnature.Example7.7:1.intSearchList(NodePtrhead,intvalue)2.

Page 189:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

3.while(head)4.5.If(head->value==value)6.7.printf(“Thevalueisfound”);8.return1;9.10.head=head->next;11.12.return0;13.Analysis:Line1:Wedonotneedtomodifythelistsopointertotheheadispassed(nodoublepointerneeded).Line3:Whileloopwilliteratethroughthelistandwill.Line5:Valueofeachelementoflistiscomparedwiththegivenvalueiffound,then“Thevalueisfound”willbeprintedtothescreen.Inaddition,functionwillreturn1.Line12:Ifthevalueisnotfound,then0willbereturnedfromthefunction.

Deleteelementfromthelinkedlist

DeleteFirstelementinalinkedlist.Example7.8:1.voidDeleteFirstNodes(NodePtr*ptrHead)2.

Page 190:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

3.printf("\nDeleteFirstNode\n");4.NodePtrtempNode=*ptrHead;5.if(tempNode==NULL)6.return;7.*ptrHead=tempNode->next;8.free(tempNode);9.Analysis:·Weneedtofindthesecondelementofthelistandassignitasheadofthelinkedlist.·Ifthelisthasatleastoneelement,itsfirstelementwillbedeletedandtheheadofthelistwillpointto

thesecondelement.

Deletenodefromthelinkedlistgivenitsvalue.

Example7.9:1.voidDeleteNode(NodePtr*ptrHead,intdelValue)2.3.printf("\nDeleteNode\n");4.NodePtrcurrNode=*ptrHead;5.NodePtrnextNode;

Page 191:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

6.7.if(currNode->value==delValue)/*firstnode*/8.9.*ptrHead=currNode->next;10.free(currNode);11.return;12.13.14.while(currNode!=NULL)15.16.nextNode=currNode->next;17.if(nextNode&&nextNode->value==delValue)18.19.currNode->next=nextNode->next;20.free(nextNode);21.return;22.23.else24.25.currNode=nextNode;26.27.28.Analysis:Line7-12:If thevaluestoredinfirstnodeisthevaluethatneedtodeleted,sotheheadofthelistwillchangesothiscaseishandledseparately.Else,innoothercaseheadoflinkedlistwillchange.Line14-27:Wetraversethelinklist inalooptofindthenodethatneedtobedeleted.WearekeepingnextNodeasthenextofcurrNode.WealwayscomparenextNodevaluewiththedelValueandcurrNode’snextpointerwillpointtothenextNode’snextpointer.ThennextNodeisthenodethatneedstobedeletedwhichisfinallyfreeatline20.

Deletealltheoccurrenceofparticularvalueinlinkedlist.Example7.10:1.voidDeleteNodes(NodePtr*ptrHead,intdelValue)2.3.printf("\nDeleteNode\n");4.NodePtrcurrNode=*ptrHead;5.NodePtrnextNode;6.NodePtrdelNode;7.8.while(currNode!=NULL&&currNode->value==delValue)/*firstnode*/

Page 192:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

9.10.*ptrHead=currNode->next;11.delNode=currNode;12.currNode=currNode->next;13.free(delNode);14.15.16.while(currNode!=NULL)17.18.nextNode=currNode->next;19.if(nextNode&&nextNode->value==delValue)20.21.currNode->next=nextNode->next;22.free(nextNode);23.24.else25.26.currNode=nextNode;27.28.29.Analysis:Line8-14:Whileloopwilldeleteallthenodesthatareatthefrontofthelist,whichhavevaluedequaltodelValue.Line 16-28: In this while loop, we will be deleting all the nodes that are having value equal to thedelValue.

DeletenodefromthelinkedlistgivenitspointerExample7.11:1.voidDeleteNodePtr(NodePtr*ptrHead,NodePtrptrDel)2.3.printf("\ndeleteNode\n");4.NodePtrcurrNode=*ptrHead;5.NodePtrnextNode;6.7.if(ptrDel==NULL)8.return;9.10.if(currNode==ptrDel)//firstnode11.12.*ptrHead=currNode->next;13.free(currNode);14.

Page 193:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

15.while(currNode!=NULL)16.17.nextNode=currNode->next;18.if(nextNode==ptrDel)//nodetobedeleated19.20.currNode->next=nextNode->next;21.free(nextNode);return;22.23.else24.25.currNode=nextNode;26.27.28.Analysis:Line10-14:Ifthenodethatneedtobedeletedisthefirstnode,thentheheadofthelinkedlistwillchangeandwillpointtothenextelementofthelinkedlist.Line15-27:Inthiswhile,loopthenodethatissupposedtobedeletedwillberemovedfromthelist.

DeleteasinglelinkedlistDeletealltheelementsofalinkedlist,givenapointertoheadoflinkedlist.Example7.12:1.voidDeleteList(NodePtr*ptrHead)2.3.printf("\nDeleteList\n");4.NodePtrdeleteMe=*ptrHead;5.NodePtrnextNode;6.while(deleteMe!=NULL)7.8.nextNode=deleteMe->next;9.free(deleteMe);10.deleteMe=nextNode;11.12.*ptrHead=NULL;13.Analysis:Line6-11:Inthiswhileloopeachnodeisdeletedonebyone.Untilwholelistisdeleted.Line12:InthislineheadoflinkedlistisassignedthevalueNULLtherebymakingthelistempty.

Reversealinkedlist.ReverseasinglylinkedListiterativelyusingthreePointers

Page 194:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example7.13:1.voidReverseList(NodePtr*ptrHead)2.3.NodePtrcurrNode=*ptrHead;4.NodePtrprevNode;5.NodePtrnextNode;6.if(!currNode)7.8.return;9.10.if(!currNode->next)11.12.return;13.14.prevNode=currNode;15.currNode=currNode->next;16.prevNode->next=NULL;17.while(tempNode)18.19.nextNode=currNode->next;20.currNode->next=prevNode;21.prevNode=currNode;22.currNode=nextNode;23.24.25.*ptrHead=prevNode;26.Analysis:Line17-24:Thelistisiterated.MakenextNodeequaltothenextnodeofthecurrNode.MakecurrNodenode’s next will point to prevNode. Then iterate the list bymaking prevNode point to currNode andcurrNodepointtonextNode.

RecursivelyReverseasinglylinkedListExample7.14:RecursivelyReversesinglylinkedListArgumentsarecurrentnodeanditsnextvalue.1.NodePtrreverseRecurseUtil(NodePtrcurrentNode,NodePtrnextNode)2.3.NodePtrret;4.if(!currentNode)5.returnNULL;6.7.if(!currentNode->next)

Page 195:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

8.9.currentNode->next=nextNode;10.returncurrentNode;11.12.13.ret=reverseRecurseUtil(currentNode->next,currentNode);14.currentNode->next=nextNode;15.16.returnret;17.18.19.voidreverseRecurse(NodePtr*ptrHead)20.21.*ptrHead=reverseRecurseUtil(*ptrHead,NULL);22.Analysis:Line19-22:reverseRecursefunctionwillcallareverseRecurseUtilfunctiontoreversethelistandthepointerreturnedbythereverseRecurseUtilwillbetheheadofthereversedlist.Line9&14:thecurrentnodewillpointtothenextNodethatispreviousnodeoftheoldlist.Note:Alinkedlistcanbereversedusingtwoapproachestheoneapproachisbyusingthreepointers.TheSecondapproachisusingrecursionbotharelinearsolution,butthree-pointersolutionismoreefficient.

RemoveduplicatesfromthelinkedlistRemove duplicate values from the linked list. The linked list is sorted and it contains some duplicatevalues, you need to remove those duplicate values. (You can create the required linked list usingSortedInsert()function)Example7.15:1.voidRemoveDuplicate(NodePtrhead)2.3.NodePtrdeleteMe;4.while(head)5.6.if((head->next)&&head->value==head->next->value)7.8.deleteMe=head->next;9.head->next=deleteMe->next;10.free(deleteMe);11.12.else13.14.head=head->next;15.

Page 196:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

16.17.Analysis:Line4-16:While loop isused to traverse the list.Whenever there isanodewhosevalue isequaltothenextnode’svalue,thatnodewillberemovedfromthelistanddeletethatnode.

CopyListReversedCopythecontentoflinkedlist inanotherlinkedlist inreverseorder.If theoriginallinkedlistcontainselementsinorder1,2,3,4,thenewlistshouldcontaintheelementsinorder4,3,2,1.Example7.16:1.voidCopyListReversed(NodePtrhead,NodePtr*ptrHead2)2.3.printf("copylist");4.NodePtrtempNode=NULL;5.NodePtrtempNode2=NULL;6.while(head)7.8.tempNode2=(NodePtr)malloc(sizeof(Node));9.tempNode2->value=head->value;10.tempNode2->next=tempNode;11.tempNode=tempNode2;12.head=head->next;13.14.*ptrHead2=tempNode;15.Analysis: Traverse the list and add the node’s value to the new list. Since the list is traversed in theforwarddirectionandeachnode’svalueisaddedtoanotherlistsotheformedlistisreverseofthegivenlist.

CopythecontentofgivenlinkedlistintoanotherlinkedlistCopythecontentofgivenlinkedlistintoanotherlinkedlist.Iftheoriginallinkedlistcontainselementsinorder1,2,3,4,thenewlistshouldcontaintheelementsinorder1,2,3,4.Example7.17:1.voidCopyList(NodePtrhead,NodePtr*ptrHead2)2.3.printf("copylist");4.NodePtrheadNode=NULL;5.NodePtrtailNode=NULL;6.NodePtrtempNode=NULL;7.

Page 197:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

8.if(head==NULL)9.return;10.headNode=(NodePtr)malloc(sizeof(Node));11.tailNode=headNode;12.headNode->value=head->value;13.headNode->next=NULL;14.head=head->next;15.16.while(head)17.18.tempNode=(NodePtr)malloc(sizeof(Node));19.tempNode->value=head->value;20.tempNode->next=NULL;21.tailNode->next=tempNode;22.tailNode=tailNode->next;23.head=head->next;24.25.*ptrHead2=headNode;26.Analysis:Traversethelistandaddthenode’svaluetonewlist,butthistimealwaysattheendofthelist.Sincethelististraversedintheforwarddirectionandeachnode’svalueisaddedtotheendofanotherlist.Therefore,theformedlistissameasthegivenlist.

CompareListExample7.18:1.intcompareList(NodePtrhead1,NodePtrhead2)2.3.printf("comparelist");4.if(head1==NULL&&head2==NULL)5.return1;6.elseif((head1==NULL)||(head2==NULL)||(head1->value!=head2->value))7.return0;8.else9.returncompareList(head1->next,head2->next);10.Analysis:Line4-5:List iscomparedrecursively.Moreover, ifwereach theendof the listandboth the listsarenull.Thenboththelistsareequalandsoreturn1.Line6-7:List is compared recursively. If eitheroneof the list is emptyor thevalueofcorrespondingnodesisunequal,thenthisfunctionwillreturn0.Line9:Recursivelycallscomparelistfunctionforthenextnodeofthecurrentnodes.

Page 198:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CompareListExample7.19:1.intcompareList2(NodePtrhead1,NodePtrhead2)2.3.while(head1!=NULL&&head2!=NULL)4.5.if(head1->value!=head2->value)6.return0;7.head1=head1->next;8.head2=head2->next;9.10.if(head1==head2)11.12.return1;13.14.else15.16.return0;17.18.Analysis:Line3-9:Boththelistsaretraverseduntilonelistisemptyortherevalueofthecorrespondingnodeisunequal.Line11-17:Ifboth the listarereachedto theend,whichmeansboth thelistareequalsoreturn1elsereturn0.

FindLengthExample7.20:Findthelengthofgivenlinkedlist.1.intfindLength(NodePtrhead)2.3.intcount=0;4.while(head)5.6.count++;7.head=head->next;8.9.returncount;10.Analysis:Lengthoflinkedlistisfoundbytraversingthelistuntilwereachtheendoflist.

NthNodefromBeginning

Page 199:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example7.21:1.NodePtrnthNodeFromBegining(NodePtrhead,intindex)2.3.intcount=0;4.while(head&&count<index-1)5.6.count++;7.head=head->next;8.9.10.if(head)11.returnhead;12.else13.returnNULL;14.Analysis:NthnodecanbefoundbytraversingthelistN-1numberoftimeandthenreturnthenodeifitisnotNULLelsereturnNULL.

NthNodefromEndExample7.22:1.NodePtrnthNodeFromEnd(NodePtrhead,intindex)2.3.intsize=findLength(head);4.intstartIndex;5.if(size&&size<index)6.7.printf("listdoesnothave%elements",index);8.returnNULL;9.10.startIndex=size-index+1;11.returnnthNodeFromBegining(head,startIndex);12.Analysis:First, find the lengthof list, thennthnode fromendwill be (length–nth+1)node from thebeginning.Example7.23:1.NodePtrnthNodeFromEnd(NodePtrhead,intindex)2.3.intcount=0;4.NodePtrtemp=NULL;5.NodePtrcurr=head;

Page 200:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

6.while(curr&&count<index-1)7.8.count++;9.curr=curr->next;10.11.12.if(!curr)13.returnNULL;14.15.temp=head;16.17.while(curr)18.19.temp=temp->next;20.curr=curr->next;21.22.returntemp;23.Analysis:SecondapproachistousetwopointersoneisNsteps/nodesaheadoftheotherwhenforwardpointerreachtheendofthelistthenthebackwardpointerwillpointtothedesirednode.Example7.241.NodePtrnthNodeFromEnd(NodePtrhead,intindex)2.3.staticintcount=0;4.NodePtrretval;5.6.if(!head)7.returnNULL;8.9.retval=nthNodeFromEnd3(head->next,index);10.if(retval)11.returnretval;12.13.count++;14.if(count==index)15.returnhead;16.else17.returnNULL;18.

LoopDetect1.Traversethroughthelist.

Page 201:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

2.IfthecurrentnodeisnotpresentintheHash-TabletheninsertitintotheHash-Table.3.Ifthecurrentnodeisalreadyinthehashtablethenwehavealoop.

LoopDetectWehavetofindifthereisaloopinthelinkedlist.Therearetwowaystofindifthereisaloopinalinkedlist.Onewayiscalled“Slowpointerandfastpointerapproach(SPFP)”theotheriscalled“Reverselistapproach”.Bothapproachesarelinearinnature,butstillinSPFPapproach,wedonotrequiretomodifythelinkedlistsoitispreferred.

Findifthereisaloopinalinkedlist.Ifthereisaloop,thenreturn1ifnot,thenreturn0.Useslowpointerfastpointerapproach.

Example7.25:1.intLoopDetect(NodePtrhead)2.3.printf("loopdetect");4.NodePtrslowPtr;5.NodePtrfastPtr;6.slowPtr=fastPtr=head;7.8.while(fastPtr->next&&fastPtr->next->next)9.10.slowPtr=slowPtr->next;11.fastPtr=fastPtr->next->next;

Page 202:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

12.if(slowPtr==fastPtr)13.14.return1;15.16.17.return0;18.Analysis:Line8-16:Thelististraversedwithtwopointers,oneisslowpointerandanotherisfastpointer.Slowpointer alwaysmovesone-step.Fastpointer alwaysmoves two steps. If there isno loop, thencontrolwillcomeoutofwhileloop.Soreturn0.Line12-15:Ifthereisaloop,thentherecameapointinaloopwherethefastpointerwillcomeandtrytopassslowpointer.Whenthispointarrives,wecometoknowthatthereisaloopinthelist.Soreturn1.

ReverseListLoopDetectFindifthereisaloopinalinkedlist.Ifthereisaloop,thenreturn1ifnot,thenreturn0.Usereverselistapproach.Example7.26:1.intReverseListLoopDetect(NodePtrhead)2.3.NodePtr*ptrHead=&head;4.NodePtrhead2=head;5.reverseList(ptrHead);6.if(*ptrHead==head2)7.8.reverseList(ptrHead);9.return1;10.11.else12.13.reverseList(ptrHead);14.return0;15.16.Analysis:Line5:reversethelistatthisline.Line6:comparethereversedlistheadpointertothecurrentlistheadpointer.Line8-9:Iftheheadofreversedlistandtheoriginallist,aresamethenreversethelistbackandreturn1.Line13-14:Iftheheadofthereversedlistandtheoriginallistarenotsamethenreversethelistbackandreturn0.Whichmeansthereisnoloop.

Page 203:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

LoopTypeDetectFindifthereisaloopinalinkedlist.Ifthereisnoloop,thenreturn0,ifthereisloopreturn1,ifthelistiscircularthen2.Useslowpointerfastpointerapproach.Example7.27:1.intLoopTypeDetect(NodePtrconsthead)2.3.printf("loopdetect");4.NodePtrslowPtr;5.NodePtrfastPtr;6.7.slowPtr=fastPtr=head;8.while(fastPtr->next&&fastPtr->next->next)9.10.11.slowPtr=slowPtr->next;12.fastPtr=fastPtr->next->next;13.14.if(head==fastPtr->next||head==fastPtr->next->next)15.16.return2;17.18.if(slowPtr==fastPtr)19.20.return1;21.22.23.return0;24.Analysis:ThisprogramissameastheloopdetectprogramexceptLine14-17.Line 14-17: If fast pointer reaches to the head of the list, then this means that there is a loop at thebeginningofthelist.

RemoveLoopExample7.28:1.voidRemoveLoop(NodePtr*ptrHead)2.3.intloopLength;4.NodePtrslowPtr,fastPtr,head;5.slowPtr=fastPtr=head=*ptrHead;

Page 204:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

6.NodePtrloopNode=NULL;7.while(fastPtr->next&&fastPtr->next->next)8.9.fastPtr=fastPtr->next->next;10.slowPtr=slowPtr->next;11.12.if(fastPtr==slowPtr||fastPtr->next==slowPtr)13.14.loopNode=slowPtr;15.break;16.17.18.if(loopNode)19.20.NodePtrtemp=loopNode->next;21.loopLength=1;22.while(temp!=loopNode)23.24.loopLength++;25.temp=temp->next;26.27.temp=head;28.NodePtrbreakNode=head;29.30.for(inti=1;i<loopLength;i++)31.32.breakNode=breakNode->next;33.34.35.while(temp!=breakNode->next)36.37.temp=temp->next;38.breakNode=breakNode->next;39.40.breakNode->next=NULL;41.42.Analysis:Loopthroughthelistbytwopointer,onefastpointerandoneslowpointer.Fastpointerjumpstwonodesat a time and slowpointer jump one node at a time.The pointwhere these two pointer intersect is apointerintheloop.Thensincewehaveapointerinaloop,wecanfindthelengthoftheloop.TakeapointerbreakNodethatpoint to theheadof the linkedlist. Increment the listbylooplengthand

Page 205:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

then increment theheadandbreakNodepointeruntilbothareequal.WhenyouhaveabreakNode thenassignitsnexttoNULL.Thereisonemoresolutionpossibletofindthebreakpoint.Thepointwhereslowpointerandfastpointermeets in loop,call it looppoint.Startonepointer fromheadandother fromlooppoint incrementbothone-stepata time theywillmeetat the looppoint.Mark thenextof looppointnullandyouaredone.(Thiscanbeprovedmathematically)

FindIntersection

Example7.29:1.NodePtrfindIntersection(NodePtrhead,NodePtrhead2)2.3.intl1=0;4.intl2=0;5.NodePtrtempHead=head;6.NodePtrtempHead2=head2;7.8.while(tempHead)9.10.l1++;11.tempHead=tempHead->next;12.13.while(tempHead2)14.15.l2++;16.tempHead2=tempHead2->next;17.18.19.intdiff;20.if(l1<12)21.22.NodePtrtemp=head;23.head=head2;24.head2=temp;25.diff=l2-l1;26.27.else28.

Page 206:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

29.diff=l1-l2;30.31.32.for(;diff>0;diff--)33.34.head=head->next;35.36.while(head!=head2)37.38.head=head->next;39.head2=head2->next;40.41.42.returnhead;43.Analysis:Findlengthofboththelists.Findthedifferenceoflengthofboththelists.Incrementthelongerlistbydiffsteps,thenincrementboththelistsandgettheintersectionpoint.

Page 207:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DoublyLinkedListInaDoublyLinkedlist,therearetwopointersineachnode.Thesepointersarecalledprevandnext.Theprevpointerofthenodewillpointtothenodebeforeitandthenextpointerwillpointtothenodenexttothegivennode.

LetuslookatNodeinthisexamplethevalueisoftypeint,butitcanbeofsomeotherdata-type.Thetwolinkpointersareprevandnext.WehavetypedeftheNode*toNodePtrsothatourcodelooksclean.structNode

intvalue;structNode*next;structNode*prev;

;typedefNode*NodePtr;

Searchinasinglelinkedlistcanbeonlydoneinonedirection.Sinceallelementsinthelisthasreferencetothenextiteminthelist.Therefore,traversaloflinkedlistislinearinnature.Inadoublylinkedlist,wekeeptrackofbothheadofthelinkedlistandtailoflinkedlist.Note:Foradoublylinkedlist,fewcasesneedtokeepinmindwhilecoding:

·Zeroelementcase(headandtailbothcanbemodified)·Onlyelementcase(headandtailbothcanbemodified)·Firstelement(headcanbemodified)·Generalcase·Thelastelement(tailcanbemodified)

Note:Anyprogramthatislikelytochangeheadpointerortailpointeristobepassedasadoublepointer,whichispointingtoheadortailpointer.

TraversingLinkedList

Page 208:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Basic operation of a linked list requires traversing a linked list. The various operations that we canperformonlinkedlists,manyoftheseoperationsrequirelisttraversal:

·Insertanelementinthelist,thisoperationisusedtocreatealinkedlist.·Printvariouselementsofthelist.·Searchanelementinthelist.·Deleteanelementfromthelist.·Reversealinkedlist.

YoucannotuseHeadtotraversealinkedlistbecauseifweusethehead,thenwelosethenodesofthelist.Wehavetouseanotherpointervariableofsamedata-typeasthehead.Thelisttraversalcodeismentionednext.NodePtrcurrent=head;while(current!=NULL)

/*Processcurrentnode*/current=current->next;

Foranylinkedlistthereareonlythreecaseszeroelement,oneelement,andgenerallyAnyprogramthatislikelytochangetheheadpointeristobepassedadoublepointerFordoublylinkedlist,wehaveafewmorethings1.NULLvalues(headandtailbothcanbemodified)2.Onlyelement(headandtailbothcanbemodified)3.Firstelement(headcanbemodified)4.Generalcase5.Lastelement(tailcanbemodified)

Page 209:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

1.structNode2.intvalue;3.structNode*next;4.structNode*prev;5.;6.typedefNode*NodePtr;

InsertNodeExample7.30:1./*INSERTVALUEINFRONT*/2.intinsertNode(NodePtr*ptrHead,NodePtr*ptrTail,intvalue)3.4.printf("\nINSERTNODE\n");5.NodePtrtemp=(NodePtr)malloc(sizeof(Node));6.if(!temp)7.return0;8.NodePtrhead=*ptrHead;9.if(!head)10.11.temp->value=value;12.temp->next=NULL;13.temp->prev=NULL;14.*ptrTail=temp;15.*ptrHead=temp;16.17.else18.19.temp->value=value;20.temp->next=head;21.temp->prev=NULL;22.head->prev=temp;23.*ptrHead=temp;24.25.return1;26.Analysis:Insertindoublelinkedlistissameasinsertinasinglylinkedlist.CreateanodeassignNULLtoprevpointerofthenode.Thenpointnexttothestartofthelist.IfthelistisemptythenptrTailwillpoint

Page 210:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

tothenode.

SortedInsertDecreasing

Example7.31:1.//SORTEDINSERTDECREASING2.intsortedInsert(NodePtr*ptrHead,NodePtr*ptrTail,intvalue)3.4.printf("\nsortedinsert\n");5.NodePtrtemp=(NodePtr)malloc(sizeof(Node));6.if(!temp)7.return0;8.temp->value=value;9.NodePtrhead=*ptrHead;10.if(!head)//firstelement11.12.temp->next=NULL;13.temp->prev=NULL;14.*ptrHead=temp;15.*ptrTail=temp;16.return1;17.18.if(head->value<=value)//atthebegining19.

Page 211:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

20.temp->next=head;21.temp->prev=NULL;22.head->prev=temp;23.*ptrHead=temp;24.return1;25.26.while(head->next&&head->next->value>value)//treversal27.28.head=head->next;29.30.if(!head->next)//attheend31.32.*ptrTail=temp;33.temp->next=NULL;34.temp->prev=head;35.head->next=temp;36.37.else///allother38.39.temp->next=head->next;40.temp->prev=head;41.head->next=temp;42.temp->next->prev=temp;43.44.return1;45.Analysis:Findtheproperlocationofthenodeandaddittothelist.Managenextandprevpointerofthenodesothatlistalwaysremaindoublelinkedlist.Example7.32:1./*2.PrintAsinglylinkedlist3.*/4.voidprintList(NodePtrhead)5.6.printf("Listis::");7.while(head!=NULL)8.9.printf("%d",head->value);10.head=head->next;11.12.printf("\n");13.

Page 212:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Analysis:Printlistissameasjusttraversingthelistandprintingthevaluesofthenodes.

ReverseadoublylinkedListiterativelyExample7.33:1./*2.ReverseadoublylinkedListiteratively3.*/4.5.voidreverseList(Node**ptrHead,Node**ptrTail)6.7.NodePtrhead=*ptrHead;8.NodePtrtempNode;9.while(head)10.11.tempNode=head->next;12.head->next=head->prev;13.head->prev=tempNode;14.if(!head->prev)15.16.*ptrTail=*ptrHead;17.*ptrHead=head;18.return;19.20.head=head->prev;21.22.return;23.Analysis:Traversethelistandswapnextandprevpointerofeachnode.WhenyouhavereachedtotheendofthelistswapptrTailandptrHeadpointers.Example7.34:Deleteasinglylinkedlist1.voiddeleteList(NodePtr*ptrHead,NodePtr*ptrTail)2.3.printf("\ndeleteList\n");4.NodePtrdeleteMe=*ptrHead;5.NodePtrnextNode;6.while(deleteMe!=NULL)7.8.nextNode=deleteMe->next;9.free(deleteMe);10.deleteMe=nextNode;11.

Page 213:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

12.*ptrTail=ptrHead=NULL;13.Analysis:Traversethelistanddeleteeachnodeofthelistonebyone.

Deleteanodegivenitspointer

Example7.35:1.voiddeleteNodePtr(NodePtr*ptrHead,NodePtr*ptrTail,NodePtrptrDel)2.3.printf("\ndeleteNode\n");4.NodePtrcurrNode=*ptrHead;5.NodePtrnextNode;6.7.if(ptrDel==NULL||currNode==NULL)8.return;9.10.if(currNode==ptrDel)//firstnode11.12.deleteMe=currNode;

Page 214:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

13.currNode=currNode->next;14.free(deleteMe);15.*ptrHead=currNode;16.if(currNode)17.currNode->prev=NULL;18.else19.*ptrTail=NULL;20.return;21.22.while(currNode!=NULL)23.24.nextNode=currNode->next;25.if(nextNode==ptrDel)//nodetobedeleated26.27.currNode->next=nextNode->next;28.nextNode->next->prev=currNode;29.if(nextNode==*ptrTail)30.*ptrTail=nextNode->prev;//lastnode31.free(nextNode);32.33.else34.35.currNode=nextNode;36.37.38.Analysis:Traversethelistfindthenodethatneedtobedeleted.Thenremoveitandadjustnextpointerofthenodebeforeitandprevpointerofthenodenexttoit.

RemoveDuplicateExample7.36:1./*RemoveDuplicate*/2.voidremoveDuplicate(Node*head)3.4.NodePtrdeleteMe;5.while(head)6.7.if((head->next)&&head->value==head->next->value)8.9.deleteMe=head->next;10.head->next=deleteMe->next;11.head->next->prev=head;12.if(deleteMe==tail)13.

Page 215:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

14.tail=curr;15.16.free(deleteMe);17.18.else19.20.head=head->next;21.22.23.Analysis:Removeduplicate is same as single linked list case.Consider the list as sorted remove therepeatedvaluenodesofthelist.

CopyListReversedExample7.37:1.voidcopyListReversed(NodePtrhead,NodePtr*ptrHead2)2.3.printf("copylist");4.NodePtrtempNode=NULL;5.NodePtrtempNode2=NULL;6.while(head)7.8.tempNode2=(NodePtr)malloc(sizeof(Node));9.tempNode2->value=head->value;10.tempNode2->next=tempNode;11.tempNode2->prev=NULL;12.tempNode->prev=tempNode2;13.tempNode=tempNode2;14.head=head->next;15.16.*ptrHead2=tempNode;17.Analysis:Traversethroughthelistandcopythevalueofthenodesintoanotherlist.Alwaysaddthenextnodevaluetothestartofthenewlisttherebyformingareversedlist.

CopyListExample7.38:1.voidcopyList(NodePtrhead,NodePtr*ptrHead2)2.3.printf("copylist");4.NodePtrheadNode=NULL;

Page 216:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

5.NodePtrtailNode=NULL;6.NodePtrtempNode=NULL;7.if(head==NULL)8.return;9.headNode=(NodePtr)malloc(sizeof(Node));10.tailNode=headNode;11.headNode->value=head->value;12.headNode->next=NULL;13.headNode->prev=NULL;14.head=head->next;15.while(head)16.17.tempNode=(NodePtr)malloc(sizeof(Node));18.tempNode->value=head->value;19.tempNode->next=NULL;20.tailNode->next=tempNode;21.tempNode->prev=tailNode;22.tailNode=tailNode->next;23.head=head->next;24.25.*ptrHead2=headNode;26.Analysis:Traversethelist,valueofthenodesareaddedtoanotherlistalwaysattheend.Usetailpointertokeeptrackoftheendofthenewlist.

Page 217:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CircularLinkedListThistypeissimilartothesinglylinkedlistexceptthatthelastelementpointstothefirstnodeofthelist.Thelinkportionofthelastnodecontainstheaddressofthefirstnode.

typedefstructNodeintvalue;structNode*next;

Node_t;typedefNode_t*NodePtr;

Insertelementinfront

Page 218:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example7.39:1./*Insertelementinfront*/2.intinsertNodeAtFront(NodePtr*ptrHead,NodePtr*ptrTail,intvalue)3.4.printf("\nINSERTNODEATFRONT\n");5.NodePtrtemp=(NodePtr)malloc(sizeof(Node_t));6.if(!temp)7.return0;8.temp->value=value;9.NodePtrhead=*ptrHead;10.NodePtrtail=*ptrTail;11.if(!head)12.13.temp->next=temp;14.*ptrTail=temp;15.*ptrHead=temp;16.17.else18.19.temp->next=head;20.tail->next=temp;21.*ptrHead=temp;22.23.return1;24.Analysis:Line11-16:Whenthelistisempty,thenodeiscreated.Headandtailispointingtothisnode.Line17-22:Newnodeiscreateditsnextwillpoint toheadandheadwillpoint tothisnewnode.Tailnodesnextwillpointtothenewnode.

InsertelementattheendExample7.40:1./*Insertelementattheend*/2.intinsertNodeAtEnd(NodePtr*ptrHead,NodePtr*ptrTail,intvalue)

Page 219:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

3.4.printf("\nINSERTNODEATEND\n");5.NodePtrtemp=(NodePtr)malloc(sizeof(Node_t));6.if(!temp)7.return0;8.temp->value=value;9.NodePtrhead=*ptrHead;10.NodePtrtail=*ptrTail;11.if(!head)12.13.temp->next=temp;14.*ptrTail=temp;15.*ptrHead=temp;16.17.else18.19.temp->next=head;20.tail->next=temp;21.*ptrTail=temp;22.23.return1;24.Analysis:Addingnodeattheendissameasaddingatthebeginning.Justneedtomodifytailpointerinplaceoftheheadpointer.

PrintListExample7.41:1./*PrintAsinglylinkedlist*/2.voidprintList(NodePtrhead)3.4.printf("LISTIS::");5.NodePtrcurrNode=head;6.if(currNode!=NULL)7.8.printf("%d",currNode->value);9.currNode=currNode->next;10.11.while(currNode!=head)12.13.printf("%d",currNode->value);14.currNode=currNode->next;15.16.

Page 220:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Analysis:Incircularlist,endoflistisnottheresowecannotcheckwithNULL.InplaceofNULLheadisusedtocheckendofthelist.

DeleteListExample7.42:1./*Deleteacircularlinkedlist*/2.voiddeleteList(NodePtr*ptrHead)3.4.printf("\nDELETELIST\n");5.NodePtrconsthead=*ptrHead;6.NodePtrcurrNode=*ptrHead;7.NodePtrnextNode;8.if(currNode!=NULL)9.10.nextNode=currNode->next;11.free(currNode);12.currNode=nextNode;13.14.while(currNode!=head)15.16.nextNode=currNode->next;17.free(currNode);18.currNode=nextNode;19.20.*ptrHead=NULL;21.Analysis:Traversethroughthelistanddeletenodesuntilyoureachthestartofthelist.

Deleteanodegivenitspointer

Page 221:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example7.43:1./*Deleteanodegivenitspointer*/2.voiddeleteNodePtr(NodePtr*ptrHead,NodePtr*ptrTail,NodePtrptrDel)3.4.printf("\nDELETENODEGIVENITSPOINTER\n");5.if(ptrDel==NULL||ptrHead==NULL||ptrTail==NULL)6.return;7.NodePtrhead=*ptrHead;8.NodePtrtail=*ptrTail;9.NodePtrcurrNode=head;10.NodePtrprevNode;11.if(head==NULL||tail==NULL)12.return;13.if(currNode==ptrDel)/*oneelementandfirstelementcase*/14.15.if(currNode->next==currNode)16.17.*ptrHead=NULL;18.*ptrTail=NULL;19.free(currNode);20.return;21.22.else23.24.*ptrHead=currNode->next;25.tail->next=currNode->next;26.free(currNode);27.return;28.29.

Page 222:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

30.prevNode=currNode;31.currNode=currNode->next;32.while(currNode!=head)33.34.if(currNode==ptrDel)35.36.if(currNode==tail)/*tailchangecase*/37.*ptrTail=prevNode;38.prevNode->next=currNode->next;39.free(currNode);40.return;41.42.prevNode=currNode;43.currNode=currNode->next;44.45.Analysis:Findthenodethatneedtofree.Onlydifference is thatwhile traversingthe listendof list istrackedbytheheadpointerinplaceofNULL.

DeleteanodegivenitsvalueExample7.44:1./*Deleteanodegivenitsvalue*/2.voiddeleteNodeValue(NodePtr*ptrHead,NodePtr*ptrTail,intvalue)3.4.printf("\nDELETENODEGIVENITSVALUE\n");5.if(ptrHead==NULL||ptrTail==NULL)6.return;7.NodePtrhead=*ptrHead;8.NodePtrtail=*ptrTail;9.NodePtrcurrNode=head;10.NodePtrprevNode;11.if(head==NULL||tail==NULL)12.return;13.if(currNode->value==value)/*oneelementandfirstelementcase*/14.15.if(currNode->next==currNode)16.17.*ptrHead=NULL;18.*ptrTail=NULL;19.free(currNode);20.return;21.22.else

Page 223:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

23.24.*ptrHead=currNode->next;25.tail->next=currNode->next;26.free(currNode);27.return;28.29.30.prevNode=currNode;31.currNode=currNode->next;32.while(currNode!=head)33.34.if(currNode->value==value)35.36.if(currNode==tail)/*tailchangecase*/37.*ptrTail=prevNode;38.prevNode->next=currNode->next;39.free(currNode);40.return;41.42.prevNode=currNode;43.currNode=currNode->next;44.45.Analysis:Findthenodethatneedtofree.Onlydifference is thatwhile traversingthe listendof list istrackedbytheheadpointerinplaceofNULL.

RemoveDuplicateExample7.45:1./*RemoveDuplicate*/2.voidremoveDuplicate(NodePtr*ptrHead,NodePtr*ptrTail)3.4.printf("\nRemoveDuplicate\n");5.NodePtrhead=*ptrHead;6.NodePtrcurrent=head;7.NodePtrdeleteMe;8.if(!head)9.return;10.while(current->next!=head)11.12.if(current->value==current->next->value)13.14.deleteMe=current->next;15.current->next=deleteMe->next;

Page 224:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

16.if(deleteMe==*ptrTail)17.18.*ptrTail=current;19.20.free(deleteMe);21.22.else23.24.current=current->next;25.26.27.Analysis:Consideringthelistissorted,repeatedvaluenodeswouldberemoved.OnlydifferenceisthatwhiletraversingthelistendofthetraversalisnotcheckedwithNULLitischeckedbyheadpointer.

CopyListReversedExample7.46:1./*CopyList*/2.voidcopyListReversed(NodePtrhead,NodePtr*newPtrHead,NodePtr*newPtrTail)3.4.printf("\nCOPYLISTREVERSED\n");5.NodePtrcurr=head;6.if(curr)7.8.insertNodeAtFront(newPtrHead,newPtrTail,curr->value);9.curr=curr->next;10.11.while(curr!=head)12.13.insertNodeAtFront(newPtrHead,newPtrTail,curr->value);14.curr=curr->next;15.16.Analysis:Thelististraversedandnodesareaddedtonewlistatthebeginning.Therebymakingthenewlistreverseofthegivenlist.

CopyListExample7.47:1.voidcopyList(NodePtrhead,NodePtr*newPtrHead,NodePtr*newPtrTail)2.3.printf("\nCOPYLIST\n");4.NodePtrcurr=head;

Page 225:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

5.if(curr)6.7.insertNodeAtEnd(newPtrHead,newPtrTail,curr->value);8.curr=curr->next;9.10.while(curr!=head)11.12.insertNodeAtEnd(newPtrHead,newPtrTail,curr->value);13.curr=curr->next;14.15.Analysis:Lististraversedandnodesareaddedtothenewlistattheend.Therebymakingthelistwhosevaluearesameastheinputlist.

Page 226:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DoublyCircularlist1.Foranylinkedlistthereareonlythreecaseszeroelement,oneelement,generalcase2.Anyprogramwhichislikelytochangetheheadpointeristobepassedadoublepointer3.Todoublylinkedlistwehaveafewmorethings

a)NULLvaluesb)Onlyelement(itgenerallyintroducesanifstatementwithnull)c)Alwaysan“if”before“while”.Whichwillcheckfromthishead.d)Generalcase(checkwiththeinitialheadkept)e)Avoidusingrecursionsolutionsitmakeslifeharder

STLimplementlistusingadoublecircularlist.

InsertNodeExample7.48:Insertvalueatthefrontofthelist.1.#include<stdio.h>2.#include<stdlib.h>3.4.structNode5.intvalue;6.structNode*next;7.structNode*prev;8.;9.typedefNode*NodePtr;10.11.//Insertvalueinfront12.intinsertNode(NodePtr*ptrHead,intvalue)13.14.printf("\nINSERTNODE\n");15.NodePtrtemp=(NodePtr)malloc(sizeof(Node));16.if(!temp)17.return0;18.NodePtrhead=*ptrHead;19.if(!head)20.21.temp->value=value;22.temp->next=temp;23.temp->prev=temp;24.*ptrHead=temp;

Page 227:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

25.26.else27.28.temp->value=value;29.temp->next=head;30.temp->prev=head->prev;31.temp->prev->next=temp32.head->prev=temp;33.*ptrHead=temp;34.35.return1;36.

DeleteNodePtrExample7.49:1./*2.Deleteanodegivenitspointer3.*/4.5.voiddeleteNodePtr(NodePtr*ptrHead,NodePtrptrDel)6.7.printf("\ndeleteNode\n");8.NodePtrcurrNode=*ptrHead;9.NodePtrhead=*ptrHead;10.NodePtrnextNode,prevNode;11.12.if(ptrDel==NULL||!(*ptrHead))13.return;14.15.if(currNode==ptrDel)//firstnode16.17.if(currNode->next==currNode)//onlynode18.19.*ptrHead=NULL;20.free(currNode);21.return;22.23.else24.25.prevNode=currNode->prev;26.*ptrHead=nextNode=currNode->next;27.prevNode->next=nextNode;28.nextNode->prev=prevNode;29.return;

Page 228:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

30.31.32.currNode=currNode->next;33.while(currNode!=head)34.35.if(currNode==ptrDel)36.37.prevNode=currNode->prev;38.nextNode=currNode->next;39.prevNode->next=nextNode;40.nextNode->prev=prevNode;41.free(currNode);42.return;43.44.currNode=currNode->next;45.46.Analysis:Deletenodeinadoublycircularlinkedlistisjustsameasdeletenodeinacircularlinkedlist.Justfewextraprevpointerneedtobeadjusted.

RemoveDuplicateExample7.50:1.voidremoveDuplicate(NodePtrhead)2.3.NodePtrdeleteMe;4.NodePtrconsttagHead=head;5.6.if(!head)7.return;8.9.head=head->next;10.11.while(head!=tagHead)12.13.if(head==head->next)//thischeckistopreventonlyonenodetobedeleted14.break;15.if((head->next)&&head->value==head->next->value)16.17.deleteMe=head->next;18.head->next=deleteMe->next;19.head->next->prev=head;20.free(deleteMe);21.

Page 229:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

22.else23.24.//checkfortail25.head=head->next;26.27.28.Analysis:Removeduplicate is sameas removeduplicate in a circular linked list. Just onemoreprevpointerneedtobeadjusted.

CopyListReversedExample7.51:1.voidcopyListReversed(NodePtrhead,NodePtr*ptrHead2)2.3.printf("copylist");4.NodePtrtempNode=NULL;5.NodePtrtempNode2=NULL;6.NodePtrconsthead2=head;7.8.if(head)9.10.tempNode2=(NodePtr)malloc(sizeof(Node));11.tempNode2->value=head->value;12.tempNode2->next=tempNode;13.tempNode2->prev=NULL;14.tempNode=tempNode2;15.head=head->next;16.17.18.while(head!=head2)19.20.tempNode2=(NodePtr)malloc(sizeof(Node));21.tempNode2->value=head->value;22.tempNode2->next=tempNode;23.tempNode2->prev=NULL;24.tempNode=tempNode2;25.head=head->next;26.27.*ptrHead2=tempNode;28.Analysis:Copylistissimilartocopylistinacircularlist.Justprevpointeralsoneedtobeadjusted.

Page 230:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CopyListExample7.52:1.voidcopyList(NodePtrhead,NodePtr*ptrHead2)2.3.printf("copylist");4.NodePtrheadNode=NULL5.NodePtrtempNode=NULL;6.NodePtrconsttagHead=head;7.NodePtrtailNode;8.9.if(head==NULL)10.return;11.12.tailNode=headNode=(NodePtr)malloc(sizeof(Node));13.headNode->value=head->value;14.headNode->next=headNode;15.headNode->prev=headNode;16.head=head->next;17.18.while(head!=tagHead)19.20.tempNode=(NodePtr)malloc(sizeof(Node));21.tempNode->value=head->value;22.tailNode->next=tempNode;23.tempNode->prev=tailNode;24.tempNode->next=headNode;25.headNode->prev=tempNode;26.head=head->next;27.28.*ptrHead2=headNode;29.Analysis:Copylistissimilartocopylistinacircularlist.Justprevpointeralsoneedtobeadjusted.

Page 231:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise

1) Insertanelementkth position from the startof linked list.Return1 if successand if list isnot longenough,thenreturn-1.Hint:TakeapointeradvanceitKstepsforward,theninsertsthenode.

2) Insert an element kth position from the endof linked list.Return1 if success and if list is not long

enough,thenreturn-1.Hint:TakeapointeradvanceitKstepsforward,thentakeanotherpointerandadvancebothofthemsimultaneously,sothatwhenthefirstpointerreachtheendofalinkedlistthatisthepointwhereyouneedtoinsertthenode.

3)Considerthereisaloopinalinkedlist,Writeaprogramtoremoveloopifthereisaloopinthislinked

list.4)IntheaboveSearchListprogramreturn,thecountofhowmanyinstancesofsamevaluefoundelseif

valuenot found then return 0.For example, if the value passed is “4”.The elements in the list are1,2,4,3&4.Theprogramshouldreturn2.Hint:Inplaceofreturn1intheaboveprogramincrementacounterandthenreturncounterattheend.

5) Given two linked list head, pointer and they meet at some point and need to find the point of

intersection.However,inplaceoftheendofboththelinkedlisttobeanullpointerthereisaloop.

6)Iflinkedlisthavingaloopisgiven.Countthenumberofnodesinthelinkedlist7)WeweresupposedtowritethecompletecodefortheadditionofpolynomialsusingLinkedLists.8)Giventwolinkedlists.Wehavetofindthatwhetherthedatainoneisreversethatofdatainanother.

Noextraspaceshouldbeusedandtraversethelinkedlistsonlyonce.9)Findthemiddleelementinasinglylinkedlist.Tellthecomplexityofyoursolution.

Hint:-·Approach1:findthelengthoflinkedlist.Thenfindthemiddleelementandreturnit.·Approach2: use two pointer onewillmove fast and onewillmove slowmake sure you handle

bordercaseproperly.(Evenlengthandoddlengthlinkedlistcases.)10)Printlistinreverseorder.

Hint:Userecursion.

Page 232:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 233:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER8:STACK

Page 234:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionA stack is a basic data structure that organized items in last-in-first-out (LIFO)manner. Last elementinsertedinastackwillbethefirsttoberemovedfromit.Thereal-lifeanalogyofthestackis"chapattisinhotpot","stackofplates".Imagineastackofplatesinadiningareaeverybodytakesaplateatthetopofthestack,therebyuncoveringthenextplateforthenextperson.Stackallowtoonlyaccessthetopelement.Theelementsthatareatthebottomofthestackaretheonethatisgoingtostayinthestackforthelongesttime.

Computersciencealsohas thecommonexampleofastack.Functioncallstack isagoodexampleofastack. Function main() calls function foo() and then foo() calls bar(). These function calls areimplementedusingstackfirstbar()exists,thengo()andthenfinallymain().Aswenavigatefromwebpagetowebpage,theURLofwebpagesarekeptinastack,withthecurrentpageURLatthetop.Ifweclickbackbutton,theneachURLentryispoppedonebyone.

Page 235:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TheStackAbstractDataTypeStackabstractdatatypeisdefinedasastructure,whichfollowsLIFOorlast-in-first-outfortheelements,addedtoit.Thestackshouldsupportthefollowingoperation:

1.Push():whichaddasingleelementatthetopofthestack2.Pop():whichremoveasingleelementfromthetopofastack.3.Top():Readsthevalueofthetopelementofthestack(doesnotremoveit)4.isEmpty():Returns1ifstackisempty5.Size():returnsthenumberofelementsinastack.

voidpush(intn);Addntothetopofastack.intpop();Removethetopelementofthestackandreturnittothecallerfunction.Thestackcanbeimplementedusinganarrayoralinkedlist.Inarraycase,therearetwotypesofimplementations

·Oneinwhicharraysizeisfixed,soitthecapacityofthestack.·Anotherapproachisvariablesizearrayinwhichmemoryofthearrayisallocatedusingmallocand

whenthearrayisfilledthesizeifdoubledusingrealloc(whenthestacksizedecreasesbelowhalfthecapacityisagainreducedusingrealloc).

Page 236:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Incaseofalinkedlist,thereisnolimitofnumberofelements.Whenastackisimplemented,usinganarraytopofthestackismanagedusinganindexvariablecalledtop.Whenastackisimplementedusingalinkedlist,push()andpop()isimplementedusinginsertattheheadofthelinkedlistandremovefromtheheadofthelinkedlist.

Page 237:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

StackusingArray(Macro)

Implementastackusingafixedlengtharray.Example8.1:#defineMAX_WIDTH50typedefstructstack

inttop;intdata[MAX_WIDTH];

Stack;ThecapacityofthestackisdefinedbyMAX_WIDTHcompiletimeconstant.Stack is defined which will contain the array to store the data and index to indicate the number ofelementsinthestack.voidStackInitialize(Stack*stk)

stk->top=-1;Numberofelementsinthestackisgovernedbythe“top”indexandtopisinitializedto-1whenastackisinitialized.Topindexvalueof-1indicatesthatthestackisemptyinthebeginning.voidStackPush(Stack*stk,intvalue)

if(stk->top<MAX_WIDTH-1)stk->top++;stk->data[stk->top]=value;//printf("valuepush:%d\n",value);elseprintf("stackoverflow\n");

StackPush() function checks whether the stack has enough space to store one more element, then itincreasesthe"top"byone.Finallysortthedatainthestack"data"array.Incase,stackisfullthen"stackoverflow"messageisprintedandthatvaluewillnotbeaddedtothestackandwillbeignored.intStackPop(Stack*stk)

if(stk->top>=0)

Page 238:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

intvalue=stk->data[stk->top];stk->top--;//printf("valuepop:%d\n",value);returnvalue;printf("stackempty\n");return0;

TheStackPop()functionis implemented,first itwillcheckthat therearesomeelementsinthestackbycheckingitstopindex.Ifsomeelementisthereinthestack,thenitwillstorethetopmostelementvalueinavariable"value".Thetopindexisreducedbyone.Finally,thatvalueisreturned.intStackTop(Stack*stk)

intvalue=stk->data[stk->top];returnvalue;

StackTop()functionreturnsthevalueofstoredinthetopelementofstack(doesnotremoveit)intStackIsEmpty(Stack*stk)

return(stk->top==-1);StackIsEmpty() function returns1 if stack isemptyor0 inallothercases.Bycomparing the top indexvaluewith-1.intStackSize(Stack*stk)

return(stk->top+1);StackSize() function returns the number of elements in the stack. It just returns "top+1".As the top isreferringthearrayindexofthestacktopvariablesoweneedtoaddonetoit.Analysis:·Theuserofthestackwillcreateastacklocalvariable.·Thenwillinitit.·Usepush()andpop()functionstoadd/removevariablestothestack.·Readthetopelementusingthetop()functioncall.·Queryregardingsizeofthestackusingsize()functioncall·QueryifstackisemptyusingisEmpty()functioncall

Page 239:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 240:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

StackusingArray(Dynamicmemory)

Createastackusinganarray,butthememoryofthearrayneedtobetakenfromheap/orthememoryneedtobedynamicallyallocated.Example8.2:1.#include"stdio.h"2.#include"stdlib.h"3.4.typedefstructstack5.inttop;6.int*data;7.intmax;8.Stack;9.10.voidStackInitialize(Stack*stk,intsize)11.12.stk->data=(int*)malloc(size*sizeof(int));13.stk->top=-1;14.stk->max=size;15.16.17.intmain()18.19.Stacks;20.StackInitialize(&s,10);21.for(inti=0;i<20;i++)22.StackPush(&s,i);23.for(inti=0;i<20;i++)24.StackPop(&s);25.return0;26.Analysis:Line1:4-8:stackstructureisdefinedwhichcontainits“top”index,Apointerdatathatwillbeusedtopoint tomemoryallocatedusingmalloc inLine12.Wekeeptrackof thecapacityofanarray inamaxvariableofastackstructure.Line 10: in init() function, we are passing the stack pointer and the size of memory that need to beallocatedtothestack.Line 12: we are allocating the memory sufficient to store "size" number of integer s. Moreover, thismemorylocationisstoredinthedatafieldofastackstructure.Maxissettothesizeofthestackpassed.Line19-20:Stackvariableiscreatedandinitialized,astackisinitializedsothatitwillbeabletocontain

Page 241:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

atmost10elements.Line22:pushisusedtoaddelementstothestack.Line24:popisusedtoreadandremovethetopelementofthestack.Note:All theother function like,StackPush(),StackPop(),StackIsEmpty(),StackSize() andStackTop()willworkfordynamicallyallocatedstackarraytoo.

Page 242:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

StackusingArray(Growingcapacityimplementation)

Intheabovedynamicarrayimplementationofastack.Makethecapacityofstackvariablesothatwhenitisnearlyfilled,thendoublethecapacityofthestack.Example8.3:1.voidStackPush(Stack*stk,intvalue)2.3.4.if(stk->top<stk->max-1)5.6.stk->top++;7.stk->data[stk->top]=value;8.printf("valuepush:%d\n",value);9.10.else11.12.stk->max=stk->max*2;13.stk->data=(int*)realloc(stk->data,stk->max*sizeof(int));14.printf("stacksizedoubled");15.StackPush(stk,value);16.17.Analysis:Line12:Inthisline,wearedoublingthemaxcapacityvariableofthestack.Line13:Sizeofthememoryisreallocatedtoabiggervalueinthisline.Thereallocfunctionisusedtoincrease or decrease the size of memory allocated. All the data on the stack is copied into the newlocation.Line15:finallytheStackPush()functioniscalledrecursivelytopushthevalueintotheincreasedcapacitystack.

Page 243:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

StackusingArray(Growing-Reducingcapacityimplementation)

Youcanalsowriteaprogram,whichcanreducethesizeofadynamicarraybytwowhenthenumberofelementsfallbelowmax/2.Youdonotwant to let the capacityof the stackbelow the initially allocated size.Youcandefineminlengthwheninitiscalled.Example8.4:1.typedefstructstack2.inttop;3.int*data;4.intmax;5.intmin;6.Stack;7.8.voidinitStack(Stack*stk,intsize)9.10.stk->data=(int*)malloc(size*sizeof(int));11.stk->top=-1;12.stk->max=size;13.stk->min=size;14.15.16.intStackPop(Stack*stk)17.18.if(stk->top>=0)19.20.intvalue=stk->data[stk->top];21.stk->top--;22.if(stk->top<(stk->max/2)&&stk->max>stk->min)23.24.stk->max=stk->max/2;25.stk->data=(int*)realloc(stk->data,stk->max*sizeof(int));26.printf("stacksizehalfed");27.28.printf("valuepop:%d\n",value);29.returnvalue;30.31.printf("stackempty\n");32.33.34.intmain()35.36.Stacks;37.initStack(&s,10);

Page 244:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

38.for(inti=0;i<20;i++)39.StackPush(&s,i);40.for(inti=0;i<20;i++)41.StackPop(&s);42.return0;43.Analysis:Line 22: the size of the stack is checked if it goes below half of the capacity and is greater than theminimumsize.Line 23-25: the capacity of the stack is divided by 2 andmemory is reallocated to point to half sizememory.

Page 245:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Stackusinglinkedlist

Example8.5:1.#include<stdlib.h>2.#include<stdio.h>3.4.structstackNode_t5.intvalue;6.stackNode_t*next;7.;8.typedefstackNode_t*stackPtr;9.#defineERROR_VALUE-999991.voidStackPush(stackPtr*dPtrHead,intvalue)2.3.stackPtrtempNode=(stackPtr)malloc(sizeof(stackNode_t));4.if(!tempNode)5.6.Printf("memoryshortageunabletopush");7.return;8.9.tempNode->value=value;10.tempNode->next=*dPtrHead;11.*dPtrHead=tempNode;12.Analysis:Stackimplementedusingalinkedlistissimplyinsertionanddeletionattheheadofthelinkedlist.InStackPush()function,memoryiscreatedforonenode.Thenthevalueisstoredintothatnode.Finally,thenodeisinsertedatthebeginningofthelist.

PopNodeImplementpopNodefunctionthatwillreturnafirstnodepointerofthestackExample8.6:1.stackPtrpopNode(stackPtr*dPtrHead)//freethereturnednodeyourself2.3.stackPtrdeleteMe;4.if(*dPtrHead)5.6.deleteMe=*dPtrHead;7.*dPtrHead=deleteMe->next;8.returndeleteMe;9.

Page 246:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

10.else11.12.printf("stackempty\n");13.returnNULL;14.15.Analysis:Line 1-15: popNode() functionwill take the first element of the list andwill return its pointer to thecaller.Thecallerofthisfunctionwillberesponsibleforthedeletionofthememory.Line13:Incasethestackisempty,NULLwillbereturned.

PopExample8.7:Implementthepopfunctionthatwillreturnthevalueatthetopofthestack.1.intpop(stackPtr*dPtrHead)//freethereturnednodeyourself2.3.stackPtrdeleteMe;4.intvalue;5.if(*dPtrHead)6.7.deleteMe=*dPtrHead;8.*dPtrHead=deleteMe->next;9.value=deleteMe->data;10.free(deleteMe);11.returnvalue;12.13.else14.15.printf("stackempty\n");16.returnERROR_VALUE;17.18.Analysis:Line 1-18: in pop() function first element of the list is pointed by a temporary pointer variable"deleteMe".Thevalueofthefirstnodeisstoredintoalocalvariable"value".Headofthelistwillpointtothenextelement.ThenthememorypointedbydeleteMewillbefreedusingfree()andfinallyvalueisreturned.Line16:Incasestackisempty,ERROR_VALUEwillbereturned.

Page 247:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinStack

BalancedParenthesisExample8.8: Stacks can be used to check a program for balanced symbols (such as , (), []). Theclosingsymbolshouldbematchedwiththemostrecentlyseenopeningsymbol.Example:() is legal,()()islegal,but((and()arenotlegalintisBalancedParenthesis(char*expn)

Stackstk;StackInitialize(&stk);inti=0;charch;while((ch=expn[i++])!='\0')switch(ch)case'':case'[':case'(':StackPush(&stk,ch);break;

case'':if(StackPop(&stk)!='')return0;break;

case']':if(StackPop(&stk)!='[')return0;break;

case')':if(StackPop(&stk)!='(')return0;break;returnStackIsEmpty(&stk);

Analysis:Traversetheinputstringwhenwegetanopeningparenthesiswepushitintostack.Whenwegetaclosing

Page 248:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

parenthesisthenwepopaparenthesisfromthestackandcompareifitisthecorrespondingtotheoneontheclosingparenthesis.Wereturn0/errorifthereisamismatchofparenthesis.Ifattheendofthewholestaringtraversal,wereachedtotheendofthestringandthestackisemptythenwehavebalancedparenthesis.intmain()

charexpn[50]="()";intvalue=isBalancedParenthesis(expn);printf("\nGivenExpn:%s\n",expn);printf("\nResultafterisParenthesisMatched:%d\n",value);return0;

Infix,PrefixandPostfixExpressionsWhenwe have an algebraic expression likeA +B thenwe know that the variable is being added tovariable B. This type of expression is called infix expression because the operator “+” is betweenoperandsAandoperandB.NowconsideranotherinfixexpressionA+B*C.Intheexpressionthereisaproblemthatinwhichorder+and*works.DoesAandBareaddedfirstandthentheresultismultiplied.OrBandCaremultipliedfirstandthentheresultisaddedtoA.Thismakestheexpressionambiguous.Todealwiththisambiguitywedefinetheprecedenceruleoruseparenthesestoremoveambiguity.So ifwewant tomultiplyBandCfirstand thenaddtheresult toA.ThenthesameexpressioncanbewrittenunambiguouslyusingparenthesesasA+(B*C).Ontheotherhand,ifwewanttoaddAandBfirstand then thesumwillbemultipliedbyCwewillwrite itas (A+B)*C.Therefore, in the infixexpressiontomaketheexpressionunambiguous,weneedparenthesis.Infixexpression:Inthisnotation,weplaceoperatorinthemiddleoftheoperands.<operand><operator><operand>Prefixexpressions:Inthisnotation,weplaceoperatoratthebeginningoftheoperands.<operator><operand><operand>Postfixexpression:Inthisnotation,weplaceoperatorattheendoftheoperands.<operand><operand><operator>InfixExpression PrefixExpression PostfixExpression

A+B +AB AB+

A+(B*C) +A*BC ABC*+

(A+B)*C *+ABC AB+C*

Page 249:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

NowcomesthemostobviousquestionwhyweneedsounnaturalPrefixorPostfixexpressionswhenwealreadyhaveinfixexpressionswhichwordsjustfineforus.The answer to this is that infix expressions are ambiguous and they need parenthesis to make themunambiguous.Whilepostfixandprefixnotationsdonotneedanyparenthesis.

Infix-to-PostfixConversionExample8.9:voidinfixToPostfix(char*expn,char*output)

Stackstk;StackInitialize(&stk);charch,op;inti=0;intindex=0;intdigit=0;while((ch=expn[i++])!='\0')if(isdigit(ch))output[index++]=ch;digit=1;elseif(digit)output[index++]='';digit=0;switch(ch)case'+':case'-':case'*':case'/':case'%':case' ':while(!StackIsEmpty(&stk)&&precedence(ch)<=precedence(StackTop(&stk)))op=StackPop(&stk);output[index++]=op;output[index++]='';StackPush(&stk,ch);

Page 250:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

break;case'(':StackPush(&stk,ch);break;case')':while(!StackIsEmpty(&stk)&&(op=StackPop(&stk))!='(')output[index++]=op;output[index++]='';break;while(!StackIsEmpty(&stk))op=StackPop(&stk);output[index++]=op;output[index++]='';output[index++]='\0';

intprecedence(charx)

if(x=='(')return(0);if(x=='+'||x=='-')return(1);if(x=='*'||x=='/'||x=='%')return(2);if(x==' ')return(3);return(4);

Analysis:1.Printoperandsinthesameorderastheyarrive.2.Ifthestackisemptyorcontainsaleftparenthesis“(”ontop,weshouldpushtheincomingoperatorinthestack.3.Iftheincomingsymbolisaleftparenthesis”(”,pushleftparenthesisinthestack.4.Iftheincomingsymbolisarightparenthesis“)”,popfromthestackandprinttheoperatorstillyouseealeftparenthesis“)”.Discardthepairofparentheses.5.Iftheprecedenceofincomingsymbolishigherthantheoperatoratthetopofthestack,thenpushittothestack.6.Iftheincomingsymbolhasanequalprecedencecomparedtothetopofthestackuseassociation.Ifthe

Page 251:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

associationislefttoright,thenpopandprintthesymbolatthetopofthestackandthenpushtheincomingoperator.Iftheassociationisrighttoleft,thenpushtheincomingoperator.7.Iftheprecedenceofincomingsymbolislowerthantheoperatoronthetopofthestack,thenpopandprint the top operator. Then compare the incoming operator against the new operator at the top of thestack.8.Attheendoftheexpression,popandprintalloperatorsonthestack.

Infix-to-PrefixConversionExample8.10:voidinfixToPrefix(char*expn,char*output)

reverseString(expn);replaceParanthesis(expn);infixToPostfix(expn,output);reverseString(output);

voidreverseString(char*a)

intlower=0;intupper=strlen(a)-1;chartempChar;while(lower<upper)tempChar=a[lower];a[lower]=a[upper];a[upper]=tempChar;

lower++;upper--;

voidreplaceParanthesis(char*a)

intlower=0;intupper=strlen(a)-1;chartempChar;while(lower<=upper)if(a[lower]=='(')a[lower]=')';elseif(a[lower]==')')a[lower]='(';

Page 252:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

lower++;

intmain()

charexpn[50]="10+((3))*5/(16-4)";printf("\nGivenExpn:%s\n",expn);infixToPostFix(expn);

charexpn2[50]="(5*3) (4-2)";printf("\nGivenExpn:%s\n",expn2);infixToPostFix(expn2);

return0;

Analysis:1.Reversethegiveninfixexpression.2.Replace'('with')'and')'with'('inthereversedexpression.3.Nowapplyinfixtopostfixsubroutinealreadydiscussed.4.Reversethegeneratedpostfixexpressionandthiswillgiverequiredprefixexpression.

PostfixEvaluateWriteapostfixEvaluate()functiontoevaluateapostfixexpression.Suchas:12+34+*Example8.11:intpostfixEvaluate(char*postfx)

Stacks;StackInitialize(&s);inti=0,op1,op2;charch;intdigit=0;intvalue=0;while((ch=postfx[i++])!='\0')if(isdigit(ch))digit=1;value=value*10+(ch-'0');elseif(ch=='')

Page 253:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if(digit==1)StackPush(&s,value);/*Pushtheoperand*/digit=0;value=0;elseop2=StackPop(&s);op1=StackPop(&s);switch(ch)case'+':StackPush(&s,op1+op2);break;case'-':StackPush(&s,op1-op2);break;case'*':StackPush(&s,op1*op2);break;case'/':StackPush(&s,op1/op2);break;returnStackTop(&s);

intmain()

charpostfx[50]="6523+8*+3+*";intvalue=postfixEvaluate(postfx);printf("\nGivenPostfixExpn:%s\n",postfx);printf("\nResultafterEvaluation:%d\n",value);return0;

Analysis:1)Createastacktostorevaluesoroperands.2)Scanthroughthegivenexpressionanddofollowingforeachelement:

a)Iftheelementisanumber,thenpushitintothestack.b) If the element is an operator, then pop values from the stack. Evaluate the operator over the

valuesandpushtheresultintothestack.3)Whentheexpressionisscannedcompletely,thenumberinthestackistheresult.

MinstackDesignastackinwhichgetminimumvalueinstackshouldalsoworkinO(1)TimeComplexity.Hint:Keeptwostackonewillbegeneralstack,whichwilljustkeeptheelements.Thesecondwillkeep

Page 254:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

theminvalue.1.Push:Pushanelementtothetopofstack1.Comparethenewvaluewiththevalueatthetopofthe

stack2. If the new value is smaller, then push the new value into stack2.Alternatively, push thevalueatthetopofthestack2toitselfoncemore.

2.Pop:Popanelementfromtopofstack1andreturn.Popanelementfromtopofstack2too.3.Min:Readfromthetopofthestack2thisvaluewillbethemin.

PalindromestringFindifgivenstringisapalindromeornotusingastack.Definition of palindrome: A palindrome is a sequence of characters, which is same backward, orforward.Eg.“AAABBBCCCBBBAAA”,“ABA”&“ABBA”Hint:Pushcharacters to thestackuntil thehalf-lengthof thestring.Thenpop thesecharactersand thencompare.Makesureyoutakecareoftheoddlengthandevenlength.

ReverseStackGivenastackhowtoreversetheelementsofthestackwithoutusinganyotherdata-structure.Youcannotuseanotherstacktoo.TimeComplexityandSpaceComplexityiswrong,itisO(n)forbothcases.Hint: Use recursion (system stack.) When you go inside the stack pop elements from stack in eachsubsequent call until stack is empty. Then push these elements one by one when coming out of therecursion.Theelementswillbereversed.Example8.12:voidreverseStack(Stack*stk)

intdata;if(StackIsEmpty(stk))return;data=StackPop(stk);reverseStack(stk);insertAtBottom(stk,data);

InsertAtBottomExample8.13:voidinsertAtBottom(Stack*stk,intvalue)

if(StackIsEmpty(stk))StackPush(stk,value);

Page 255:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

elseinttemp=StackPop(stk);insertAtBottom(stk,value);StackPush(stk,temp);

Depth-FirstSearchwithaStackInadepth-firstsearch,wetraversedownapathuntilwegetadeadend;thenwebacktrackbypoppingastacktogetanalternativepath.·Createastack·Createastartpoint·Pushthestartpointontothestack·While(valuesearchingnotfoundandthestackisnotempty)

oPopthestackoFindallpossiblepointsaftertheonewhichwejusttriedoPushthesepointsontothestack

StackusingaqueueHowtoimplementastackusingaqueue.Analysetherunningtimeofthestackoperations.Seequeuechapterforthis.

TwostacksusingsinglearrayExample8.14:Howtoimplementtwostacksusingonesinglearray.#defineMAX_SIZE50typedefstructstack

inttop1;inttop2;intdata[MAX_SIZE];

Stack;voidStackInitialize(Stack*stk)

stk->top1=-1;stk->top2=MAX_SIZE;

voidStackPush1(Stack*stk,intdata)

Page 256:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if(stk->top1<stk->top2-1)stk->data[++stk->top1]=data;elseprintf("StackisFull!\n");

intStackPop1(Stack*stk)

if(stk->top1>=0)intvalue=stk->data[stk->top1--];printf("%disbeingpoppedfromStack1\n",value);returnvalue;elseprintf("StackEmpty!CannotPop\n");returnINT_MIN;

voidStackPush2(Stack*stk,intdata)

if(stk->top1<stk->top2-1)stk->data[--stk->top2]=data;elseprintf("StackisFull!\n");

intStackPop2(Stack*stk)

if(stk->top2<MAX_SIZE)intvalue=stk->data[stk->top2++];printf("%disbeingpoppedfromStack2\n",value);returnvalue;

Page 257:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

elseprintf("StackEmpty!CannotPop\n");returnINT_MIN;

Analysis:Samearrayisusedtoimplementtwostack.Firststackisfilledfromthebeginningofthearrayandsecondstackisfilledfromtheendofthearray.Overflowandunderflowconditionsneedtobetakencareofcarefully.

StockSpanProblem

Approach1:int*StockSpanRange(intarr[],intsize)

int*SR=(int*)malloc(size*sizeof(int));SR[0]=1;

for(inti=1;i<size;i++)SR[i]=1;for(intj=i-1;(j>=0)&&(arr[i]>=arr[j]);j--)SR[i]++;returnSR;

Approach2:int*StockSpanRange(intarr[],intsize)

Stackstk;int*SR=(int*)malloc(size*sizeof(int));StackInitialize(&stk);

Page 258:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

StackPush(&stk,0);SR[0]=1;

for(inti=1;i<size;i++)while(!StackIsEmpty(&stk)&&arr[StackTop(&stk)]<=arr[i])StackPop(&stk);SR[i]=(StackIsEmpty(&stk))?(i+1):(i-StackTop(&stk));StackPush(&stk,i);returnSR;

GetMaxRectangularAreainaHistogram

Approach1intGetMaxArea(intarr[],intsize)

intmaxArea=-1;intcurrArea;intminHeight=0;for(inti=1;i<size;i++)minHeight=arr[i];for(intj=i-1;j>=0;j--)if(minHeight>arr[j])minHeight=arr[j];

currArea=minHeight*(i-j+1);

if(maxArea<currArea)maxArea=currArea;

Page 259:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

returnmaxArea;

Approach2:DivideandconquerApproach3intGetMaxArea(intarr[],intsize)

Stackstk;StackInitialize(&stk);intmaxArea=0;inttop;inttopArea;inti=0;while(i<size)while((i<size)&&(StackIsEmpty(&stk)||arr[StackTop(&stk)]<=arr[i]))StackPush(&stk,i);i++;while(!StackIsEmpty(&stk)&&(i==size||arr[StackTop(&stk)]>arr[i]))top=StackTop(&stk);StackPop(&stk);topArea=arr[top]*(StackIsEmpty(&stk)?i:i-StackTop(&stk)-1);if(maxArea<topArea)maxArea=topArea;returnmaxArea;

Page 260:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Prosandconsofarrayandlinkedlistimplementationofstack.Linkedlists:Listimplementationuses1pointerextramemoryperitem.Thereisnosizerestriction.Arrays:Allocatedaconstantamountofspace,whenthestackisnearlyempty,thenlostofspaceiswasteasitisnotused.Maximumsizeisdeterminedwhenthestackiscreated.

Page 261:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

UsesofStack·Recursioncanalsobedoneusingstack.(Inplaceofthesystemstack)·Thefunctioncallisimplementedusingstack.·Someproblemswhenwewanttoreverseasequence,wejustpusheverythinginstackandpopfromit.·Grammar checking, balance parenthesis, infix to postfix conversion, postfix evaluation of expression

etc.

Page 262:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ExerciseEx1:ConvertingDecimalNumberstoBinaryNumbersusingstackdatastructure.Hint:storeremindersintothestackandthenprintthestack.Ex2:Convertaninfixexpressiontoprefixexpression.Hint:Reversegivenexpression,Applyinfixtopostfix,andthenreversetheexpressionagain.

Step1.Reversetheinfixexpression.5^E+D*)C^B+A(

Step2.MakeEvery'('as')'andevery')'as'('5^E+D*(C^B+A)

Step3.Convertanexpressiontopostfixform.Step4.Reversetheexpression.

+*+A^BCD^E5Ex3:WriteanHTMLopeningtagandclosingtag-matchingprogram.Hint:parenthesismatching.Ex4:WriteafunctionthatwilldoPostfixtoInfixConversionEx5::WriteafunctionthatwilldoPrefixtoInfixConversionEx6 :Write a palindromematching function,which ignore characters other thanEnglish alphabet anddigits.String"Madam,I'mAdam."shouldreturntrue.

Page 263:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 264:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER9:QUEUE

Page 265:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionAqueue is abasicdata structure thatorganized items in first-in-first-out (FIFO)manner.First elementinsertedintoaqueuewillbethefirsttoberemoved.Itisalsoknownas"first-come-first-served".Thereallifeanalogyofqueueistypicallinesinwhichweallparticipatetimetotime.

·Wewaitinalineofrailwayreservationcounter.·Wewaitinthecafeterialine(topopaplatefrom“stackofplates”).·Wewaitinaqueuewhenwecalltosomecustomercase.

Theelements,whichareatthefrontofthequeue,aretheone,whichstayedinthequeueforthelongesttime.

Computersciencealsohascommonexamplesofqueues.Weissueaprintcommandfromourofficetoasingleprinterperfloor,printtaskislinedupinaprinterqueue.Theprintcommandthatwasissuedfirstwillbeprintedbeforethenextcommandsinline.In addition to printing queues, operating system is also using different queues to control processscheduling.Processesareaddedtoprocessingqueue,whichisusedbyanoperatingsystemforvariousschedulingalgorithms.Soonwewillbereadingaboutgraphsandwillcometoknowaboutbreadth-firsttraversal,whichusesaqueue.

Page 266:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TheQueueAbstractDataTypeQueueabstractdatatypeisdefinedasastructurethatfollowsFIFOorfirst-in-first-outfortheelementsaddedtoit.Queueshouldsupportthefollowingoperation:1.enqueue():Whichaddasingleelementatthebackofaqueue2.dequeue():Whichremoveasingleelementfromthefrontofaqueue.3.isEmpty():Returns1ifthequeueisempty4.size():Returnsthenumberofelementsinaqueue.

Page 267:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

QueueUsingArray

Example9.1:#defineSIZE100#defineERROR_VALUE-999typedefstructQueue_t

intfront;intback;intsize;intdata[SIZE];

Queue;voidQueueInitialize(Queue*que)

que->back=0;que->front=0;que->size=0;

intQueueIsEmpty(Queue*que)

returnque->size==0;intQueueSize(Queue*que)

returnque->size;voidEnqueue(Queue*que,intvalue)

if(que->size>=SIZE)

Page 268:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

printf("\nQueueisfull.");return;elseque->size++;que->data[que->back]=value;que->back=(++(que->back))%(SIZE-1);//printf("\nenqueue:%d",value);

intDequeue(Queue*que)

intvalue;if(que->size<=0)printf("\nQueueisempty.");returnERROR_VALUE;elseque->size--;value=que->data[que->front];que->front=(++(que->front))%(SIZE-1);returnvalue;

intmain()

Queueque;QueueInitialize(&que);for(inti=0;i<20;i++)Enqueue(&que,i);for(inti=0;i<20;i++)Dequeue(&que);return0;

Page 269:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Analysis:1.Hearqueueiscreatedfromanarrayofsize100.2.QueueInitializefunctioninitializethenumberofelementinqueuetozero.Byassigningfront,backand

sizeofqueuetozero.3.Enqueueinsertoneelementatthebackofthequeue.4.Dequeuedeleteoneelementfromthefrontofthequeue.

Page 270:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

QueueUsinglinkedliststructqueueNode_t

intvalue;queueNode_t*next;

;typedefqueueNode_t*queuePtr;#defineERROR_VALUE-99999Anodeofaqueueusinglinkedlistlookssameaslinkedlist.

EnqueueEnqueue into a queue using linked list.Nodes are added to the end of the linked list.Belowdiagramindicateshowanewnodeisaddedtothelist.Thetailismodifiedeverytimewhenanewvalueisaddedto thequeue.However, thehead isalsoupdated in thecasewhen there isnoelement in thequeueandwhenthatfirstelementisaddedtothequeuebothheadandtailwillbepointingtoit.

Example9.2:1.voidenqueue(queuePtr*dPtrHead,queuePtr*dPtrTail,intvalue)2.

Page 271:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

3.queuePtrtempNode=(queuePtr)malloc(sizeof(queueNode_t));4.if(!tempNode)5.6.Printf("memoryshortageunabletoenqueue");7.return;8.9.tempNode->value=value;10.tempNode->next=NULL;11.if(*dPtrHead==NULL)12.13.*dPtrTail=tempNode;14.*dPtrHead=tempNode;15.16.else17.18.(*dPtrTail)->next=tempNode;19.*dPtrTail=tempNode;20.21.Analysis:EnqueueoperationaddoneelementattheendoftheQueue(linkedlist).

Dequeue

Inthisweneedthetailpointerasitmaybethecasetherewasonlyoneelementinthelistandthetailpointerwillalsobemodifiedincaseofthedequeue.Example9.3:1.intdequeue(queuePtr*dPtrHead,queuePtr*dPtrTail)

Page 272:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

2.3.intvalue;4.queuePtrdeleteMe;5.if(*dPtrHead)6.7.deleteMe=*dPtrHead;8.*dPtrHead=deleteMe->next;9.value=deleteMe->value;10.free(deleteMe);11.if(*dPtrHead==NULL)12.*dPtrTail=NULL;13.returnvalue;14.15.else16.17.Printf("queueempty\n");18.returnERROR_VALUE;19.20.Analysis:Dequeueoperationremovesfirstnodefromthestartofthequeue(linkedlist).

Page 273:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinQueue

QueueusingastackHowtoimplementaqueueusingastack.Youcanusemorethanonestack.Solution:Wecanusetwostacktoimplementqueue.Weneedtosimulatefirstinfirstourusingstack.a)EnqueueOperation:newelementsareaddedtothetopoffirststack.b)DequeueOperation:elementsarepoppedfromthesecondstack.Whensecondstackisemptythenall

theelementsoffirststackarepoppedandpushedintosecondstackonebyone.Example9.4:#include"Stack.h"typedefstructSQueue_t

Stackstk1;Stackstk2;

SQueue;voidQueueInitialize(SQueue*que)

StackInitialize(&que->stk1);StackInitialize(&que->stk2);

voidEnqueue(SQueue*que,intvalue)

StackPush(&que->stk1,value);intDequeue(SQueue*que)

intvalue;if(!StackIsEmpty(&que->stk2))returnStackPop(&que->stk2);while(!StackIsEmpty(&que->stk1))value=StackPop(&que->stk1);StackPush(&que->stk2,value);returnStackPop(&que->stk2);

intmain()

Page 274:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

SQueueque;QueueInitialize(&que);Enqueue(&que,1);Enqueue(&que,11);Enqueue(&que,111);printf("%d",Dequeue(&que));printf("%d",Dequeue(&que));printf("%d",Dequeue(&que));

StackusingaQueueImplementstackusingaqueue.Solution1:usetwoqueuePush:enqueuenewelementstoqueue1.Pop:whilesizeofqueue1isbiggerthan1.Pushallitemsfromqueue1toqueue2exceptthelastitem.Switchthenameofqueue1andqueue2.Andreturnthelastitem.PushoperationisO(1)andPopoperationisO(n)Solution2:Thissamecanbedoneusingjustonequeue.Push:enqueuetheelementtoqueue.Pop: find the size of queue. If size is zero then return error. If size is positive then dequeue size- 1elementsfromthequeueandagainenqueuetothesamequeue.Atlast,dequeuethenextelementandreturnit.PushoperationisO(1)andPopoperationisO(n)Solution3:IntheabovesolutionsthepushisefficientandpopisunefficientcanwemakepopefficientO(1)andpushinefficientO(n)Push : enqueue new elements to queue2. Then enqueue all the elements of queue 1 to queue 2. Thenswitchnamesofqueue1andqueue2.Pop:dequeuefromqueue1PushoperationisO(n)andPopoperationisO(1)

ReverseastackReverseastackusingaqueueSolution:a)Popalltheelementsofstackandenqueuethemintoaqueue.b)Thendequeuealltheelementsofthequeueintostackc)Wehavetheelementsofthestackreversed.

Reverseaqueue

Page 275:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ReverseaqueueusingastackSolution:a)Dequeuealltheelementsofthequeueintostackb)Thenpopalltheelementsofstackandenqueuethemintoaqueue.c)Wehavetheelementsofthequeuereversed.

Breadth-FirstSearchwithaQueueIn breadth-first search, we explore all the nearest nodes first by finding all possible successors andenqueuethemtoaqueue.a)Createaqueueb)Createastartpointc)Enqueuethestartpointontothequeued)while(valuesearchingnotfoundandthequeueisnotempty)

oDequeuefromthequeueoFindallpossiblepointsafterthelastonetriedoEnqueuethesepointsontothequeue

JosephusproblemTherearenpeople standing in aqueuewaiting tobe executed.Thecountingbegins at the frontof thequeue. Ineachstep,knumberofpeoplearedequeuedandagainenqueuedonebyone from thequeue.Then the next person is executed. The execution proceeds around the circle until only the last personremains,whoisgivenfreedom.Findthatpositionwhereyouwanttostandandgainyourfreedom.Solution:1)Justinsertintegerfor1tokinaqueue.(correspondstokpeople)2)DefineaKpop()functionsuchthatitwilldequeueandenqueuethequeuek-1timesandthendequeue

onemoretime.(Thismanisdead.)3)Repeatsecondstepuntilsizeofqueueis1.4)Printthevalueinthelastelement.Thisisthesolution.

Page 276:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise

1) Implement queue using dynamicmemory allocation. Such that the implementation should follow thefollowingconstraints.a)Theuser shouldusememoryallocation from theheapusingmalloc() function. In theabovecode

makethischangeintheinit()function.Inthis,youneedtotakecareofthemaxvalueinthequeuestructure.(Youdonotneed#define).

b)Onceyouaredonewiththeaboveexerciseandyouareabletotestyourqueue.Thenyoucanadd

some more complexity to your code. In enqueue() function when the queue is full in place ofprinting“Queueisfull”youshouldallocatemorespaceusingrealloc()functioncall.

c)Onceyouaredonewiththeaboveexercise.Nowindequeuefunctiononceyouarebelowhalfofthe

capacityofthequeue,youneedtodecreasethesizeofthequeuebyhalf.Youshouldaddonemorevariable"min"toqueuestructuresothatyoucantrackwhatistheoriginalvaluecapacitypassedatinit()function.Moreover,thecapacityofthequeuewillnotgobelowthevaluepassedintheinit()function.

(Ifyouarenotabletosolvetheaboveexercise,thenhavealookintostackchapter,wherewehavedonesimilarforstack)

2)Implementthebelowfunctionforthequeue:

a.IsEmpty:Thisisleftasanexercisefortheuser.Takeavariable,whichwilltakecareofthesizeofaqueueifthevalueofthatvariableiszero,isEmptyshouldreturn1(true).Ifthequeueisnotempty,thenitshouldreturn0(false).

b.Size:Usethesizevariabletobeusedundersizefunctioncall.Size()functionshouldreturnthe

numberofelementsinthequeue.3)Implementstackusingaqueue.Writeaprogramforthisproblem.Youcanusejustonequeue.4)WriteaprogramtoReverseastackusingqueue5)WriteaprogramtoReverseaqueueusingstack6)WriteaprogramtosolveJosephusproblem(algoalreadydiscussed.).Therearenpeoplestandingina

queuewaitingtobeexecuted.Thecountingbeginsatthefrontofthequeue.Ineachstep,knumberofpeoplearedequeuedandagainenqueuedonebyonefromthequeue.Thenthenextpersonisexecuted.Theeliminationproceedsaroundthecircleuntilonlythelastpersonremains,whoisgivenfreedom.Findthatpositionwhereyouwanttostandandgainyourfreedom.

7)WriteaCompStack()functionwhichtakesapointertotwostackstructureasanargumentandreturn

true or false depending uponwhether all the elements of the stack are equal or not.You are givenisEqual(int,int)whichwillcompareandreturn1ifbothvaluesareequaland0iftheyaredifferent.

Page 277:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 278:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER10:TREE

Page 279:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionWehavealreadyreadaboutvariouslineardatastructureslikeanarray,linkedlist,stack,queueetc.Botharrayandlinkedlisthaveadrawbackoflineartimerequiredforsearchinganelement.A tree is anonlineardata structure,which is used to represent hierarchical relationships (parent-childrelationship).Eachnodeisconnectedbyanothernodebydirectededges.Example1:Treeinorganization

Example2:Treeinafilesystem

Page 280:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Terminologyintree

Root:Therootofthetreeistheonlynodewithoutanyincomingedges.Itisthetopnodeofatree.Node:Itisafundamentalelementofatree.Eachnodehasdataandtwopointers,whichpointtonulloritschild.Edge:Itisalsoafundamentalpartofatree,whichisusedtoconnecttwonodes.Path:Apathisanorderedlistofnodesthatareconnectedbyedges.Leaf:Aleafnodeisanodethathasnochildren.Heightofthetree:Theheightofatreeisthenumberofedgesonthelongestpathbetweentherootandaleaf.Thelevelofnode:Thelevelofanodeisthenumberofedgesonthepathfromtherootnodetothatnode.

Page 281:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Children:Nodesthathaveincomingedgesfromthesamenodetobesaidtobethechildrenofthatnode.Parent:Nodeisaparentofallthechildnodes,whicharelinkedbyoutgoingedges.Sibling:NodesinthetreethatarechildrenofthesameparentaresaidtobesiblingsAncestor:Anodereachablebyrepeatedmovingfromchildtoparent.

Page 282:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BinaryTreeAbinarytreeisatypetreeinwhicheachnodehasatmosttwochildren(0,1or2),whicharereferredtoastheleftchildandtherightchild.Belowisanodeofthebinarytreewith"a"storedasdataandwhoseleftchild(lChild)andwhoserightchild(rchild)bothpointingtowardsNULL.

Belowisastructureusedtodefinenode,wehavetypedefnodepointertotreeptrstructtreeNode_t

intvalue;treeNode_t*lChild;treeNode_t*rChild;

;typedeftreeNode_t*treePtr;Belowisabinarytreewhosenodescontainsdatafrom1to10

Intherestofthebook,binarytreewillberepresentedasbelow:

Page 283:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

PropertiesofBinarytreeare:1.Themaximumnumberofnodesonleveliofabinarytreeis2i,wherei>=12.Themaximumnumberofnodesinabinarytreeofdepthkis2k+1,wherek>=13.Thereisexactlyonepathfromtheroottoanynodesinatree.4.AtreewithNnodeshaveexactlyN-1edgesconnectingthesenodes.5.TheheightofacompletebinarytreeofNnodesislog2N.

Page 284:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TypesofBinarytrees

CompletebinarytreeInacompletebinary tree,every levelexcept the lastone iscompletelyfilled.Allnodes in the leftarefilledfirst,thentherightone.Abinaryheapisanexampleofacompletebinarytree.

Full/StrictlybinarytreeThefullbinarytreeisabinarytreeinwhicheachnodehasexactlyzeroortwochildren.

PerfectbinarytreeTheperfectbinary tree is a typeof fullbinary tree inwhicheachnon-leafnodehasexactly twochildnodes.Allleafnodeshaveidenticalpathlengthandallpossiblenodeslotsareoccupied

Page 285:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

RightskewedbinarytreeAbinarytreeinwhicheachnodeishavingeitherarightchildornochild(leaf)iscalledasrightskewedbinarytree

LeftskewedbinarytreeAbinarytreeinwhicheachnodeishavingeitheraleftchildornochild(leaf)iscalledasLeftskewedbinarytree

Height-balancedBinaryTreeAheight-balancedbinarytreeisabinarytreesuchthattheleft&rightsubtreesforanygivennodedifferinheightbymaxone.Note:Eachcompletebinarytreeisaheight-balancedbinarytree

Page 286:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

AVLtreeandRBtreeareanexampleofheightbalancedtreewewilldiscussthesetreesinadvancetreetopic.

Page 287:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinBinaryTree

CreateaCompletebinarytreeCreateabinarytreegivenalistofvaluesinanarray.Solution:Sincethereisnoorderdefinedinabinarytree,sonodescanbeinsertedinanyordersoitcanbeaskewedbinarytree.ButitisinefficienttodoanythinginaskewedbinarytreesowewillcreateaCompletebinarytree.Ateachnode,themiddlevaluestoredinthearrayisassignedtonodeandleftofarrayispassedtotheleftchildofthenodetocreateleftsub-tree.Andrightportionofarrayispassedtorightchildofthenodetocraterightsub-tree.Example10.1:treePtrCompleteBinaryTree(int*arr,intstart,intsize)

treePtrroot=NULL;

root=createNode(arr[start]);

intleft=2*start+1;intright=2*start+2;

if(left<size)root->lChild=CompleteBinaryTree(arr,left,size);if(right<size)root->rChild=CompleteBinaryTree(arr,right,size);

returnroot;

treePtrcreateNode(intval)

treePtrroot=(treePtr)malloc(sizeof(treeNode_t));root->value=val;root->lChild=root->rChild=NULL;returnroot;

intmain()

treePtrroot=NULL;intA[]=1,2,3,4,5,6,7,8,9,10;root=CompleteBinaryTree(A,0,10);return0;

Page 288:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ComplexityAnalysis:Thisisanefficientalgorithmforcreatingacompletebinarytree.TimeComplexity:O(n),SpaceComplexity:O(n)

Pre-OrderTraversalTraversalisaprocessofvisitingeachnodeofatree.InPre-OrderTraversalparentisvisited/traversedfirst,thenleftchildandrightchild.Pre-Ordertraversalisatypeofdepth-firsttraversal.

Solution:Preordertraversalisdoneusingrecursion.Ateachnode,firstthevaluestoredinitisprintedandthenfollowedbythevalueofleftchildandrightchild.AteachnodeitsvalueisprintedfollowedbycallingprintTree()functiontoitsleftandrightchildtoprintleftandrightsub-tree.Example10.2:1.voidprintPreorder(treePtrroot)/*preorder*/2.3.if(root)4.5.printf("%d",root->value);6.printPreorder(root->lChild);7.printPreorder(root->rChild);8.9.Output:64213587910ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)Note:Whenthereisanalgorithminwhichallnodesaretraversed,thencomplexitycannotbelessthanO(n).Whenthereisalargeportionofthetreethatisnottraversedthencomplexityreduces.

Page 289:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Post-OrderTraversalInPost-OrderTraversalleftchildisvisited/traversedfirst,thenrightchildandlastparentPost-Ordertraversalisatypeofdepth-firsttraversal.

Solution:Inpostordertraversal,first, theleftchildistraversedthenrightchildandintheend,currentnodevalueisprintedtothescreen.Example10.3:1.voidprintPostorder(treePtrroot)/*postorder*/2.3.if(root)4.5.printPostorder(root->lChild);6.printPostorder(root->rChild);7.printf("%d",root->value);8.9.Output:13254710986ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

In-OrderTraversalInIn-OrderTraversal,leftchildisvisited/traversedfirst,thentheparentandlastrightchildIn-Ordertraversalisatypeofdepth-firsttraversal.TheoutputofIn-OrdertraversalofBSTisasortedlist.Solution:InIn-Ordertraversal,firstthevalueofleftchildistraversed,thenthevalueofnodeisprintedtothescreenandthenthevalueofrightchildistraversed.

Page 290:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example10.4:1.voidprintInorder(treePtrroot)/*inorder*/2.3.if(root)4.5.printInorder(root->lChild);6.printf(“%d“,root->value);7.printInorder(root->rChild);8.9.Output:12345678910ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)Note:Pre-Order,Post-Order,andIn-Ordertraversalareforallbinarytrees.Theycanbeusedtotraverseanykindofabinarytree.

Levelordertraversal/BreadthFirsttraversalWriteCcode to implement levelorder traversalofa tree.Such thatnodesatdepthk isprintedbeforenodesatdepthk+1.

Page 291:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Solution:LevelordertraversalorBreadthFirsttraversalofatreeisdoneusingaqueue.Atthestart,theroot node pointer is added to queue.The traversal of tree happens until its queue is empty.Whenwetraversethetree,wefirstdequeueanelementfromthequeue,printthevaluestoredinthatnodeandthenitsleftchildandrightchildwillbeaddedtothequeue.Example10.5:1.voidprintBredthFirst(treePtrroot)2.3.std::queue<treePtr>que;4.treePtrtemp;5.que.push(root);6.while(!que.empty())7.8.temp=que.front();9.que.pop();10.printf(“%d”,temp->value);11.if(temp->lChild)12.que.push(temp->lChild);13.if(temp->rChild)14.que.push(temp->rChild);15.16.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

PrintDepthFirstwithoutusingtherecursion/systemstack.Solution:Depthfirsttraversalofthetreeisdoneusingrecursionbyusingsystemstack.Thesamecanbedoneusingstack.Inthestart,rootnodepointerisaddedtothestack.Thewholetreeistraverseduntilthestackisempty.Ineachiteration,anelementispoppedfromthestackitsvalueisprintedtoscreen.Thenrightchildandthenleftchildofthenodeisaddedtostack.

Page 292:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example10.6:1.voidprintDepthFirst(treePtrroot)2.3.std::stack<treePtr>st;4.treePtrtemp;5.st.push(root);6.while(!st.empty())7.8.temp=st.top();9.st.pop();10.printf(“%d”,temp->value);11.if(temp->rChild)12.st.push(temp->rChild);13.if(temp->lChild)14.st.push(temp->lChild);15.16.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

TreeDepthSolution:Depth is tree is calculated recursivelyby traversing left and right child of the root.At eachleveloftraversaldepthofleftchildiscalculatedanddepthofrightchildiscalculated.Thegreaterdepthamongtheleftandrightchildisaddedbyone(whichisthedepthofthecurrentnode)andthisvalueisreturned.Example10.7:1.inttreeDepth(treePtrroot)2.3.if(!root)4.return0;5.else6.7.intlDepth=treeDepth(root->lChild);8.intrDepth=treeDepth(root->rChild);9.if(lDepth>rDepth)10.returnlDepth+1;11.else12.returnrDepth+1;13.14.

Page 293:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

NthPre-OrderSolution:Wewant to print the node thatwill be at the nth indexwhenwe print the tree in PreOrdertraversal.Therefore,wekeepacounter tokeep trackof the index.When thecounter isequal to index,thenweprintthevalueandreturntheNthPreOrderindexnode.Example10.8:1.treePtrNthPreOrder(treePtrroot,intindex)/*preorder*/2.3.staticintcounter=0;4.treePtrtemp=NULL;5.if(root)6.7.counter++;8.if(counter==index)9.10.printf("%d",root->value);11.returnroot;12.13.temp=NthPreOrder(root->lChild,index);14.if(temp)15.returntemp;16.temp=NthPreOrder(root->rChild,index);17.if(temp)18.returntemp;19.20.returnNULL;21.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

NthPostOrderSolution:Wewant toprint thenode thatwill be at thenth indexwhenweprint the tree inpost ordertraversal.Therefore,wekeepacountertokeeptrackoftheindex,butatthistime,wewillincrementthecounterafterleftchildandrightchildtraversal.Whenthecounterisequaltoindex,weprintthevalueandreturnthenthpostordernode.Example10.91.treePtrNthPostOrder(treePtrroot,intindex)/*postorder*/2.3.staticintcount=0;4.treePtrtemp=NULL;

Page 294:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

5.if(root)6.7.temp=NthPostOrder(root->lChild,index);8.if(temp)9.returntemp;10.temp=NthPostOrder(root->rChild,index);11.if(temp)12.returntemp;13.count++;14.if(count==index)15.16.printf("%d“,root->value);17.returnroot;18.19.20.returnNULL;21.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

NthInOrderSolution:Wewant toprint thenode,whichwill be at thenth indexwhenweprint the tree in in-ordertraversal.Therefore,wekeepacountertokeeptrackoftheindex,butatthistime,wewillincrementthecounterafterleftchildtraversalbutbeforetherightchildtraversal.Whenthecounterisequaltoindex,thenweprintthevalueandreturnthenthin-orderindexnode.Program10.10:1.treePtrNthInOrder(treePtrroot,intindex)/*inorder*/2.3.staticintcount=0;4.treePtrtemp=NULL;5.if(root)6.7.temp=NthInOrder(root->lChild,index);8.if(temp)9.returntemp;10.count++;11.if(count==index)12.13.printf("%d“,root->value);14.returnroot;15.16.

Page 295:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

17.temp=NthInOrder(root->rChild,index);18.if(temp)19.returntemp;20.21.returnNULL;22.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(1)

CopyTreeSolution:Copytreeisdonebycopynodesoftheinputtreeateachlevelofthetraversalofthetree.Ateachlevelofthetraversalofnodesoftree,anewnodeiscreatedandthevalueoftheinputtreenodeiscopiedtoit.Theleftchildtreeiscopiedrecursivelyandthenpointertonewsubtreeisreturnedwhichwillbeassignedtotheleftchildofthecurrentnewnode.Similarlyfortherightchildtoo.Finally,thetreeiscopied.Example10.11:1.treePtrcopyTree(treePtrroot)2.3.treePtrtemp;4.if(root!=NULL)5.6.temp=(treePtr)malloc(sizeof(treeNode_t));7.if(!temp)8.returnNULL;9.temp->value=root->value;10.temp->lChild=copyTree(root->lChild);11.temp->rChild=copyTree(root->rChild);12.returntemp;13.14.else15.returnNULL;16.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

CopyMirrorTreeSolution:Copy,mirrorimageofthetreeisdonesameascopytree,butinplaceofleftchildpointingtothetreeformedbyleftchildtraversalofinputtree,thistimeleftchildpointstothetreeformedbyrightchildtraversal.Similarlyrightchildpointtothetraversaloftheleftchildoftheinputtree.Example10.12:1.treePtrcopyMirrorTree(treePtrroot)2.3.treePtrtemp;

Page 296:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

4.if(root!=NULL)5.6.temp=(treePtr)malloc(sizeof(treeNode_t));7.if(!temp)8.returnNULL;9.temp->value=root->value;10.temp->lChild=copyMirrorTree(root->rChild);11.temp->rChild=copyMirrorTree(root->lChild);12.returntemp;13.14.else15.returnNULL;16.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

NumberofElementSolution:Numberofnodesattherightchildandthenumberofnodesattheleftchildisaddedbyoneandwegetthetotalnumberofnodesinanytree/sub-tree.Example10.13:1.intnumElement(treePtrroot)2.3.if(!root)4.return0;5.else6.return(1+numElement(root->rChild)+numElement(root->lChild));7ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

NumberofLeafnodesSolution:Ifweadd thenumberof leafnode in therightchildwith thenumberof leafnodes in the leftchild,wewillgetthetotalnumberofleafnodeinanytreeorsubtree.Example10.14:1.intnumLeafs(treePtrroot)2.3.if(!root)4.return0;5.if(!root->lChild&&!root->rChild)6.return1;7.else

Page 297:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

8.return(numLeafs(root->rChild)+numLeafs(root->lChild));9.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

PrintMirrorSolution:PrintmirrortreeisverysimpleinplaceofprintingtheleftchildfirstprinttherightchildfirstsothatthetreeisprintedisPreOrdertraversalofmirroroftheinputtree.Example10.15:1.voidprintMirror(treePtrroot)/*preorder*/2.3.if(root!=NULL)4.5.printf("%d",root->value);6.printMirror(root->rChild);7.printMirror(root->lChild);8.return;9.10.else11.return;12.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

IdenticalSolution:Twotreeshaveidenticalvaluesifateachlevelthevalueisequal.Example10.16:1.intidentical(treePtrroot1,treePtrroot2)2.3.if(!root1&&!root2)4.return1;5.elseif(!root1||!root2)6.return0;7.else8. return ( identical(root1->lChild, root2->lChild) && identical(root1->rChild, root2->rChild) &&(root1->value==root2->value));9.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

FreeTree

Page 298:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Solution:Thetreeistraversedandnodesoftreearefreedinsuchamannersuchthatallchildnodesarefreedbeforeit.Example10.17:1.treePtrfreeTree(treePtrroot)2.3.if(root)4.5.root->lChild=freeTree(root->lChild);6.root->rChild=freeTree(root->rChild);7.if(root->lChild==NULL&&root->rChild==NULL)8.9.free(root);10.returnNULL;11.12.13.returnNULL;14.1.voidfreeTree(treePtr*rootPtr)2.3.*rootPtr=freeTree(*rootPtr);4.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

TreetoListRecSolution:Treetothelistisdonerecursively.Ateachnode,wewillsupposethatthetreetolistfunctionwilldoitsjobfortheleftchildandrightchild.Thenwewillcombinetheresultoftheleftchildandrightchild traversal.Weneedaheadand tail pointerof the left list and right list to combine themwith thecurrentnode.Intheprocessof integration, thecurrentnodewillbeaddedtothetailof theleft listandcurrentnodewillbeaddedtotheheadtotherightlist.Headoftheleftlistwillbecometheheadofthenewlyformedlistandtailoftherightlistwillbecomethetailofthenewlycreatedlist.Example10.18:treePtrtreeToListRec(treePtrcurr)

treePtrHead,Tail,tempHead;if(!curr)returnNULL;

if(curr->lChild==NULL&&curr->rChild==NULL)curr->lChild=curr;

Page 299:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

curr->rChild=curr;returnroot;if(curr->lChild)Head=treeToListRec(curr->lChild);Tail=Head->lChild;curr->lChild=Tail;Tail->rChild=curr;elseHead=curr;

if(curr->rChild)tempHead=treeToListRec(curr->rChild);Tail=tempHead->lChild;curr->rChild=tempHead;tempHead->lChild=curr;elseTail=curr;

Head->lChild=Tail;Tail->rChild=Head;returnHead;

ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

PrintallthepathsPrintallthepathsfromtherootstotheleafSolution:Wheneverwetraverseanode,weaddthatnodetothelist.Whenwereachaleaf,weprintthewholelist.Whenwereturnfromafunction,thenweremovetheelementthatwasaddedtothelistwhenweenteredthisfunction.Example10.19:1.voidprintList(list<int>L1)2.3.list<int>::iteratoriterB=L1.begin();4.list<int>::iteratoriterE=L1.end();5.while(iterB!=iterE)6.7.cout<<(*iterB)<<"";

Page 300:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

8.iterB++;9.10.cout<<endl;11.1.voidprintPath(treePtrhead,list<int>&L1)2.3.if(!head)4.return;5.If(head->rChild==null||head->lChild==null)6.7.printList(L1);8.L1.pop_back();9.return;10.11.L1.push_back(head->value);12.printPath(head->rChild,L1);13.printPath(head->lChild,L1);14.L1.pop_back();15.1.voidprintPathWrapper(treePtrhead)2.3.list<int>L1;4.printPath(head,L1);5.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

LeastCommonAncestorSolution:We recursively traverse the nodes of a binary tree. If we find any one of the nodewe aresearching for thenwe return that node.Andwhenwegetboth the left and right as somevalidpointerlocationotherthanNULL,wewillreturnthatnodeasthecommonancestor.Example10.20:1.treePtrLCA(treePtrroot,treePtrfirstPtr,treePtrsecondPtr)2.3.treePtrleft,right;4.5.if(root==NULL)6.returnNULL;7.8.if(root==firstPtr||root==secondPtr)9.returnroot;

Page 301:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

10.11.left=LCA(root->lChild,firstPtr,secondPtr);12.right=LCA(root->rChild,firstPtr,secondPtr);13.14.if(left&&right)15.returnroot;16.elseif(left)17.returnleft;18.else19.returnright;20.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

FindMaxinBinaryTreeSolution:Werecursivelytraversethenodesofabinarytree.Wewillfindthemaximumvalueintheleftandrightsubtreeofanynodethenwillcomparethevaluewiththevalueofthecurrentnodeandfinallyreturnthelargestofthethreevalues.Example10.21:1.intfindMaxBT(treePtrroot)2.3.intmax;4.intleft,right;5.6.if(root==NULL)7.returnINT_MIN;8.9.max=root->value;10.11.left=findMaxBT(root->lChild);12.right=findMaxBT(root->rChild);13.14.if(left>max)15.max=left;16.if(right>max)17.max=right;18.19.returnmax;20.

SearchvalueinaBinaryTreeSolution:To find if somevalue is there in a binary treeor not is doneusing exhaustive searchof the

Page 302:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

binarytree.First,thevalueofcurrentnodeiscomparedwiththevaluethatwearelookingfor.Thenitiscomparedrecursivelyinsidetheleftchildandrightchild.Example10.22:1.intsearchBT(treePtrroot,intvalue)2.3.intmax;4.intleft,right;5.6.if(root==NULL)7.return0;8.9.if(root->value==value)10.return1;11.12.left=searchBT(root->lChild,value);13.if(left)14.return1;15.16.right=searchBT(root->rChild,value);17.if(right)18.return1;19.20.return0;21.

MaximumDepthinaBinaryTreeSolution:Tofindthemaximumdepthofabinarytreeweneedtofindthedepthofthelefttreeanddepthofrighttreethenweneedtostorethevalueandincrementitbyonesothatwegetdepthofthegivennode.Example10.23:1.intmaxDepthBT(treePtrroot)2.3.intmax;4.intleft,right;5.6.if(root==NULL)7.return0;8.9.left=findMaxBT(root->lChild);10.right=findMaxBT(root->rChild);11.12.if(left>max)13.max=left;

Page 303:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

14.if(right>max)15.max=right;16.17.returnmax+1;18.

NumberofFullNodesinaBTSolution:Afullnodeisanodethathavebothleftandrightchild.Wewillrecursivelytraversthewholetreeandwillincreasethecountoffullnodeaswefindthem.Example10.24:1.intnumFullNodesBT(treePtrroot)2.3.intcount=0;4.intleft,right;5.6.if(root==NULL)7.return0;8.9.left=findMaxBT(root->lChild);10.right=findMaxBT(root->rChild);11.12.count=left+right;13.14.if(root->lChild&&root->rChild)//thislinecanbechangedtosolvemanyproblems.15.count++;16.17.returncount;18.

MaximumLengthPathinaBT/DiameterofBTSolution:TofindthediameterofBTweneedtofindthedepthofleftchildandrightchildthenwilladdthese two values and increment it by one so that we will get the maximum length path (diametercandidate)whichcontainsthecurrentnode.Thenwewillfindmaxlengthpathintheleftchildsub-tree.Andwillfindthemaxlengthpathintherightchildsub-tree.Finally,wewillcomparethethreevaluesandreturnthemaximumvalueoutofthesethiswillbethediameteroftheBinarytree.Example10.25:1.intmaxLengthPathBT(treePtrroot)//diameter2.3.intmax;4.intleftPath,rightPath;5.intleftMax,rightMax;

Page 304:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

6.7.if(root==NULL)8.return0;9.10.leftPath=maxDepthBT(root->lChild);11.rightPath=maxDepthBT(root->rChild);12.13.max=leftPath+rightPath+1;14.15.leftMax=maxLengthPathBT(root->lChild);16.rightMax=maxLengthPathBT(root->rChild);17.18.if(leftMax>max)19.max=leftMax;20.21.if(rightMax>max)22.max=rightMax;23.24.returnmax;25.

SumofAllnodesinaBTSolution:Wewill find the sumofall thenodes recursively. sumAllBT()will return the sumofall thenodeofleftandrightsubtreethenwilladdthevalueofcurrentnodeandwillreturnthefinalsum.Example10.26:1.intsumAllBT(treePtrroot)2.3.intsum;4.intleft,right;5.6.if(root==NULL)7.return0;8.9.left=sumAllBT(root->lChild);10.right=sumAllBT(root->rChild);11.12.sum=left+right+root->value;13.14.returnsum;15.

IterativePre-order

Page 305:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Solution:Inplaceofusingsystemstackinrecursion,wecantraversethetreeusingstackdatastructure.Example10.27:1.#definemaxStackSize1002.voiditerativePreorder(treePtrroot)3.4.structstructStack5.treePtrptr;6.intvisited;7.;8.treePtrtempRoot=NULL;9.inttempVisit=0;10.structStackstack[maxStackSize];11.inttop=1;12.stack[top].ptr=root;13.stack[top].visited=0;14.while(top)15.16.tempRoot=stack[top].ptr;17.tempVisit=stack[top].visited;18.top--;19.if(tempVisit)20.21.printf("[%d]",tempRoot->value);22.23.else24.25.if(tempRoot->rChild!=NULL)/*rightchildalwaysgoesfirstthenleftchild*/26.27.top++;28.stack[top].ptr=tempRoot->rChild;29.stack[top].visited=0;30.31.if(tempRoot->lChild!=NULL)32.33.top++;34.stack[top].ptr=tempRoot->lChild;35.stack[top].visited=0;36.37.top++;38.stack[top].ptr=tempRoot;39.stack[top].visited=1;40.41.42.

Page 306:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

IterativePost-orderSolution:Inplaceofusingsystemstackinrecursion,wecantraversethetreeusingstackdatastructure.Example10.28:1.voiditerativePostorder(treePtrroot)2.3.structstructStack4.treePtrptr;5.intvisited;6.;7.treePtrtempRoot=NULL;8.inttempVisit=0;9.structStackstack[maxStackSize];10.inttop=1;11.stack[top].ptr=root;12.stack[top].visited=0;13.while(top)14.15.tempRoot=stack[top].ptr;16.tempVisit=stack[top].visited;17.top--;18.if(tempVisit)19.20.printf("[%d]",tempRoot->value);21.22.else23.24.top++;25.stack[top].ptr=tempRoot;26.stack[top].visited=1;27.if(tempRoot->rChild!=NULL)/*rightchldalwaysgoesfirstthenrightchild*/28.29.top++;30.stack[top].ptr=tempRoot->rChild;31.stack[top].visited=0;32.33.if(tempRoot->lChild!=NULL)34.35.top++;36.stack[top].ptr=tempRoot->lChild;37.stack[top].visited=0;38.39.

Page 307:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

40.41.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

IterativeIn-orderSolution:Inplaceofusingsystemstackinrecursion,wecantraversethetreeusingstackdatastructure.Example10.29:1.voiditerativeInorder(treePtrroot)2.3.structstructStack4.treePtrptr;5.intvisited;6.;7.treePtrtempRoot=NULL;8.inttempVisit=0;9.structStackstack[maxStackSize];10.inttop=1;11.stack[top].ptr=root;12.stack[top].visited=0;13.while(top)14.15.tempRoot=stack[top].ptr;16.tempVisit=stack[top].visited;17.top--;18.if(tempVisit)19.20.printf("[%d]",tempRoot->value);21.22.else23.24.if(tempRoot->rChild!=NULL)/*rightchldalwaysgoesfirstthenrightchild*/25.26.top++;27.stack[top].ptr=tempRoot->rChild;28.stack[top].visited=0;29.30.top++;31.stack[top].ptr=tempRoot;32.stack[top].visited=1;33.if(tempRoot->lChild!=NULL)34.35.top++;36.stack[top].ptr=tempRoot->lChild;37.stack[top].visited=0;

Page 308:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

38.39.40.41.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

Page 309:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BinarySearchTree(BST)Abinarysearchtree(BST)isabinarytreeonwhichnodesareorderedinthefollowingway:

·Thekeyintheleftsubtreeislessthanthekeyinitsparentnode.·Thekeyintherightsubtreeisgreaterthekeyinitsparentnode.·Noduplicatekeyallowed.

Note: there can be two separate key and value fields in the tree node. But for simplicity, we areconsideringvalueasthekey.Allproblemsinthebinarysearchtreearesolvedusingthissuppositionthatthevalueinthenodeiskeyforthetree.Note:Sincebinarysearchtreeisabinarytreetoalltheabovealgorithmofabinarytreeareapplicabletoabinarysearchtree.

Page 310:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinBinarySearchTree(BST)Allbinarytreealgorithmsarevalidforbinarysearchtreetoo.

CreateabinarysearchtreeCreateabinarytreegivenlistofvaluesinanarrayinsortedorderSolution:Sincetheelementsinthearrayareinsortedorderandwewanttocreateabinarysearchtreeinwhichleftsubtreenodesarehavingvalueslessthanthecurrentnodeandrightsubtreenodeshavevaluegreaterthanthevalueofthecurrentnode.Wehavetofindthemiddlenodetocreateacurrentnodeandsendtherestofthearraytoconstructleftandrightsubtree.Example10.30:treePtrCreateBinaryTree(int*arr,intstart,intend)

treePtrroot=NULL;if(start>end)returnNULL;intmid=(start+end)/2;root=createNode(arr[mid]);root->left=CreateBinaryTree(arr,start,mid-1);root->right=CreateBinaryTree(arr,mid+1,end);returnroot;

treePtrcreateNode(intval)

treePtrroot=(treePtr)malloc(sizeof(treeNode_t));root->value=val;root->lChild=root->rChild=NULL;returnroot;

intmain()

treePtrroot=NULL;intA[]=1,2,3,4,5,6,7,8,9,10;root=CreateBinarySearchTree(A,0,10);return0;

Page 311:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

InsertionNodeswithkey6,4,2,5,1,3,8,7,9,10areinsertedinatree.Belowisstepbysteptreeafterinsertingnodesintheorder.

Page 312:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Solution: Smaller valueswill be added to the left child sub-tree of a node and greater valuewill beaddedtotherightchildsub-treeofthecurrentnode.Example10.31:1.treePtrinsertNode(intvalue,treePtrroot)2.3.if(root==NULL)4.5.root=(treePtr)malloc(sizeof(treeNode_t));6.if(root==NULL)7.8.printf("filledmemoryshortage");

Page 313:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

9.returnroot;10.11.root->value=value;12.root->lChild=root->rChild=NULL;13.14.else15.16.if(root->value>value)17.18.root->lChild=insertNode(value,root->lChild);19.20.else21.22.root->rChild=insertNode(value,root->rChild);23.24.25.returnroot;26.1.voidinsertNode(intvalue,treePtr*ptrRoot)2.3.*ptrRoot=insertNode(value,*ptrRoot);4.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

FindNodeFindthenodewiththevaluegiven.Solution:Thevaluegreaterthanthecurrentnodevaluewillbeintherightchildsub-treeandthevaluesmallerthanthecurrentnodeisintheleftchildsub-tree.Example10.32:1.treePtrfindNode(treePtrroot,intvalue)2.3.if(!root)4.returnNULL;5.if(root->value==value)6.returnroot;7.else8.9.if(root->value>value)10.returnfindNode(root->lChild,value);11.else

Page 314:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

12.returnfindNode(root->rChild,value);13.14.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(1)

FindNodeIterativeSolution:Thevaluegreaterthanthecurrentnodevaluewillbeintherightchildsub-treeandthevaluesmallerthanthecurrentnodeisintheleftchildsub-tree.Wecanfindavaluebytraversingtheleftorrightsubtreeiteratively.Example10.33:1.treePtrfindNodeIterative(treePtrroot,intvalue)/*iterative*/2.3.while(root)4.5.if(root->value==value)6.returnroot;7.elseif(root->value>value)8.root=root->lChild;9.else10.root=root->rChild;11.12.returnNULL;13.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(1)Example10.34:Operatorsaregenerallyreadfromlefttoright1.treePtrfindNodeIterative_optimized(treePtrroot,intvalue)2.3.while(root&&root->value!=value)4.(root->value>value)?root=root->lChild:root=root->rChild;5.returnroot;6.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

FindMinFindthenodewiththeminimumvalue.

Page 315:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Solution:leftmostchildofthetreewillbethenodewiththeminimumvalue.Example10.35:1.treePtrfindMin(treePtrroot)2.3.if(root)4.5.while(root->lChild)6.7.root=root->lChild;8.9.10.returnroot;11.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(1)

FindMinRecursiveFindthenodewithaminimumvalue,providearecursivesolution.Example10.36:1.treePtrfindMinRec(treePtrroot)2.3.if(!root)4.returnNULL;5.if(root->lChild==NULL)6.returnroot;7.else8.returnfindMinRec(root->lChild);9.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

FindMax

Page 316:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Findthenodeinthetreewiththemaximumvalue.

Solution:Rightmostnodeofthetreewillbethenodewiththemaximumvalue.Example10.37:1.treePtrfindMax(treePtrroot)2.3.if(root)4.5.while(root->rChild)6.7.root=root->rChild;8.9.10.returnroot;11.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(1)

FindMaxRecursiveFindthenodeinthetreewiththemaximumvalue,providearecursivesolution.Example10.38:1.treePtrfindMaxRec(treePtrroot)2.3.if(!root)4.returnNULL;5.if(root->rChild==NULL)6.returnroot;7.else8.returnfindMaxRec(root->rChild);9.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)

MaxValue

Page 317:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example10.39:1.intmaxValue(treePtrroot)2.3.if(root)4.5.while(root->rChild)6.7.root=root->rChild;8.9.returnroot->value;10.11.return-999;12.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(1)

MinValueExample10.40:1.intminValue(treePtrroot)2.3.if(root)4.5.while(root->lChild)6.7.root=root->lChild;8.9.returnroot->value;10.11.return-999;12.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(1)

IstreeaBSTSolution:Ateachnodewecheck,maxvalueofleftsubtreeissmallerthanthevalueofcurrentnodeandminvalueofrightsubtreeisgreaterthanthecurrentnode.Example10.41:1.intisBST(treePtrroot)2.3.if(!root)4.return1;5.if(root->lChild&&maxValue(root->lChild)>root->value)6.return0;

Page 318:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

7.if(root->rChild&&minValue(root->rChild)<=root->value)8.return0;9.return(isBST(root->lChild)&&isBST(root->rChild));10.ComplexityAnalysis:TimeComplexity:O(n2),SpaceComplexity:O(n)Theabovesolutioniscorrectbutitisnotefficientassametreenodesaretraversedmanytimes.Solution:Anotherbettersolutionwillbetheoneinwhichwewilllookintoeachnodeonlyonce.Thisisdonebynarrowingtherange.WewillbeusinganisBSTUtil()functionwhichtakethemaxandminrangeofthevaluesofthenodes.TheinitialvalueofminandmaxwillbeINT_MINandINT_MAX.Example10.42:1.intisBSTUtil(treePtrroot,intmin,intmax)2.3.if(!root)4.return1;5.6.if(root->value<min||root->value>max)7.return0;8.9.returnisBSTUtil(root->lChild,min,root->value)&&isBSTUtil(root->rChild,root->value+1,max);10.11.12.intisBST(treePtrroot)13.14.returnisBSTUtil(root,INT_MIN,INT_MAX);15.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)forstackSolution:Abovemethodiscorrectandefficientbutthereisanothereasymethodtodothesame.Wecandoin-ordertraversalofnodesandseeifwearegettingastrictlyincreasingsequenceExample10.43:1.intisBST(treePtrroot,int*value)/*inordertraversal*/2.3.intret;4.if(root)5.6.ret=isBST(root->lChild,value);7.if(!ret)8.return0;9.

Page 319:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

10.if(*value>root->value)11.return0;12.13.*value=root->value;14.15.ret=isBST(root->rChild,value);16.if(!ret)17.return0;18.19.return1;20.ComplexityAnalysis:TimeComplexity:O(n),SpaceComplexity:O(n)forstack

DeleteNodeDescription:Removethenodexfromthebinarysearchtree,makingthenecessary,reorganizenodesofbinarysearchtreetomaintainitsproperties.Therearethreecasesindeletenode,letuscallthenodethatneedtobedeletedasx.Case1:nodexhasnochildren.Justdeleteit(i.e.Changeparentnodesothatitdoesnotpointtox)Case2:nodexhasonechild.Spliceoutxbylinkingx’sparenttox’schildCase3:nodexhastwochildren.Spliceoutthex’ssuccessorandreplacexwithx’ssuccessorWhenthenodetobedeletedhavenochildrenThisisatrivialcasewedirectlydeletethenodeandreturnnull.Whenthenodetobedeletedhaveonlyonechild.Inthiscase,wesavethechildinatempvariable,thendeletecurrentnode,andfinallyreturnthechild.

Page 320:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Whenthenodetobedeletedhastwochildren.

Example10.44:1.voiddeleteNode(treePtr*rootPtr,intvalue)2.3.*rootPtr=deleteNode(*rootPtr,value);4.1.treePtrdeleteNode(treePtrroot,intvalue)2.3.treePtrtemp=NULL;4.if(root)5.6.if(root->value==value)

Page 321:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

7.8.if(root->lChild==NULL&&root->rChild==NULL)9.10.free(root);11.returnNULL;12.13.else14.15.if(root->lChild==NULL)16.17.temp=root->rChild;18.free(root);19.returntemp;20.21.if(root->rChild==NULL)22.23.temp=root->lChild;24.free(root);25.returntemp;26.27.temp=findMin(root->rChild);28.root->value=temp->value;29.root->rChild=deleteNode(root->rChild,temp->value);30.31.32.else33.34.if(root->value>value)35.36.root->lChild=deleteNode(root->lChild,value);37.38.else39.40.root->rChild=deleteNode(root->rChild,value);41.42.43.44.returnroot;45.Analysis:TimeComplexity:O(n),SpaceComplexity:O(n)

LeastCommonAncestorInatreeT.Theleastcommonancestorbetweentwonodesn1andn2isdefinedasthelowestnodeinT

Page 322:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

thathasbothn1andn2asdescendants.Example10.45:1.treePtrLcaBST(treePtrroot,treePtrfirstPtr,treePtrsecondPtr)2.3.if(!firstPtr||!secondPtr||!root)4.5.returnroot;6.7.8.if(root->value>firstPtr->value&&9.root->value>secondPtr->value)10.11.returnLcaBST(root->lChild,firstPtr,secondPtr);12.13.if(root->value<firstPtr->value&&14.root->value<secondPtr->value)15.16.returnLcaBST(root->rChild,firstPtr,secondPtr);17.18.returnroot;19.

PathLengthGiventwonodes,findthepathlengthbetweenthem.Solution:Thisproblemsolutionissimplyfindingtheleastcommonancestorofthetwonodeandthenfindthelengthofeachofnodefromtheirparent.Example10.46:1.intpathLength(treePtrroot,treePtrfirstPtr,treePtrsecondPtr)2.3.treePtrparent=LcaBST(root,firstPtr,secondPtr);4.intfirst=findNodeDepth(parent,firstPtr);5.intsecond=findNodeDepth(parent,secondPtr);6.returnfirst+second;7.1.intfindNodeDepth(treePtrroot,treePtrdstPtr)2.3.intvalue;4.if(!root||!dstPtr)5.return-1;6.

Page 323:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

7.if(root->value==dstPtr->value)8.return0;9.else10.11.if(root->value>dstPtr->value)12.value=findNodeDepth(root->lChild,dstPtr);13.else14.value=findNodeDepth(root->rChild,dstPtr);15.16.if(value!=-1)17.return(value+1);18.19.

TrimtheTreenodeswhichareOutsideRangeGivenarangeasmin,max.Weneedtodeleteallthenodesofthetreethatareoutofthisrange.Solution:Traversethetreeandeachnodethatishavingvalueoutsidetherangewilldeleteitself.Allthedeletionwillhappenfrominsideoutsowedonothavetocareaboutthechildrenofanodeasiftheyareoutofrangethentheyalreadyhaddeletedthemselves.Example10.47:1.treePtrtrimOutsideRange(treePtrroot,intmin,intmax)2.3.treePtrtempNode;4.if(root==NULL)5.returnNULL;6.7.root->lChild=trimOutsideRange(root->lChild,min,max);8.root->rChild=trimOutsideRange(root->rChild,min,max);9.10.if(root->value<min)11.12.tempNode=root->rChild;13.deleteroot;14.returntempNode;15.16.17.if(root->value>max)18.19.tempNode=root->lChild;20.deleteroot;21.returntempNode;22.

Page 324:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

23.24.returnroot;25.

PrintTreenodeswhichareinRangePrintonlythosenodesofthetreewhosevalueisintherangegiven.Solution:Justnormalinordertraversalandatthetimeofprintingwewillcheckifthevalueisinsidetherangeprovided.Example10.48:1.voidprintInRange(treePtrroot,intmin,intmax)2.3.if(!root)4.return;5.6.printInRange(root->lChild,min,max);7.8.if(root->value>=min&&root->value<=max)9.printf("%d",root->value);10.11.printInRange(root->rChild,min,max);12.

FindCeilandFloorvalueinsideBSTgivenkeyGivenatreeandavalueweneedtofindtheceilvalueofnodeintreewhichissmallerthanthegivenvalueandneedtofindthefloorvalueofnodeintreewhichisbigger.Ouraimistofindceilandfloorvalueascloseaspossiblethenthegivenvalue.Example10.49:1.voidCeilFloorBST(treePtrroot,intvalue,int*ceil,int*floor)2.3.while(root)4.5.if(root->value==value)6.7.*ceil=root->value;8.*floor=root->value;9.break;10.11.elseif(root->value>value)12.13.*ceil=root->value;

Page 325:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

14.root=root->lChild;15.16.else17.18.*floor=root->value;19.root=root->rChild;20.21.22.

TreetoDoublyLinkedlistWeneedtoconvertabinarytreetodoublelinkedlist.Suchthattheinordertraversalofthetreeissavedasasequenceofnodeindoublelinkedlist.Solution:WewilluseTreeToList()function.AteachnodewewillcallTreeToList()functionforbothleftchildandrightchild.Thesetwofunctioncallwillcreatedoublelinkedlistofleftchildandrightchildrespectively. Thenwe just have toworry about the current node.Wewill append the two linked listformedbytherecursivecallandthejointhemandthefinallistisprepared.Example10.50:1.voidconnect(treePtra,treePtrb)2.3.a->rChild=b;4.b->lChild=a;5.1.treePtrappend(treePtra,treePtrb)2.3.treePtraLast,bLast;4.if(a==NULL)5.return(b);6.if(b==NULL)7.return(a);8.aLast=a->lChild;9.bLast=b->lChild;10.connect(aLast,b);11.connect(bLast,a);12.return(a);13.1.treePtrtreeToList(treePtrroot)2.3.treePtraList,bList;4.if(root==NULL)

Page 326:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

5.return(NULL);6.aList=treeToList(root->lChild);7.bList=treeToList(root->rChild);8.root->lChild=root;9.root->rChild=root;10.aList=append(aList,root);11.aList=append(aList,bList);12.return(aList);13.Analysis:TimeComplexity:O(n),SpaceComplexity:O(1)

Page 327:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise1.Constructatreegivenitsin-orderandpre-ordertraversalstrings.

oinorder:12345678910opre-order:64213587910

2.Constructatreegivenitsin-orderandpost-ordertraversalstrings.

oinorder:12345678910opost-order:13254710986

3.WriteadeletenodefunctioninBinarytree.4.Writeafunctionprintdepthfirst inabinarytreewithoutusingsystemstack(useSTLqueueorstack

etc.)Hint:youmaywanttokeepanotherelementtotreenodelikevisitedflag.

5.CheckwhetheragivenBinaryTreeisCompleteornot

oInacompletebinarytree,everylevelexceptthelastoneiscompletelyfilled.Allnodesintheleftarefilledfirst,thentherightone.

6.CheckwhetheragivenBinaryTreeisFull/Strictlybinarytreeornot

oThefullbinarytreeisabinarytreeinwhicheachnodehaszeroortwochildren.

Page 328:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

7.CheckwhetheragivenBinaryTreeisaPerfectbinarytreeornotoTheperfectbinarytree-isatypeoffullbinarytreesinwhicheachnon-leafnodehasexactlytwo

childnodes.

8.CheckwhetheragivenBinaryTreeisHeight-balancedBinaryTreeornotoAheight-balancedbinarytreeisabinarytreesuchthattheleft&rightsubtreesforanygivennode

differinheightbynomorethanone

9.Isomorphic:twotreesareisomorphiciftheyhavethesameshape,itdoesnotmatterwhatthevalueis.Writeaprogramtofindiftwogiventreeareisomorphicornot.

10.Theworst-caseruntimeComplexityofbuildingaBSTwithnnodes

oO(n2)oO(n*logn)oO(n)oO(logn)

11.Theworst-caseruntimeComplexityofinsertionintoaBSTwithnnodesis

oO(n2)oO(n*logn)oO(n)oO(logn)

12.Theworst-caseruntimeComplexityofasearchofavalueinaBSTwithnnodes.

oO(n2)oO(n*logn)oO(n)oO(logn)

13.WhichofthefollowingtraversalsalwaysgivesthesortedsequenceoftheelementsinaBST?

oPreorderoIgnoredoPostorderoUndefined

Page 329:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

14.TheheightofaBinarySearchTreewithnnodesintheworstcase?

oO(n*logn)oO(n)oO(logn)oO(1)

15.TrytooptimizetheabovesolutiontogiveaDFStraversalwithoutusingrecursionusesomestackor

queue.16.Thisisanopenexerciseforthereaders.Everyalgorithmthatissolvedusingrecursion(systemstack)

can also be solved using user defined or library defined (STL) stack. So try to figure outwhat allalgorithms,whichareusingrecursionandtrytofigureouthowyouwilldothissameissueusinguserlayerstack.

17.Inabinarytree,printthenodesinzigzagorder.Inthefirstlevel,nodesareprintedinthelefttoright

order.Inthesecondlevel,nodesareprintedinrighttoleftandinthethirdlevelagainintheorderlefttoright.Hint:Usetwostacks.Popfromfirststackandpushintoanotherstack.Swapthestacksalternatively.

18.Findnthsmallestelementinabinarysearchtree.

Hint:Nthinorderinabinarytree.19.Findthefloorvalueofkey,whichisinsideaBST.20.FindtheCeilvalueofkey,whichisinsideaBST.21.WhatisTimeComplexityofthebelowcode:voidDFS(treePtrhead)

treePtrcurr=head,*prev;intcount=0;while(curr&&!curr->visited)count++;if(curr->lChild&&!curr->lChild->visited)curr=curr->lChild;elseif(curr->rChild&&!curr->rChild->visited)curr=curr->rChild;else

Page 330:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

printf("%d",curr->value);curr->visited=1;curr=head;printf("\ncountis:%d",count);

Page 331:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 332:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER11:PRIORITYQUEUE

Page 333:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionAPriority-QueuealsoknowsasBinary-Heap,isavariantofqueue.Itemsareremovedfromthestartofthe queue but in a Priority-Queue, the logical ordering of objects is determined by their priority. ThehighestpriorityitemareatthefrontofthePriority-Queue.WhenyouenqueueanitemtoPriority-Queuethe new item canmore to the front of the queue.A Priority-Queue is a very important data structure.Priority-Queue is used in various Graph algorithms like Prim’s Algorithm and Dijkstra’s algorithm.Priority-Queueisalsousedinthetimerimplementationetc.A Priority-Queue is implemented using a Heap (Binary Heap). A Heap data structure is an array ofelementsthatcanbeobservedasacompletebinarytree.Thetreeiscompletelyfilledonalllevelsexceptpossiblythelowest.Heapsatisfiestheheaporderingproperty.Aheapisacompletebinarytreeso theheightoftreewithNnodesisalwaysO(logn).

Aheapisnotasortedstructureandcanberegardedaspartiallyordered.Asyouseefromthepicture,thereisnorelationshipamongnodesatanygivenlevel,evenamongthesiblings.Heapisimplementedusinganarray.Inaddition,becauseheapisacompletebinarytree,theleftchildofaparent(atpositionx)isthenodethatisfoundinposition2xinthearray.Similarly,therightchildoftheparentisatposition2x+1inthearray.Tofindtheparentofanynodeintheheap,wecansimplydivision.Giventheindexyofanode,theparentindexwillbyy/2.

Page 334:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TypesofHeapTherearetwotypesofheapandthetypedependsontheorderingoftheelements.Theorderingcanbedoneintwoways:Min-HeapandMax-Heap

MaxHeapMax-Heap:thevalueofeachnodeislessthanorequaltothevalueofitsparent,withthelargest-valueelementattheroot.

MaxHeapOperationsInsert O(logn)DeleteMax O(logn)Remove O(logn)FindMax O(1)

MinHeapMin-Heap:thevalueofeachnodeisgreaterthanorequaltothevalueofitsparent,withtheminimum-valueelementattheroot.

Useitwheneveryouneedquickaccesstothesmallestitem,becausethatitemwillalwaysbeattherootofthetreeorthefirstelementinthearray.However,theremainderofthearrayiskeptpartiallysorted.Thus,instantaccessisonlypossibleforthesmallestitem.MinHeapOperations

Page 335:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Insert O(logn)DeleteMin O(logn)Remove O(logn)FindMin O(1)Throughout thischapter, theword"heap"willalwaysrefer toamax-heap.The implementationofmin-heapisleftfortheusertodoitasanexercise.

Page 336:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

HeapADTOperationsThebasicoperationsofbinaryheapareasfollows:BinaryHeap Createanewemptybinaryheap O(1)Insert Addinganewelementtotheheap O(logn)DeleteMax Deletethemaximumelementformtheheap. O(logn)FindMax Findthemaximumelementintheheap. O(1)isEmpty returntrueiftheheapisemptyelsereturnfalse O(1)Size Returnthenumberofelementsintheheap. O(1)BuildHeap Buildanewheapfromthearrayofelements O(logn)

Page 337:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

OperationonHeap

CreateHeapfromanarray1.Startsbyputtingtheelementstoanarray.2.Starting from themiddle of the arraymove downward towards the start of the array.At each step,

compareparentvaluewithitsleftchildandrightchild.Thenrestoretheheappropertybyshiftingtheparent valuewith its largest-value child. Such that the parent valuewill always be greater than orequaltoleftchildandrightchild.

3.Forallelementsfrommiddleofthearraytothestartofthearray.Wewillcompareandshiftuntilwereachtotheleafnodes.TheTimeComplexityofbuildheapisO(N).

Given an array as input to create heapfunction. Value of index i is comparedwithvalueofitschildrennodesthatisatindex(i*2+1)and(i*2+2).MiddleofarrayN/2thatisindex3iscomapredwithindex7. If the childrennode valueis greater than parent node then thevaluewillbeswapped.

Similarly, value of index 2 is comparedwith index 5 and 6. The largest of thevalue is 7 which will be swapped withthevalueattheindex2.

Page 338:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Similarly, value of index 1 is comparedwith index 3 and 4 The largest of thevalue is 8 which will be swapped withthevalueattheindex1.

Proclate down function is used tosubsequentlyadjestthevaluereplasedinthe previous step by comparing it withitschildrennodes.

Now value at index 0 is comared withindex1and2.8isthelargestvaluesoitswappedwiththevalueatindex0.

Page 339:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Proclate down function is used tofurther compare the value at index 1withitschildrennodesatindex3and4.

Intheendmaxheapiscreated.

Example11.1:PtrHeapBuildHeap(int*arr,intsize,intcapacity)

PtrHeappHeap=(PtrHeap)malloc(sizeof(Heap));pHeap->Size=size;pHeap->Capacity=capacity;pHeap->Array=arr;

for(inti=(pHeap->Size)/2;i>0;i--)ProclateDown(pHeap->Array,i,pHeap->Size);

returnpHeap;

voidProclateDown(int*arr,intposition,intsize)

intlChild=2*position+1;

Page 340:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

intrChild=lChild+1;intsmall=-1;

if(lChild<size)small=lChild;

if(rChild<size&&arr[rChild]<arr[lChild])small=rChild;

if(small!=-1&&arr[small]<arr[position])inttemp=arr[position];arr[position]=arr[small];arr[small]=temp;ProclateDown(arr,small,size);

InitializinganemptyHeapExample11.2:voidHeapInitialize(PtrHeappHeap,intcapacity)

pHeap->Size=0;pHeap->Capacity=capacity;pHeap->Array=(int*)malloc((capacity)*sizeof(int));

Enqueue/Insert1.Addthenewelementattheendofthearray.Thiskeepsthestructureasacompletebinarytree,butit

mightnolongerbeaheapsincethenewelementmighthaveavaluegreaterthanitsparentvalue.2.Swapthenewelementwithitsparentuntilithasvaluegreaterthanitsparentvalue.3.Step2willterminatewhenthenewelementreachestherootorwhenthenewelement'sparenthavea

valuegreaterthanorequaltothenewelement'svalue.LetustakeanexampleoftheMaxheapcreatedintheaboveexample.

Page 341:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Letustakeanexamplebyinsertingelementwithvalue9totheheap.Theelementisaddedtotheendoftheheaparray.Nowthevaluewillbeproclateupbycomparingitwiththeparent.Thevalueisaddedtoindex8anditsparentwillbe(N-1)/2=index3.

Sincethevalue9isgreaterthan4itwillbeswappedwithit.

Proclate up is used and the value is moved up tillheappropertyissatisfied.

Page 342:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Now the value at index 1 is comparedwith index 0andtosatisfyheappropertyitisfurtherswapped.

Now finally max heap is created by inserting newnode.

Example11.3:voidHeapInsert(PtrHeappHeap,intvalue)

pHeap->Array[pHeap->Size]=value;ProclateUp(pHeap->Array,pHeap->Size);pHeap->Size++;

voidProclateUp(int*arr,intposition)

intparent=(position–1)/2;

if(position!=0)if(arr[parent]>arr[position])inttemp=arr[position];arr[position]=arr[parent];arr[parent]=temp;

ProclateUp(arr,parent);

Page 343:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Dequeue/Delete1.Copythevalueattherootoftheheaptothevariableusedtoreturnavalue.2.Copythe lastelementof theheapto theroot,and thenreduce thesizeofheapby1.Thiselement is

calledthe"out-of-place"element.3.Restoreheappropertybyswappingtheout-of-placeelementwithitsgreatest-valuechild.Repeatthis

processuntiltheout-of-placeelementreachesaleaforithasavaluethatisgreaterorequaltoallitschildren.

4.ReturntheanswerthatwassavedinStep1.Todequeueanelementfromheapitstopvalueisswappedtotheendoftheheaparrayandsizeofheapisreducedby1.

Sinceendoftheheapvalueiscopiedtohead of heap. Heap property isdisturbed sowe need to again proclatedown by comparing node with itschildrennodestorestoreheapproperty.

Page 344:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Proclate downcontinuedby comparingwithitschildrennodes.

Proclatedown

ProclatedownComplete

Page 345:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example11.4:intHeapDelete(PtrHeappHeap)

intvalue=(pHeap->Array[0);pHeap->Array[0]=pHeap->Array[pHeap->Size-1];pHeap->Size--;ProclateDown(pHeap->Array,0,pHeap->Size);returnvalue;

Page 346:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Heap-Sort1.Usecreateheapfunctiontobuildamaxheapfromthegivenarrayofelements.Thisoperationwilltake

O(N)time.2.Dequeuethemaxvaluefromtheheapandstorethisvaluetotheendofthearrayatlocationarr[size-1]

a)Copythevalueattherootoftheheaptoendofthearray.b)Copy the last element of the heap to the root, and then reduce the size of heap by 1.This

elementiscalledthe"out-of-place"element.c) Restore heap property by swapping the out-of-place elementwith its greatest-value child.

Repeat this process until the out-of-place element reaches a leaf or it has a value that isgreaterorequaltoallitschildren

3.Repeatthisoperationuntilthereisjustoneelementintheheap.Letustakeexampleoftheheapthatwehadcreatedatthestartofthechapter.Heapsortisalgorithmstartsbycreatingaheapof thegivenarray that isdone in linear time.Thenateachstepheadof theheap isswappedwiththeendoftheheapandtheheapsizeisreducedby1.Thenproclatedownisusedtorestoretheheapproperty.Inaddition,thissameisdonemultipletimesuntiltheheapcontainjustoneelement.

Page 347:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 348:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example11.5:voidHeapSort(int*arr,intsize)

inttemp;for(inti=size/2;i>0;i--)ProclateDown(arr,i,size);while(size)temp=arr[0];arr[0]=arr[size-1];arr[size-1]=temp;size--;ProclateDown(arr,0,size);

Page 349:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

voidProclateDown(int*arr,intposition,intsize)

intlChild=2*position+1;intrChild=lChild+1;intsmall=-1;

if(lChild<size)small=lChild;if(rChild<size&&compare(arr[rChild],arr[lChild]))//comparefunctiondecideminsmall=rChild;

if(small!=-1&&compare(arr[small],arr[position]))inttemp=arr[position];arr[position]=arr[small];arr[small]=temp;ProclateDown(arr,small,size);

//Swap,whentheparentislessthanchild,willgivemaxheap.//Swapwhenaparentisgreaterthenachild.itwillgiveminheap.intcompare(intparentVal,intchildVal)

return(parentVal<childVal);intmain()

inta[10]=4,5,3,2,6,7,11,8,9,10;heapSort(a,sizeof(a)/sizeof(int));

Datastructure ArrayWorstCaseTimeComplexity O(nlogn)BestCaseTimeComplexity O(nlogn)AverageTimeComplexity O(nlogn)SpaceComplexity O(1)Note:Heap-SortisnotaStablesortanddonotrequireanyextraspaceforsortingalist.

Page 350:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 351:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

UsesofHeap1.Heapsort:Oneofthebestsortingmethodsbeingin-placeandlog(N)timecomplexityinallscenarios.2.Selectionalgorithms: Finding themin,max, both themin andmax,median, or even the kth largest

elementcanbedoneinlineartime(oftenconstanttime)usingheaps.3. Priority Queues: Heap Implemented priority queues are used in Graph algorithms like Prim’s

AlgorithmandDijkstra’salgorithm.Aheap is a useful data structurewhen you need to remove theobjectwiththehighest(orlowest)priority.Schedulers,timers

4.Graphalgorithms:Byusingheapsas internal traversaldatastructures, run timewillbereducedby

polynomialorder.ExamplesofsuchproblemsarePrim'sminimal5. Because of the lack of pointers, the operations are faster than a binary tree. Also, some more

complicatedheaps(suchasbinomial)canbemergedefficiently,whichisnoteasytodoforabinarytree.

Page 352:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinHeap

KthSmallestinaMinHeapJustcallDeleteMin()operationK-1timesandthenagaincallDeleteMin() this lastoperationwillgiveKthsmallestvalue.TimeComplexityO(KlogN)

KthLargestinaMaxHeapJustcallDeleteMax()operationK-1timesandthenagaincallDeleteMax()thislastoperationwillgiveKthsmallestvalue.TimeComplexityO(KlogN)

100LargestinaStreamTherearebillionsofintegerscomingoutofastreamsomegetInt()functionisprovidingintegersonebyone.Howwouldyoudeterminethelargest100numbers?Solution:Largehundred(orsmallesthundredetc.)suchproblemsaresolvedveryeasilyusingaHeap.Inourcase,wewillcreateaminheap.1.Firstfrom100firstintegersbuildsaminheap.2.Thenforeachcomingintegercompareifitisgreaterthanthetopoftheminheap.3.Ifnot,thenlookfornextinteger.Ifyes,thenremovethetopminvaluefromtheminheaptheninsertthe

newvalueatthetopoftheheapanduseprocolateDownandmoveittoitsproperpositiondowntheheap.

4.Everytimeyouhavelargest100valuesstoredinyourhead

MergetwoHeapHowcanwemergetwoheaps?Solution:Thereisnosinglesolutionforthis.LetussupposethesizeofthebiggerheapisNandthesizeofthesmallerheapisM.1.Ifbothheapsarecomparablesize,thenputbothheaparraysinsamebiggerarrays.Alternatively,inone

of thearrays if theyarebig enough.ThenapplyCreateHeap() functionwhichwill take theta(N+M)time.

2.IfMismuchsmallerthanNthenenqueue()eachelementofMarrayonebyonetoNheap.ThiswilltakeO(MlogN)theworstcaseorO(M)bestcase.

Min/MaxHeapusingfunctionpointerExample11.6: Same heap data structure can be used to create bothmin heap andmax heap only thecomparefunctionwillchange.typedefstructHeap_t

intCapacity;intSize;int*Array;

Page 353:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

bool(*compare)(int,int);Heap;voidHeapInitialize(PtrHeappHeap,intcapacity,bool(*comp)(int,int))

pHeap->Size=0;pHeap->Capacity=capacity;pHeap->Array=(int*)malloc((capacity)*sizeof(int));pHeap->compare=comp;

voidHeapInsert(PtrHeappHeap,intvalue)

pHeap->Array[pHeap->Size]=value;ProclateUp(pHeap->Array,pHeap->Size,pHeap->compare);pHeap->Size++;

voidProclateUp(int*arr,intposition,bool(*comp)(int,int))

intparent=(position-1)/2;

if(position!=0)if(comp(arr[parent],arr[position]))inttemp=arr[position];arr[position]=arr[parent];arr[parent]=temp;ProclateUp(arr,parent);

voidProclateDown(int*arr,intposition,intsize,bool(*comp)(int,int))

intlChild=2*position+1;intrChild=lChild+1;intsmall=-1;

if(lChild<size)small=lChild;

if(rChild<size&&comp(arr[rChild],arr[lChild]))small=rChild;

Page 354:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if(small!=-1&&comp(arr[small],arr[position]))inttemp=arr[position];arr[position]=arr[small];arr[small]=temp;ProclateDown(arr,small,size);

intHeapDelete(PtrHeappHeap)

intvalue=(pHeap->Array[0]);pHeap->Array[0]=pHeap->Array[pHeap->Size-1];pHeap->Size--;ProclateDown(pHeap->Array,0,pHeap->Size,pHeap->compare);returnvalue;

//Greaterusedascomparator,swapwhenparentisgreaterthenchild,minheapboolGreater(inta,intb)

returna>b;//Smallerusedascomparator,swapwhenparentissmallerthenchild,maxheapboolSmaller(inta,intb)

returna<b;intHeapSize(PtrHeappHeap)

returnpHeap->Size;

GetMedianfunctionExample11.7:Giveadatastructure,whichwillprovidemedianofgivenvaluesinconstanttime.Solution:Wewillbeusingtwoheaponeminheapandothermaxheap.First,therewillbeamaxheap,whichwillcontainthefirsthalfofdata,andtherewillbeanotherminheap,whichwillcontainthesecondhalfofthedata.Maxheapwillcontainthesmallerhalfofthedataanditsmaxvalue,whichisatthetopoftheheap,willbethemediancontender.Similarly,theMinheapwillcontainthelargervaluesofthedataanditsminvalue,whichisatitstop,willcontainthemediancontender.Wewillkeeptrackofthesizeofheaps.Wheneverweinsertavaluetoheap,wewillmakesurethatthesizeoftwoheapsdiffersbymax

Page 355:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

oneelement,otherwisewewillpoponeelementfromoneandinsertintoanothertokeepthembalanced.voidMedianHeapInit(MedianHeap*heap)

HeapInitialize(&heap->minHeap,100,Greater);HeapInitialize(&heap->maxHeap,100,Smaller);

voidMedianHeapInsert(MedianHeap*heap,intvalue)

if(HeapSize(&heap->maxHeap)==0||HeapTop(&heap->maxHeap)>=value)HeapInsert(&heap->maxHeap,value);elseHeapInsert(&heap->minHeap,value);//sizebalancingif(HeapSize(&heap->maxHeap)>HeapSize(&heap->minHeap)+1)value=HeapDelete(&heap->maxHeap);HeapInsert(&heap->minHeap,value);if(HeapSize(&heap->minHeap)>HeapSize(&heap->maxHeap)+1)value=HeapDelete(&heap->minHeap);HeapInsert(&heap->maxHeap,value);

intgetMedian(MedianHeap*heap)

if(HeapSize(&heap->maxHeap)==0&&HeapSize(&heap->minHeap)==0)returnINT_MIN;

if(HeapSize(&heap->maxHeap)==HeapSize(&heap->minHeap))return(HeapTop(&heap->maxHeap)+HeapTop(&heap->minHeap))/2;elseif(HeapSize(&heap->maxHeap)>HeapSize(&heap->minHeap))returnHeapTop(&heap->maxHeap);elsereturnHeapTop(&heap->minHeap);

intmain()

Page 356:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

intarr[]=1,9,2,8,3,7,4,6,5,1,9,2,8,3,7,4,6,5,10,10;

MedianHeapheap;MedianHeapInit(&heap);for(inti=0;i<20;i++)MedianHeapInsert(&heap,arr[i]);printf("Medianafterinsertionof%dis%d\n",arr[i],getMedian(&heap));return0;

IsMinHeapGivenanarrayfindifitisabinaryHeapisMinHeapExample11.8:intIsMinHeap(intarr[],intsize)

for(inti=0;i<=(size-2)/2;i++)if(2*i+1<size)if(arr[i]>arr[2*i+1])return0;if(2*i+2<size)if(arr[i]>arr[2*i+2])return0;return1;

IsMaxHeapGivenanarrayfindifitisabinaryHeapMaxheapExample11.9:intIsMaxHeap(intarr[],intsize)

for(inti=0;i<=(size-2)/2;i++)

Page 357:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if(2*i+1<size)if(arr[i]<arr[2*i+1])return0;if(2*i+2<size)if(arr[i]<arr[2*i+2])return0;return1;

TraversalinHeapHeapsarenotdesignedto traverse tofindsomeelement theyaremadetogetminormaxelementfast.Stillifyouwanttotraverseaheapjusttraversethearraysequentially.Thistraversalwillbelevelordertraversal.ThistraversalwillhavelinearTimeComplexity.

DeletingArbitraryelementfromMinHeapHeap isnotdesigned todeleteanarbitraryelement,butstill ifyouwant todoso.Find theelementbylinearsearchintheheaparray.ReplaceitwiththevaluestoredattheendoftheHeapvalue.Reducethesizeoftheheapbyone.Comparethenewinsertedvaluewithitsparent.If itsvalueissmallerthantheparentvalue,thenpercolateup.Elseifitsvalueisgreaterthanitsleftandrightchildthenpercolatedown.TimeComplexityisO(logn)

DeletingKthelementfromMinHeapHeapisnotdesignedtodeleteanarbitraryelement,butstillifyouwanttodoso.ReplacethekthvaluewiththevaluestoredattheendoftheHeapvalue.Reducethesizeoftheheapbyone.Comparethenewinsertedvaluewithitsparent.Ifitsvalueissmallerthantheparentvalue,thenpercolateup.Elseif itsvalueisgreaterthanitsleftandrightchildthenpercolatedown.TimeComplexityisO(logn)

PrintvalueinRangeinMinHeapLinearlytraversethroughtheheapandprintthevaluethatareinthegivenrange.

Page 358:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise1.Whatistheworst-caseruntimeComplexityoffindingthesmallestiteminamin-heap?2.Findmaxinaminheap.

Hint:normalsearchinthecompletearray.ThereisonemoreoptimizationyoucansearchfromthemidofthearrayatindexN/2

3.Whatistheworst-casetimeComplexityoffindingthelargestiteminamin-heap?4.Whatistheworst-casetimeComplexityofdeleteMininamin-heap?5.Whatistheworst-casetimeComplexityofbuildingaheapbyinsertion?6.Isaheapfullorcompletebinarytree?7.WhatistheworsttimeruntimeComplexityofsortinganarrayofNelementsusingheapsort?8.Givenasequenceofnumbers:1,2,3,4,5,6,7,8,9

a.DrawabinaryMin-heapbyinsertingtheabovenumbersonebyoneb.AlsodrawthetreethatwillbeformedaftercallingDequeue()onthisheap

9.Givenasequenceofnumbers:1,2,3,4,5,6,7,8,9

a.DrawabinaryMax-heapbyinsertingtheabovenumbersonebyoneb.AlsodrawthetreethatwillbeformedaftercallingDequeue()onthisheap

10.Givenasequenceofnumbers:3,9,5,4,8,1,5,2,7,6.ConstructaMin-heapbycallingCreateHeap

function.11.ShowanarraythatwouldbetheresultafterthecalltodeleteMin()onthisheap12.Givenanarray:[3,9,5,4,8,1,5,2,7,6].Applyheapifyoverthistomakeaminheapandsortthe

elementsindecreasingorder?13.InHeap-Sortoncearootelementhasbeenputinitsfinalposition,howmuchtimedoesittaketore-

heapify the structure so that the next removal can take place? In other words, what is the TimeComplexityofasingleelementremovalfromtheheapofsizeN?

14.WhatdoyouthinktheoverallTimeComplexityforheapsortis?Whydoyoufeelthisway?

Page 359:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 360:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER12:HASH-TABLE

Page 361:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionIn the previous chapter, we have looked into various searching techniques. Consider a problem ofsearchingavalueinanarray.Ifthearrayisnotsortedthenwehavenootheroptionbuttolookintoeveryelementonebyoneso thesearchingTimeComplexitywillbeO(n). If thearray is sorted thenwecansearchthevaluewearelookingforinO(logn)logarithmictimeusingbinarysearch.Whatifwehaveafunctionthatcantellusthelocation/indexofthevaluewearelookingforinthearray?WecandirectlygointothatlocationandtellwhetherourobjectwearesearchingforispresentornotinjustO(1)constanttime.SuchafunctioniscalledaHashfunction.In real lifewhena letter ishandedover toapostman,by lookingat theaddresson the letter,postmanpreciselyknowstowhichhousethisletterneedstobedelivered.Heisnotgoingtoaskforapersondoortodoor.

Theprocessofstoringobjectsusingahashfunctionisasfollows:1.CreateanarrayofsizeMtostoreobjects,thisarrayiscalledHash-Table.2.Findahashcodeofanobjectbypassingitthroughthehashfunction.3.TakemoduleofhashcodebythesizeofHashtabletogettheindexofthetablewhereobjectswillbestored.4.Finallystoretheseobjectsinthedesignatedindex.TheprocessofsearchingobjectsinHash-Tableusingahashfunctionisasfollows:1.Findahashcodeoftheobjectwearesearchingforbypassingitthroughthehashfunction.2. Takemodule of hash code by the size ofHashtable to get the index of the tablewhere objects arestored.3.Finally,retrievetheobjectfromthedesignatedindex.

Page 362:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Hash-TableAHash-Tableisadatastructure,whichmapskeystovalues.EachpositionoftheHash-Tableiscalledaslot.TheHash-Tableusesahash function tocalculatean indexofanarrayof slots.Weuse theHash-Tablewhenthenumberofkeysactuallystoredissmallrelativelytothenumberofpossiblekeys.

Hash-TableAbstractDataType(ADT)ADTofHash-Tablecontainsthefollowingfunctions:1.Insert(x),addobjectxtothedataset.2.Delete(x),deleteobjectxfromthedataset.3.Search(x),searchobjectxindataset.

HashFunctionAhashfunctionisafunction,whichgeneratesanindexinatableforagivenobject.Anidealhashfunctionshouldgenerateauniqueindexforeveryobjectiscalledtheperfecthashfunction.Example12.1:MostsimplehashfunctionunsignedintHash(intkey,inttableSize)//divisionmethod

unsignedinthashValue=0;hashValue=key;returnhashValue%tableSize;

Therearemanyhashfunctions,butthisistheminimumthatitshoulddo.Varioushashgenerationlogicswillbeaddedtothisfunctiontogenerateabetterhash.

Propertiesofgoodhashfunction:1. It should provide a uniform distribution of hash values. A non-uniform distribution increased the

numberofcollisionsandthecostofresolvingthem.2.Choose a hash function,which can be computed quickly and returns valueswithin the range of the

Hash-Table.3. Chose a hash function with a good collision resolution algorithm which can be used to compute

alternativeindexifthecollisionoccurs.4.Chooseahashfunction,whichusesthenecessaryinformationprovidedinthekey.5.Itshouldhavehighloadfactorforagivensetofkeys.

LoadFactorLoadfactor=NumberofelementsinHash-Table/Hash-TablesizeBased on the above definition, Load factor tells whether the hash function is distributing the keysuniformlyornot.Therefore,ithelpsindeterminingtheefficiencyofthehashingfunction.Italsoworksas

Page 363:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

decisionparameterwhenwewanttoexpandorrehashtheexistingHash-Tableentries.

CollisionsWhenahashfunctiongeneratesthesameindexforthetwoormoredifferentobjects,theproblemknownasthecollision.Ideally,hashfunctionshouldreturnauniqueaddressforeachkey,butpracticallyitisnotpossible.

CollisionResolutionTechniquesHashcollisionsarepracticallyunavoidablewhenhashinglargenumberofobjects.Techniques,whichareusedtofindthealternatelocationintheHash-Table,iscalledcollisionresolution.Thereareanumberofcollisionresolutiontechniquestohandlethecollisioninhashing.Mostcommonandwidelyusedtechniquesare:·Openaddressing·Separatechaining

Page 364:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

HashingwithOpenAddressing

When using linear open addressing, the Hash-Table is represented by a one-dimensional array withindicesthatrangefrom0tothedesiredtablesize-1.Onemethodof resolvingcollision is the look intoaHash-Tableandfindanother freeslot thehold theobjectthathavecausedthecollision.Asimplewayistomovefromoneslottoanotherinsomesequentialorderuntilwefindafreespace.ThiscollisionresolutionprocessiscalledOpenAddressing.

LinearProbingInLinearProbing,wetrytoresolvethecollisionofanindexofaHash-TablebysequentiallysearchingtheHash-Tablefreelocation.Letussuppose,ifkistheindexretrievedfromthehashfunction.Ifthekthindexisalreadyfilledthenwewilllookfor(k+1)%M,then(k+2)%Mandsoon.Whenwegetafreeslot,wewillinserttheobjectintothatfreeslot.Example12.2:TheresolverfunctionoflinearprobingintresolverFun(inti)

returni;

QuadraticProbingIn Quadratic Probing, we try to resolve the collision of the index of a Hash-Table by quadratic allyincreasingthesearchindexfreelocation.Letussuppose,ifkistheindexretrievedfromthehashfunction.Ifthekthindexisalreadyfilledthenwewilllookfor(k+1^2)%M,then(k+2^2)%Mandsoon.Whenwegetafreeslot,wewillinserttheobjectintothatfreeslot.Example12.3:TheresolverfunctionofquadraticprobingintresolverFun(inti)

returni*i;Tablesizeshouldbeaprimenumbertopreventearlyloopingshouldnotbetoocloseto2powN

LinearProbingimplementationExample12.4:BelowisalinearprobingcollisionresolutionHash-Tableimplementation.#defineTABLE_SIZE50#defineEMPTY_NODE-1#defineLAZY_DELETED-2Table array size will be 50 and we have defined two constant values EMPTY_NODE andLAZY_DELETED.

Page 365:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

unsignedintComputeHash(intkey,inttableSize)//divisionmethod

unsignedinthashValue=0;hashValue=key;returnhashValue%tableSize;

Thisisthemostsimplehashgenerationfunction,whichjusttakethemodulusofthekey.intResolverFun(inti)

returni;Whenthehashindexisalreadyoccupiedbysomeelementthevaluewillbeplacedinsomeotherlocationtofindthatnewlocationresolverfunctionisused.structhashash_t

inttableSize;int*intArray;

;typedefhashash_t*hashPtr;Hash-Tablehastwocomponentoneistablesizeandotherispointertoarray.hashPtrHashInitialize()

hashPtrhash;hash=(hashPtr)malloc(sizeof(hashash_t));

hash->tableSize=TABLE_SIZE;hash->intArray=(int*)malloc(hash->tableSize*sizeof(int));

for(inti=0;i<hash->tableSize;i++)hash->intArray[i]=EMPTY_NODE;

returnhash;

HashInitializeis thefirstfunction,whichwill initialize theHash-Table.This is thefirstfunctioncalledafteraHash-Tablebeforeanyinsert,searchordeleteoperation.Example12.5:intHashInsert(hashPtrhash,intvalue)

inthashValue=ComputeHash(value,hash->tableSize);inti=0;for(i=0;i<hash->tableSize;i++)

Page 366:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if (hash->intArray[hashValue] == EMPTY_NODE || hash->intArray[hashValue] ==LAZY_DELETED)

hash->intArray[hashValue]=value;return1;hashValue=hashValue+ResolverFun(i);hashValue=hashValue%hash->tableSize;return-1;

Aninsertnodefunctionisusedtoaddvaluestothearray.Firsthashiscalculated.ThenwetrytoplacethatvalueintheHash-Table.Welookforemptynodeorlazydeletednodetoinsertvalue.Incaseinsertdidnotsuccess,wetrynewlocationusingaresolverfunction.Example12.6:intHashFind(hashPtrhash,intvalue)

inthashValue=ComputeHash(value,hash->tableSize);for(inti=0;i<hash->tableSize;i++)if(hash->intArray[hashValue]==value||hash->intArray[hashValue]==EMPTY_NODE)break;hashValue=hashValue+ResolverFun(i);hashValue=hashValue%hash->tableSize;

if(hash->intArray[hashValue]==value)returnhashValue;elsereturn-1;//valuenotfound

Findnodefunctionisusedtosearchvaluesinthearray.Firsthashiscalculated.ThenwetrytofindthatvalueintheHash-Table.Welookforoverdesiredvalueoremptynode.Incasewefindthevaluethatwearelooking,thenwereturnthatvalueorwereturn-1.Weusearesolverfunctiontofindthenextprobableindextosearch.Example12.7:intHashDelete(hashPtrhash,intvalue)

Page 367:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

inthashValue=ComputeHash(value,hash->tableSize);

for(inti=0;i<hash->tableSize;i++)if(hash->intArray[hashValue]==EMPTY_NODE)return-1;

if(hash->intArray[hashValue]==value)hash->intArray[hashValue]=LAZY_DELETED;return1;//deletedproperly

hashValue=hashValue+ResolverFun(i);hashValue=hashValue%hash->tableSize;return-1;//valuenotfound

DeletenodefunctionisusedtodeletevaluesfromaHashtable.WedonotactuallydeletethevaluewejustmarkthatvalueasLAZY_DELETED.SameastheinsertandsearchweuseresolverFuntofindthenextprobablelocationofthekey.Example12.8:voidPrintHash(hashPtrhash,inttableSize)//printkeywisevalues

for(inti=0;i<hash->tableSize;i++)printf("index%dvalue::%d\n",i,hash->intArray[i]);

intmain()

hashPtrmyHash=HashInitialize();for(inti=100;i<110;i++)HashInsert(myHash,i);printf("search100::%d\n",HashFind(myHash,100));printf("remove100::%d\n",HashDelete(myHash,100));printf("search100::%d\n",HashFind(myHash,100));printf("remove100::%d\n",HashDelete(myHash,100));PrintHash(myHash,TABLE_SIZE);

QuadraticProbingimplementation.

Page 368:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Everythingwillbesameaslinearprobingimplementationonlyresolverfunctionwillbechanged.intresolverFun(inti)

returni*i;

Page 369:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

HashingwithSeparate-ChainingAnothermethodforcollisionresolutionisbasedonanideaofputtingthekeysthatcollideinalinkedlist.Thismethodiscalledseparatechaining.TospeedupsearchweuseInsertion-Sortorkeepingthelinkedlistsorted.

SeparateChainingimplementation‘Example12.9:Belowisseparatechainingimplementationofhashtables.#defineTABLE_SIZE517#defineTABLE_BITS9structlistNode_t

intvalue;listNode_t*next;

;typedeflistNode_t*ptrList;structhashTable_t

inttableSize;ptrList*listArray;//doublepointer

;typedefhashTable_t*hashPtr;unsignedintComputeHash(intkey,inttableSize)//divisionmethod

unsignedinthashValue=0;hashValue=key;returnhashValue%tableSize;

hashPtrHashInitialize(intsize)

Page 370:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

hashPtrhTable=(hashPtr)malloc(sizeof(hashTable_t));hTable->tableSize=size;hTable->listArray=(ptrList*)malloc(hTable->tableSize*sizeof(ptrList));

for(inti=0;i<hTable->tableSize;i++)hTable->listArray[i]=NULL;returnhTable;

voidPrintHash(hashPtrhTable,inttableSize)//printkeywisevalues

for(inti=0;i<hTable->tableSize;i++)printf("\nPrintingforindexvalue::(%d)Listofvalueprinting::",i);ptrListhead=hTable->listArray[i];while(head)printf("%d",head->value);head=head->next;

intHashFind(hashPtrhTable,intvalue)

ptrListpossition;intindex=ComputeHash(value,hTable->tableSize);possition=hTable->listArray[index];while(possition&&possition->value!=value)possition=possition->next;return!(possition==NULL);

voidHashInsert(hashPtrhTable,intvalue)

intindex=ComputeHash(value,hTable->tableSize);ptrListtempPtr=(ptrList)malloc(sizeof(listNode_t));tempPtr->value=value;tempPtr->next=hTable->listArray[index];hTable->listArray[index]=tempPtr;

Page 371:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

intHashDelete(hashPtrhTable,intvalue)

ptrListcurrNode,nextNode;intindex=ComputeHash(value,hTable->tableSize);currNode=hTable->listArray[index];

if(currNode&&currNode->value==value)hTable->listArray[index]=currNode->next;free(currNode);return1;while(currNode)nextNode=currNode->next;if(nextNode&&nextNode->value==value)currNode->next=nextNode->next;free(nextNode);return1;elsecurrNode=nextNode;return0;

intmain()

hashPtrmyTable=HashInitialize(TABLE_SIZE);for(inti=100;i<110;i++)HashInsert(myTable,i);printf("search100::%d\n",HashFind(myTable,100));printf("remove100::%d\n",HashDelete(myTable,100));printf("search100::%d\n",HashFind(myTable,100));printf("remove100::%d\n",HashDelete(myTable,100));PrintHash(myTable,TABLE_SIZE);

Note: It is important tonote that the sizeof the“skip”mustbe such that all the slots in the tablewilleventuallybeoccupied.Otherwise,partofthetablewillbeunused.Toensurethis,itisoftensuggestedthatthetablesizebeingaprimenumber.Thisisthereasonwehavebeenusing11inourexamples.

Page 372:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinHashing

AnagramsolverAnanagramisawordorphraseformedbyreorderingthelettersofanotherwordorphrase.Example12.10:Twowordsareanagramiftheyareofsamesizeandtheircharactersaresame.intisAnagram(charstr1[],charstr2[])

intcurr=0;intsize1=strlen(str1);intsize2=strlen(str2);if(size1!=size2)return0;hashPtrpHash=HashInitialize();

while(str1[curr])HashInsert(pHash,str1[curr]);curr++;curr=0;

while(str2[curr])if(!HashDelete(pHash,str2[curr]))return0;curr++;return1;

RemoveDuplicateRemoveduplicatesinanarrayofnumbers.Solution:Wecanuseasecondarrayorthesamearray,astheoutputarray.InthebelowexampleHash-Tableisusedtosolvethisproblem.Example12.11:voidremoveDuplicate(charstr[])

intcurr=0,end=0;intsize=strlen(str);hashPtrpHash=HashInitialize();

Page 373:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

while(str[curr])if(!HashFind(pHash,str[curr]))str[end++]=str[curr];HashInsert(pHash,str[curr]);curr++;str[end]='\0';

FindMissingExample12.12:Findthemissingnumberinthelistofintegers.intfindMissing(intarr[],intsize)

intcurr=0;intn=size+1;hashPtrpHash=HashInitialize();

while(arr[curr])HashInsert(pHash,arr[curr]);curr++;

for(curr=1;curr<=n;curr++)if(!HashFind(pHash,curr))returncurr;return1;

PrintRepeatingExample12.13:Printtherepeatingintegerinalistofintegers.voidprintRepeating(intarr[],intsize)

inti;hashPtrpHash=HashInitialize();printf("Repeatingelementsare");

Page 374:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

for(i=0;i<size;i++)if(HashFind(pHash,arr[i]))printf("%d",arr[i]);elseHashInsert(pHash,arr[i]);

PrintFirstRepeatingExample12.14:Sameastheaboveprobleminthisweneedtoprintthefirstrepeatingnumber.Cautionshouldbetakentofindthefirstrepeatingnumber.Itshouldbethenumberwhichisrepeating.Forexample1,2,3,2,1.Theanswershouldbe1asitisthefirstnumber,whichisrepeating.voidprintFirstRepeating(intarr[],intsize)

inti;hashPtrpHash=HashInitialize();

for(i=0;i<size;i++)HashInsert(pHash,arr[i]);for(i=0;i<size;i++)HashDelete(pHash,arr[i]);

if(HashFind(pHash,arr[i]))printf("FirstRepeatingnumberis:%d",arr[i]);return;

Page 375:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise1.Designanumber(ID)generatorsystemthatgeneratenumbersbetween0-99999999(8-digits).

Thesystemshouldsupporttwofunctions:a)intgetNumber();b)intrequestNumber();

getNumber()functionshouldfindoutanumberthatisnotassigned,thenmarksitasassignedandreturnthatnumber.requestNumber()functionchecksthenumberisassignedornot.Ifitisassignedreturns0,elsemarksitasassignedandreturn1.Hint:Youcankeepacounter forassigningnumbers.Whenever there isagetNumber()callyouwillcheckif thatnumber isalreadyassignedinaHash-Table.If it isalreadyassigned, thenincrease thecounter and check again. If you find a number not in the Hash-Table then add it to Hashtable andincreasethecounter.requestNumber()willlookintheHash-Tableifthenumberisalreadytaken,thenitwillreturn0elseitwillreturn1andmarkthatnumberastakeninsidetheHash-Table.

2.Givenalargestring,findthemostoccurringwordsinthestring.WhatistheTimeComplexityofthe

abovesolution?Hint:-

a.CreateaHashtablewhichwillkeeptrackof<word,frequency>b.IteratethroughthestringandkeeptrackofwordfrequencybyinsertingintoHash-Table.c. When we have a new word, we will insert it into the Hashtable with frequency 1. For all

repetitionoftheword,wewillincreasethefrequency.d.Wecankeeptrackofthemostoccurringwordswheneverweareincreasingthefrequencywecan

seeifthisisthemostoccurringwordornot.e.TheTimeComplexityisO(n)wherenisthenumberofwordsinthestringandSpaceComplexity

istheO(m)wheremistheuniquewordsinthestring.3.Intheabovequestion,WhatifyouaregivenwholeworkofOSCARWILDE,mostpopularplaywrights

intheearly1890s.Hint:-

a.Whoknowshowmanybooksarethere,letusassumethereisalotandwecannotputeverythinginmemory.First,weneedaStreamingLibraryso thatwecanreadsectionbysection ineachdocument.Thenweneed a tokenizer,whichwill givewords to our program. In addition,weneedsomesortofdictionaryletussaywewilluseHashTable.

b.Whatyouneedis-1.Astreaminglibrarytokenizer,2.Atokenizer3.AhashmapMethod:1.Usestreamerstofindastreamofthegivenwords2.Tokenizetheinputtext3.Ifthestemmedwordisinhashmap,incrementitsfrequencycountelseaddsawordtohashmapwithfrequency1

c.Wecanimprovetheperformancebylookingintoparallelcomputing.Wecanusethemap-reduce

Page 376:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

tosolvethisproblem.Multiplenodeswillreadandprocessmultipledocuments.Oncetheyaredonewiththeirprocessing,thenwecanusereducetomergethem.

4.Intheabovequestion,WhatifwewantedtofindthemostcommonPHRASEinhiswritings.

Hint:-We can keep <phrase, frequency> Hash-Table and do the same process of the 2nd and 3rdproblems.

5.Writeahashingalgorithmforstrings.

Hint:UseHorner'smethodinthornerHash(char*key,inttableSize)

intsize=strlen(key);inth=0;inti;for(i=0;i<size;i++)h=(32*h+key[i])%tableSize;returnh;

6.PicktwodatastructurestouseinimplementingaMap.Describelookup,insert,&deleteoperations.Givetime&SpaceComplexityforeach.Givepros&consforeach.Hint:-a)LinkedList

I.InsertisO(1)II.DeleteisO(1)III.LookupisO(1)auxiliaryandO(N)worstcase.IV.Pros:Fastinsertsanddeletes,canuseforanydatatype.V.Cons:Slowlookups.

b)BalancedSearchTree(RBTree)I.InsertisO(logn)II.DeleteisO(logn)III.LookupisO(logn)IV.Pros:Reasonablyfastinserts/deletesandlookups.V.Cons:Dataneedstohaveorderdefinedonit.

Page 377:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 378:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER13:GRAPHS

Page 379:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionInthischapter,wewillstudyaboutGraphs.Graphscanbeusedtorepresentmanyinterestingthingsintherealworld.Flightsfromcities tocities, rodsconnectingvarious townandcities.Even thesequenceofstepsthatwetaketobecomereadyforjobsdaily,orevenasequenceofclassesthatwetaketobecomeagraduate incomputerscience.Oncewehaveagoodrepresentationof themap, thenweuseastandardgraphalgorithmstosolvemanyinterestingproblemsofreallife.The flight connectionbetweenmajor citiesof India canalsobe representedby thebelowgraph.Eachnodeisacityandeachedgeisastraightflightpathfromonecitytoanother.YoumaywanttogofromDelhi toChennai, ifgiven thisdata ingood representation to a computer, throughgraphalgorithms thecomputermayproposeshortest,quickestorcheapestpathfromsouredtodestination.

Googlemapthatweuseisalsoabiggraphoflotsofnodesandedges.Thensuggestshortestandquickestpathtotheuser.GraphDefinitionsAGraphisrepresentedbyGwhereG=(V,E),whereVisafinitesetofpointscalledVerticesandEisafinitesetofEdges.Eachedgeisatuple(u,v)whereu,v∈V.Therecanbeathirdcomponentweighttothetuple.Weightiscosttogofromonevertextoanother.Edge inagraphcanbedirectedorundirected. If theedgesofgraphareoneway it iscalledDirectedgraphorDigraph.ThegraphwhoseedgesaretwowaysarecalledUndirectedgraphorjustgraph.APath isasequenceofedgesbetween twovertices.The lengthofapath isdefinedas thesumof theweightofalltheedgesinthepath.Twoverticesuandvareadjacentifthereisanedgewhoseendpointsareuandv.Inthebelowgraph:V=V1,V2,V3,V4,V5,V6,V7,V8,V9,

Page 380:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

E=

Thein-degreeofavertexv,Donetedbyindeg(v)isthenumberofincomingedgestothevertexv.Theout-degreeofavertexv,Donetedbyoutdeg(v)isthenumberofoutgoingedgesofavertexv.Thedegreeofavertexv,Donetedbydeg(v)isthetotalnumberofedgeswhoseoneendpointisv.deg(v)=Indeg(v)+outdeg(v)Intheabovegraphdeg(V4)=3,indeg(V4)=2andoutdeg(V4)=1ACycleisapaththatstartsandendsatthesamevertexandincludeatleastonevertex.AnedgeisaSelf-Loopiftwoifitstwoendpointscoincide.Thisisaformofacycle.AvertexvisReachable fromvertexuor“ureachesv”if thereisapathfromutov.Inanundirectedgraphifvisreachablefromuthenuisreachablefromv.However,inadirectedgraphitispossiblethatureachesvbutthereisnopathfromvtou.AgraphisConnectedifforanytwoverticesthereisapathbetweenthem.AForestisagraphwithoutcycles.ASub-GraphofagraphGisagraphwhoseverticesandedgesareasubsetoftheverticesandedgesofG.ASpanningSub-GraphofGisagraphthatconnectsalltheverticesofG.ATreeisaacyclicconnectedgraph.ASpanningtreeofagraphisaspanningsub-graph,whichisalsoatreethatmeans,aconnectedgraph,whichconnectsalltheverticesofgraphandthat,doesnothaveacycle.

Page 381:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 382:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

GraphRepresentationInthissection,weintroducethedatastructureforrepresentingagraph.Inthebelowrepresentationswemaintainacollectiontostoreedgesandverticesofthegraph.

Page 383:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

AdjacencyMatrixOneof theways to represent a graph is to use two-dimensionalmatrix.Each combinationof rowandcolumnrepresentavertexinthegraph.Thevaluestoredatthelocationrowvandcolumnwistheedgefromvertexvtovertexw.Thenodesthatareconnectedbyanedgearecalledadjacentnodes.ThismatrixisusedtostoreadjacentrelationsoitiscalledtheAdjacencyMatrix.Inthebelowdiagram,wehaveagraphanditsAdjacencymatrix.

Intheabovegraph,eachnodehasweight1sotheadjacencymatrixhasjust1sor0s.Iftheedgesareofdifferent,weightsthatthatweightwillbefilledinthematrix.Pros:Adjacencymatriximplementationissimple.Adding/RemovinganedgebetweentwoverticesisjustO(1).QueryifthereisanedgebetweentwoverticesisalsoO(1)Cons:ItalwaysconsumesO(V2)space,whichisaninefficientwaytostorewhenagraphisasparse.SparseMatrix: In a huge graph, each node is connected with fewer nodes. So most of the places inadjacencymatrix are empty. Suchmatrix is called sparsematrix. Inmost of the real world problemsadjacencymatrixisnotagoodchoiceforsoregraphdata.

Page 384:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

AdjacencyListAmorespaceefficientwayofstoringgraphisadjacencylist.Inadjacencylistofpointerstoalinkedlistnode.Eachpointercorrespondstoverticesinagraph.Eachpointerwillthenpointtothevertices,whichareconnectedtoitandstorethisasalist.Inthebelowdiagramnode2isconnectedto1,3and4.Therefore,thepointeratlocation2ispointingtoalistthatcontain1,3and4.

Theadjacencylisthelpsustorepresentasparsegraph.Anadjacencylistrepresentationalsoallowsustofind all the vertices that are directly connected to any vertices by just one link list scan. In all ourprograms,wearegoingtousetheadjacencylisttostorethegraph.BelowisCcodeforadjacencylistrepresentationofanundirectedgraph:Example13.1:structListNode

intweight;intindex;ListNode*next;

;typedefListNode*ListPtr;typedefstructGraph_t

ListPtr*dpHead;intcount;

Graph;typedefGraph*GraphPtr;voidGraphInit(GraphPtrpGraph,intnodeCount)//oneextrasentinelforease

ListPtr*dpHead=(ListPtr*)malloc((nodeCount)*sizeof(ListPtr));for(inti=0;i<=nodeCount;i++)dpHead[i]=NULL;pGraph->dpHead=dpHead;pGraph->count=nodeCount;

Page 385:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

intGraphInsert(GraphPtrG,intsrc,intdst,intweight)

ListPtrtemp=(ListPtr)malloc(sizeof(ListNode));temp->weight=weight;temp->index=dst;temp->next=G->dpHead[src];G->dpHead[src]=temp;return1;

voidUndirectedGraphInsert(GraphPtrG,intsrc,intdst,intweight)

GraphInsert(G,src,dst,weight);GraphInsert(G,dst,src,weight);

voidGraphPrint(GraphPtrG)

intcount=G->count,index;for(index=0;index<count;index++)ListPtrhead=G->dpHead[index];printf("\nAdjacencylistofindex%dare[",index);while(head)printf("%d",head->index);head=head->next;printf("]\n");

intmain()

intnodeCount=8;Graphgph;GraphInit(&gph,nodeCount);UndirectedGraphInsert(&gph,0,1,1);UndirectedGraphInsert(&gph,0,2,1);UndirectedGraphInsert(&gph,0,3,1);UndirectedGraphInsert(&gph,1,4,1);UndirectedGraphInsert(&gph,2,5,1);UndirectedGraphInsert(&gph,3,6,1);

Page 386:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

UndirectedGraphInsert(&gph,4,7,1);UndirectedGraphInsert(&gph,5,7,1);UndirectedGraphInsert(&gph,6,7,1);GraphPrint(&gph);return0;

Page 387:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

GraphtraversalsTheDepthfirstsearch(DFS)andBreadthfirstsearch(BFS)arethetwoalgorithmsusedtotraverseagraph.Thesesamealgorithmscanalsobeusedtofindsomenodeinthegraph,findifanodeisreachableetc.Traversalistheprocessofexploringagraphbyexaminingallitsedgesandvertices.Alistofsomeoftheproblemsthataresolvedusinggraphtraversalare:1.Determiningapathfromvertexutovertexv,orreportanerrorifthereisnosuchpath.2.Givenastartingvertexs,findingtheminimumnumberofedgesfromvertexstoalltheotherverticesof

thegraph.3.TestingofagraphGisconnected.4.FindingaspanningtreeofaGraph.5.Findingifthereissomecycleinthegraph.

Page 388:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DepthFirstTraversalTheDFSalgorithmwestartfromstartingpointandgointodepthofgraphuntilwereachadeadendandthenmoveup toparentnode(Backtrack). InDFS,weusestack toget thenextvertex tostartasearch.Alternatively,wecanuserecursion(systemstack)todothesame.

AlgorithmstepsforDFS1.Pushthestartingnodeinthestack.2.Loopuntilthestackisempty.3.Popthenodefromthestackinsideloopcallthisnodecurrent.4.Processthecurrentnode.//Print,etc.5.Traverseallthechildnodesofthecurrentnodeandpushthemintostack.6.Repeatsteps3to5untilthestackisempty.

StackbasedimplementationofDFSExample13.2:voidDFSStack(GraphPtrG)

intcount=G->count;int*visited=(int*)malloc((count)*sizeof(int));intcurr;Stackstk;for(inti=0;i<count;i++)visited[i]=0;StackInitialize(&stk);visited[0]=1;StackPush(&stk,0);

while(!StackIsEmpty(&stk))curr=StackPop(&stk);printf("%d",curr);

Page 389:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ListPtrhead=G->dpHead[curr];while(head)if(!visited[head->index])visited[head->index]=1;StackPush(&stk,head->index);head=head->next;

RecursionbasedimplementationofDFSExample13.3:voidDFSRec(GraphPtrG,intindex,int*visited)

printf("%d",index);ListPtrhead=G->dpHead[index];while(head)if(!visited[head->index])visited[head->index]=1;DFSRec(G,head->index,visited);head=head->next;

voidDFS(GraphPtrG)

intcount=G->count;int*visited=(int*)malloc((count)*sizeof(int));for(inti=0;i<count;i++)visited[i]=0;

for(inti=0;i<count;i++)if(visited[i]==0)visited[i]=1;DFSRec(G,i,visited);

Page 390:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 391:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BreadthFirstTraversalInBFS algorithm, a graph is traversed in layer-by-layer fashion. The graph is traversed closer to thestartingpoint.ThequeueisusedtoimplementBFS.

AlgorithmstepsforBFS1.PushthestartingnodeintotheQueue.2.LoopuntiltheQueueisempty.3.RemoveanodefromtheQueueinsideloop,callthisnodecurrent.4.Processthecurrentnode.//printetc.5.TraverseallthechildnodesofthecurrentnodeandpushthemintoQueue.6.Repeatsteps3to5untilQueueisempty.Example13.4:voidBFSQueue(GraphPtrG,intindex,int*visited)

intcurr;Queueque;QueueInitialize(&que);

visited[index]=1;Enqueue(&que,index);

while(!QueueIsEmpty(&que))curr=Dequeue(&que);printf("%d",curr);ListPtrhead=G->dpHead[curr];while(head)if(!visited[head->index])

Page 392:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

visited[head->index]=1;Enqueue(&que,head->index);head=head->next;

voidBFS(GraphPtrG)

intcount=G->count;int*visited=(int*)malloc((count)*sizeof(int));for(inti=0;i<count;i++)visited[i]=0;

for(inti=0;i<count;i++)if(visited[i]==0)BFSQueue(G,i,visited);

AruntimeanalysisofDFSandBFStraversalisO(n+m)time,wherenisthenumberofedgesreachablefromsourcenodeandmisthenumberofedgesincidentons.ThefollowingproblemshaveO(m+n)timeperformance:1.Determiningapathfromvertexutovertexv,orreportanerrorifthereisnosuchpath.2.Givenastartingvertexs,findingtheminimumnumberofedgesfromvertexstoalltheotherverticesof

thegraph.3.TestingofagraphGisconnected.4.FindingaspanningtreeofaGraph.5.Findingifthereissomecycleinthegraph.

Page 393:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinGraph

DeterminingapathfromvertexutovertexvIFthereisapathfromutovandwearedoingDFSfromuthenvmustbevisited.Ifthereisnopaththenreportanerror.Example13.5:intPathExist(GraphPtrG,intsrc,intdst)

intcount=G->count;int*visited=(int*)malloc((count)*sizeof(int));for(inti=0;i<count;i++)visited[i]=0;visited[src]=1;DFSRec(G,src,visited);returnvisited[dst];

Givenastartingvertexs,findingtheminimumnumberofedgesfromvertexstoalltheotherverticesofthegraphLookforsinglesourceshortestpathalgorithmforeachedgecostas1unit.

TestingofagraphGisconnected.DoDFS search start from any arbitrary vertex. Find if there is a vertex that is not visited. If all theverticesarevisitedthenitisaconnectedgraph.Example13.6:intisConnected(GraphPtrG)

intcount=G->count;int*visited=(int*)malloc((count)*sizeof(int));for(inti=0;i<count;i++)visited[i]=0;visited[0]=1;DFSRec(G,0,visited);for(inti=0;i<count;i++)if(visited[i]==0)return0;return1;

Findingifthereissomecycleinthegraph.

Page 394:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ModifyDFSproblemandgetthisdone.

Page 395:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DirectedAcyclicGraphADirected Acyclic Graph (DAG) is a directed graph with no cycle. A DAG represent relationship,whichismoregeneralthanatree.BelowisanexampleofDAG,thisishowsomeonebecomesreadyforwork.ThereareNother real lifeexamplesofDAGsuchascoercesselection tobeinggraduatedfromcollege

Page 396:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TopologicalSortA topological sort is a method of ordering the nodes of a directed graph in which nodes representactivities and the edges represent dependency among those tasks.For topological sorting towork it isrequiredthatthegraphshouldbeaDAGwhichmeansitshouldnothaveanycycle.JustuseDFStogettopologicalsorting.Example13.7:voidTopologicalSort(GraphPtrG)

Stackstk;StackInitialize(&stk);intcount=G->count;int*visited=(int*)malloc((count)*sizeof(int));for(inti=0;i<count;i++)visited[i]=0;for(inti=0;i<count;i++)if(visited[i]==0)visited[i]=1;TopologicalSortDFS(G,i,visited,&stk);while(!StackIsEmpty(&stk))printf("%d",StackPop(&stk));

voidTopologicalSortDFS(GraphPtrG,intindex,int*visited,Stack*stk)

ListPtrhead=G->dpHead[index];while(head)if(!visited[head->index])visited[head->index]=1;TopologicalSortDFS(G,head->index,visited,stk);head=head->next;StackPush(stk,index);

Page 397:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

MinimumSpanningTrees(MST)ASpanningTreeofagraphGisatreethatcontainsalltheedgesoftheGraphG.AMinimumSpanningTreeisatreewhosesumoflength/weightofedgesisminimumaspossible.Forexample, ifyouwanttosetupcommunicationbetweenasetofcities, thenyoumaywant tousetheleastamountofwireaspossible.MSTcanbeusedtofindthenetworkpathandwirecostestimate.

Prim’sAlgorithmforMSTPrim’salgorithmgrowsasingletreeT,oneedgeatatime,untilitbecomesaspanningtree.WeinitializeTwithzeroedges.Uwithsinglenode.WhereTisspanningtreeedgessetandUisspanningtreevertexset.Ateachstep,Prim’salgorithmaddsthesmallestvalueedgewithoneendpointinUandothernotinus.SinceeachedgeaddsonenewvertextoU,aftern−1additions,UcontainalltheverticesofthespanningtreeandTbecomesaspanningtree.Example13.8://ReturnstheMSTbyPrim’sAlgorithm//Input:AweightedconnectedgraphG=(V,E)//Output:SetofedgescomprisingaMSTAlgorithmPrim(G)

T=LetrbeanyvertexinGU=rfori=1to|V|-1doe=minimum-weightedge(u,v)WithuinUandvinV-UU=U+v

Page 398:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

T=T+ereturnT

Prim’sAlgorithmusingapriorityqueue(minheap)togettheclosestfringevertexTimeComplexitywillbeO(mlogn)wherenverticesandmedgesoftheMST.Example13.9:voidPrimMST(GraphPtrG)

inti,src=1;intcount=G->count;//Getthenumberofverticesingraphint*distance=(int*)malloc((count)*sizeof(int));int*path=(int*)malloc((count)*sizeof(int));

Heapque;HeapInitialize(&que,100);

for(i=0;i<count;i++)distance[i]=-1;

ListPtrhead;Edgee;e.src=src;e.dst=src;e.weight=0;HeapInsert(&que,e);distance[src]=0;path[src]=-1;Edgecurr;while(que.Size)curr=HeapDeleteMin(&que);head=G->dpHead[curr.dst];

while(head)intdisUpdate=head->weight;if(distance[head->index]==-1||distance[head->index]>disUpdate)distance[head->index]=disUpdate;path[head->index]=curr.dst;e.src=curr.dst;e.dst=head->index;e.weight=distance[head->index];HeapInsert(&que,e);

Page 399:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

head=head->next;for(inti=0;i<count;i++)printf("%dto%dweight%d\n",path[i],i,distance[i]);

Kruskal’sAlgorithmKruskal’sAlgorithmrepeatedlychoosesthesmallest-weightedgethatdoesnotformacycle.Sorttheedgesinnon-decreasingorderofcost:c(e1)≤c(e2)≤···≤c(em).SetTtobetheemptytree.Addedgestotreeonebyoneifitdoesnotcreateacycle.Example13.10://ReturnstheMSTbyKruskal’sAlgorithm//Input:AweightedconnectedgraphG=(V,E)//Output:SetofedgescomprisingaMSTAlgorithmKruskal(G)

SorttheedgesEbytheirweightsT=while|T|+1<|V|doe=nextedgeinEifT+edoesnothaveacyclethenT=T+ereturnT

Kruskal’sAlgorithmisO(ElogV)usingefficientcycledetection.

Page 400:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ShortestPathAlgorithmsinGraph

SingleSourceShortestPathForagraphG=(V,E), thesinglesourceshortestpathproblemis tofindtheshortestpathfromagivensourcevertexstoalltheverticesofV.

SingleSourceShortestPathforunweightedGraph.Findsinglesourceshortestpathforunweightedgraphoragraphwhosealltheverticeshavesameweight.Example13.11:voidShortestPath(GraphPtrG,intsrc)

intcurr;intcount=G->count;int*distance=(int*)malloc((count)*sizeof(int));int*path=(int*)malloc((count)*sizeof(int));

Queueque;QueueInitialize(&que);

for(inti=0;i<count;i++)distance[i]=-1;

Enqueue(&que,src);distance[src]=0;

while(!QueueIsEmpty(&que))curr=Dequeue(&que);ListPtrhead=G->dpHead[curr];while(head)if(distance[head->index]==-1)distance[head->index]=distance[curr]+1;path[head->index]=curr;Enqueue(&que,head->index);head=head->next;for(inti=0;i<count;i++)printf("%dto%dweight%d\n",path[i],i,distance[i]);

Page 401:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Dijkstra’salgorithmDijkstra’salgorithmforsingle-sourceshortestpathproblemforweightededgeswithnonegativeweight.GivenaweightedconnectedgraphG, find shortest paths from the sourcevertex s to eachof theothervertices.Dijkstra’salgorithmissimilartoprimsalgorithm.Itmaintainsasetofnodesforwhichshortestpathisknown.

Thealgorithmstartsbykeepingtrackofthedistanceofeachnodeanditsparents.Allthedistanceissettoinfiniteinthebeginningaswedonotknowtheactualpathtothenodesandparentsofalltheverticesaresettonull.Alltheverticesareaddedtoapriorityqueue(minheapimplementation)Ateachstepalgorithmtakesonevertexfromthepriorityqueue(whichwillbethesourcevertexinthebeginning).Thenupdatethedistancearraycorrespondingtoalltheadjacentvertices.Whenthequeueisempty,thenwewillhavethedistanceandparentarrayfullypopulated.Example13.12://SolvesSSSPbyDijkstra’sAlgorithm//Input:AweightedconnectedgraphG=(V,E)//withnonegativeweights,andsourcevertexv//Output:ThelengthandpathfromstoeveryvAlgorithmDijkstra(G,s)

foreachvinVdoD[v]=infinite//UnknowndistanceP[v]=null//unknownpreviousnodeaddvtoPQ//addingallnodestopriorityqueue

D[source]=0//Distancefromsourcetosource

while(PQisnotempty)u=vertexfromPQwithsmallestD[u]removeufromPQforeachvadjacentfromudoalt=D[u]+length(u,v)

Page 402:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ifalt<D[v]thenD[v]=altP[v]=uReturnD[],P[]

TimeComplexitywillbeO(|E|log|V|)Note:Dijkstra’salgorithmdoesnotworkforgraphswithnegativeedgesweight.Note:Dijkstra’salgorithmisapplicabletobothundirectedanddirectedgraphs.Example13.13:voidDijkstraShortestPath(GraphPtrG,intsrc)

Edgecurr;inti;intcount=G->count;

int*distance=(int*)malloc((count)*sizeof(int));int*path=(int*)malloc((count)*sizeof(int));

Heapque;HeapInitialize(&que,100);

for(i=0;i<count;i++)distance[i]=-1;

ListPtrhead;Edgee;e.src=src;e.dst=src;e.weight=0;

HeapInsert(&que,e);distance[src]=0;path[src]=-1;

while(que.Size)curr=HeapDeleteMin(&que);head=G->dpHead[curr.dst];while(head)intdisUpdate=distance[curr.dst]+head->weight;if(distance[head->index]==-1||distance[head->index]>disUpdate)

Page 403:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

distance[head->index]=disUpdate;path[head->index]=curr.dst;e.src=curr.dst;e.dst=head->index;e.weight=distance[head->index];HeapInsert(&que,e);head=head->next;for(inti=0;i<count;i++)printf("%dto%dweight%d\n",path[i],i,distance[i]);

BellmanFordShortestPathThebellmanfordalgorithmworksevenwhen therearenegativeweightedges in thegraph. Itdoesnotworkifthereissomecycleinthegraphwhosetotalweightisnegative.Example13.14:#defineINF123456789voidBellmanFordShortestPath(GraphPtrG,intsrc)

intcurr;intcount=G->count;

int*distance=(int*)malloc((count)*sizeof(int));int*path=(int*)malloc((count)*sizeof(int));

for(inti=0;i<count;i++)distance[i]=INF;

distance[src]=0;

for(inti=0;i<count-1;i++)for(intj=0;j<count;j++)ListPtrhead=G->dpHead[j];while(head)intnewDistance=distance[j]+head->weight;if(distance[head->index]>newDistance)distance[head->index]=newDistance;

Page 404:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

path[head->index]=j;head=head->next;for(inti=0;i<count;i++)printf("%dto%dweight%d\n",path[i],i,distance[i]);

AllPairsShortestPathsGivenaweightedgraphG(V,E),theallpairshortestpathproblemistofindtheshortestpathbetweenallpairsofverticesu,vєV.Executeninstancesofsinglesourceshortestpathalgorithmforeachvertexofthegraph.ThecomplexityofthisalgorithmwillbeO(n3)

Page 405:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise1.Intheentirepath-findingalgorithm,wehavecreatedapatharraythatjuststoreimmediateparentofa

node,printthecompletepathforit.2.Allthefunctionsareimplementedconsideringasifthegraphisrepresentedbyadjacencylist.Towrite

allthosefunctionsforgraphrepresentationasadjacencymatrix.3.Givenastartstring,endstringandasetofstrings,findifthereexistsapathbetweenthestartstringand

endstringviathesetofstrings.

Apathexistsifwecangetfromstartstringtoendthestringbychanging(noaddition/removal)onlyonecharacteratatime.Therestrictionisthatthenewstringgeneratedafterchangingonecharacterhastobeintheset.Start:"cog"End:"bad"Set:["bag","cag","cat","fag","con","rat","sat","fog"]Oneofthepaths:"cog"->"fog"->"fag"->"bag"->"bad"

Page 406:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 407:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER14:STRINGALGORITHMS

Page 408:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionStringinClanguageisanarrayofcharacter.Weusestringalgorithminsomanytasks,whenweareusingsomecopy-paste,somestringreplacement,andsomestringsearch.Whenweareusingsomedictionaryprogram,we are using string algorithms.Whenwe are searching something in googlewe are passingsomeinformationthatisalsoastringandthatwillfurtherconvertandprocessedbygoogle.Note:Thischapterisveryimportantfortheinterviewpointofviewasmanyinterviewproblemsarefromthischapter.

Page 409:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

StringMatchingEverywordprocessingprogramhas a search function inwhichyou can search all occurrencesof anyparticularwordinalongtextfile.Forthis,weneedstring-matchingalgorithms.

BruteForceSearchWehaveapatternthatwewanttosearchinthetext.Thepatternisoflengthmandthetextisoflengthn.Wherem<n.Thebruteforcesearchalgorithmwillcheckthepatternatallpossiblevalueof“i”inthetextwherethevalueof“i”rangefrom0ton-m.Thepatterniscomparedwiththetext,characterbycharacterfromlefttoright.When amismatch is detected, then pattern is compared by shifting the comparewindowby onecharacter.Example14.1:intBruteForceSearch(char*text,char*pattern)

inti=0,j=0,count=0;constintn=strlen(text);constintm=strlen(pattern);

while(i<=n-m)j=0;while(j<m&&pattern[j]==text[i+j])j++;if(j==m)return(i);i++;return-1;

WorstcaseTimeComplexityofthealgorithmisO(m*n),wegotthepatternattheendofthetextorwedidnotgetthepatternatall.BestcaseTimeComplexityofthisalgorithmisO(m),theaverageTimeComplexityofthisalgorithmisO(n)

Robin-KarpalgorithmRobin-Karpalgorithmissomewhatsimilartothebruteforcealgorithm.Becausethepatterniscomparedto each textbox. Instead of pattern at each position a hash code is compared, only one comparison isperformed.Thehashcodeof thepattern iscomparedwith thehashcodeof the textwindow.Wetry tokeepthehashcodeasuniqueaspossible.

Page 410:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Thetwofeaturesofgoodhashcodeare:·Thecollisionshouldbeexcludedasmuchaspossible.·Thehashcodeoftextmustbecalculatedinconstanttime.

Acollisionoccurswhenhashcodematches,butthepatterndoesnot.Calculationinconstanttime,onememberleavesthewindowandanewnumberentersawindow.Multiplicationby2issameasleftshiftoperation.Multiplicationby2m-1issameasleftshiftm-1times.Wewantthismultipletimessojuststoreitinvariablepow(m)=2m-1Wedonotwanttodobigmultiplicationoperationssomodularoperationwithaprimenumberisused.Example14.2:intRobinKarp(char*text,char*pattern)

intn=strlen(text);intm=strlen(pattern);inti,j;intprime=101;intpowm=1;intTextHash=0,PatternHash=0;

if(m==0||m>n)return-1;

for(i=0;i<m-1;i++)powm=(powm<<1)%prime;

for(i=0;i<m;i++)PatternHash=((PatternHash<<1)+pattern[i])%prime;TextHash=((TextHash<<1)+text[i])%prime;

for(i=0;i<=(n-m);i++)if(TextHash==PatternHash)for(j=0;j<m;j++)if(text[i+j]!=pattern[j])break;

if(j==m)

Page 411:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

returni;TextHash=(((TextHash-text[i]*powm)<<1)+text[i+m])%prime;

if(TextHash<0)TextHash=(TextHash+prime);return-1;

Knuth-Morris-PrattalgorithmAfter a shift of the pattern, the brute force algorithm forgotten all the information about the previousmatchedsymbols.ThisisbecauseofwhichitsworstcaseTimeComplexityisO(mn).The Knuth-Morris-Pratt algorithm make use of this information that is computed in the previouscomparison.Itneverrecomparesthewholetext.Itusespre-processingofthepattern.Thepre-processingtakesO(m)timeandwholealgorithmisO(n)Pre-processingstep:wetrytofindtheborderofthepatternatadifferentprefixofthepattern.Aprefixisastringthatcomesatthestartofastring.Aproperprefixisaprefixthatisnotthecompletestring.Itslengthislessthanthelengthofthestring.Asuffixisastringthatcomesattheendofastring.Apropersuffixisasuffixthatisnotthecompletestring.Itslengthislessthanthelengthofthestring.Aborderisastringthatisbothproperprefixandapropersuffix.

Example14.3:voidKMPPreprocess(char*pattern,int*ShiftArr)

constintm=strlen(pattern);inti=0,j=-1;ShiftArr[i]=-1;while(i<m)while(j>=0&&pattern[i]!=pattern[j])j=ShiftArr[j];i++;

Page 412:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

j++;ShiftArr[i]=j;

Wehavetoloopouterloopforthetextandinnerloopforthepatternwhenwehavematchedthetextandpatternmismatch,weshiftthetextsuchthatthewidestborderisconsideredandthentherestofthepatternmatchingisresumedafterthisshift.Ifagainamismatchhappensthenthenextmismatchistaken.

Example14.4:intKMP(char*text,char*pattern)

inti=0,j=0,count=0;constintn=strlen(text);constintm=strlen(pattern);

int*ShiftArr=(int*)calloc(m+1,sizeof(int));

KMPPreprocess(pattern,ShiftArr);

while(i<n)while(j>=0&&text[i]!=pattern[j])j=ShiftArr[j];i++;j++;if(j==m)return(i-m);return-1;

Example14.5:UsethesameKMPalgorithmtofindthenumberofoccurrencesofthepatterninatext.intKMPFindCount(char*text,char*pattern)

Page 413:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

inti=0,j=0,count=0;constintn=strlen(text);constintm=strlen(pattern);int*ShiftArr=(int*)calloc(m+1,sizeof(int));

KMPPreprocess(pattern,ShiftArr);while(i<n)while(j>=0&&text[i]!=pattern[j])j=ShiftArr[j];

i++;j++;

if(j==m)count++;j=ShiftArr[j];returncount;

Page 414:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Dictionary/SymbolTableAsymboltableisamappingbetweenastring(key)andavaluethatcanbeofanytype.Avaluecanbeanintegersuchasoccurrencecount,dictionarymeaningofawordandsoon.

BinarySearchTree(BST)forStringsBinarySearchTree(BST)isthesimplestwaytoimplementsymboltable.Simplestrcmp()functioncanbeusedtocomparetwostrings.Ifallthekeysarerandom,andthetreeisbalanced.ThenonanaveragekeylookupcanbedoneinO(logn)time.

Below is an implementation of binary search tree to store string as key. This will keep track of theoccurrencecountofwordsinatext.Example14.6:1.#include<stdio.h>2.#include<stdlib.h>3.#include<string.h>4.#include<iostream>5.usingnamespacestd;6.7.structtreeNode_t8.char*value;9.intcount;10.treeNode_t*lChild;11.treeNode_t*rChild;12.;13.14.typedeftreeNode_t*treePtr;1.voidprintTree(treePtrroot)/*preorder*/2.3.if(root)4.5.cout<<"valueis::"<<root->value;

Page 415:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

6.cout<<"countis::"<<root->count<<endl;7.printTree(root->lChild);8.printTree(root->rChild);9.10.1.treePtrinsertNode(char*value,treePtrroot)2.3.intcompare;4.if(root==NULL)5.6.root=(treePtr)malloc(sizeof(treeNode_t));7.if(root==NULL)8.9.printf("fallelmemoryshortage...");10.returnroot;11.12.root->value=(char*)malloc((1+strlen(value))*sizeof(char));13.strcpy(root->value,value);14.root->lChild=root->rChild=NULL;15.root->count=1;16.17.else18.19.compare=strcmp(root->value,value);20.if(compare==0)21.22.root->count++;23.24.elseif(compare==1)25.26.root->lChild=insertNode(value,root->lChild);27.28.else29.30.root->rChild=insertNode(value,root->rChild);31.32.33.returnroot;34.1.voidinsertNode(char*value,treePtr*ptrRoot)2.3.*ptrRoot=insertNode(value,*ptrRoot);4.

Page 416:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

1.voidfreeTree(treePtr*rootPtr)2.3.*rootPtr=freeTree(*rootPtr);4.1.treePtrfreeTree(treePtrroot)2.3.if(root)4.5.freeTree(root->lChild);6.freeTree(root->rChild);7.free(root->value);8.free(root);9.10.returnNULL;11.1.treePtrfindNode(treePtrroot,char*value)2.3.intcompare;4.if(!root)5.returnNULL;6.compare=strcmp(root->value,value);7.if(compare==0)8.returnroot;9.else10.11.if(compare==1)12.returnfindNode(root->lChild,value);13.else14.returnfindNode(root->rChild,value);15.16.1.intfrequency(treePtrroot,char*value)2.3.intcompare;4.if(!root)5.return0;6.compare=strcmp(root->value,value);7.if(compare==0)8.returnroot->count;9.else10.

Page 417:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

11.if(compare==1)12.returnfrequency(root->lChild,value);13.else14.returnfrequency(root->rChild,value);15.16.1.intgetword(char*a,FILE*fp)2.3.inti=0;4.while(1)5.6.a[i]=getc(fp);7.if(a[i]==EOF)8.9.a[i]='\0';10.return0;11.12.elseif(a[i]==''||a[i]=='\t'||a[i]=='\n')13.14.a[i]='\0';15.return1;16.17.i++;18.19.1.intmain()2.3.4.treePtrroot=NULL;5.treePtrtemp=NULL;6.FILE*fp=fopen("binaryString.cpp","r");7.chara[100];8.while(getword(a,fp))9.10.root=insertNode(a,root);11.12.printTree(root);13.printf("\n");14.cout<<"quencyreturned::"<<frequency(root,"&&");15.printf("\n");16.

Page 418:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Hash-TableTheHash-Tableisanotherdatastructurethatcanbeusedforsymboltableimplementation.BelowHash-Tablediagram,wecanseethenameofthatpersonistakenasthekey,andtheirmeaningisthevalueofthesearch.Thefirstkeyisconvertedintoahashcodebypassingittoappropriatehashfunction.InsidehashfunctionthesizeofHash-Tableisalsopassed,whichisusedtofindtheactualindexwherevalueswillbestored.Finally,thevaluethatismeaningofnameisstoredintheHash-Table,oryoucanstoreareferencetothestringwhichstoremeaningcanbestoredintotheHash-Table.

Hash-TablehasanexcellentlookupofO(1).Let us supposewewant to implement autocomplete the box feature ofGoogle search.When you typesomestringtosearchingoogle,itproposesomecompletestringevenbeforeyouhavedonetyping.BSTcannotsolvethisproblemasrelatedstringscanbeinbothrightandleftsubtree.TheHash-Tableisalsonotsuitedfor this job.OnecannotperformapartialmatchorrangequeryonaHash-Table.Hash function transforms string to a number.Agoodhash functionwill give a distributedhashcodeevenforpartialstringandthereisnowaytorelatetwostringsinaHash-Table.TrieandTernarySearchtreeareaspecialkindoftreethatsolvespartialmatchandrangequeryproblemwell.

TrieTrieisatree,inwhichwestoreonlyonecharacterateachnode.Thisfinalkeyvaluepairisstoredintheleaves.EachnodehasRchildren,oneforeachpossiblecharacter.Forsimplicitypurpose,letusconsiderthatthecharactersetis26,correspondstodifferentcharactersofEnglishalphabets.Trie is an efficient data structure. Using Trie, we can search the key in O(M) time.WhereM is themaximumstringlength.Trieisalsosuitableforsolvingpartialmatchandrangequeryproblems.

Page 419:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example14.7:1.#include<iostream>2.usingnamespacestd;3.structtrieNode_t4.intflag;5.charch;6.trieNode_t*child[26];7.;8.typedeftrieNode_t*triePtr;1.triePtrcreateNode()2.3.triePtrtemp=(triePtr)malloc(sizeof(trieNode_t));4.for(inti=0;i<26;i++)5.temp->child[i]==NULL;6.returntemp;7.1.voidmyToLower(char*str)2.3.intlength=strlen(str);4.for(inti=0;i<length;i++)5.str[i]=tolower(str[i]);6.7.voidtrie(triePtrroot,char*str)8.

Page 420:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

9.if(*(str+1)=='\0')10.11.if(root->child[*str-'a']==NULL)12.13.root->child[*str-'a']=createNode();14.15.root->child[*str-'a']->flag=1;16.root->child[*str-'a']->ch=*str;17.return;18.19.else20.21.if(root->child[*str-'a']==NULL)22.23.root->child[*str-'a']=createNode();24.root->child[*str-'a']->flag=0;25.26.root->child[*str-'a']->ch=*str;27.trie(root->child[*str-'a'],(str+1));28.29.1.triePtrtrieInsert(triePtrroot,char*str)2.3.myToLower(str);4.if(str==NULL||*str=='\0')5.returnroot;6.if(root==NULL)7.8.root=createNode();9.trie(root,str);10.11.else12.13.trie(root,str);14.15.returnroot;16.1.intfindNode(triePtrroot,char*str)2.3.myToLower(str);4.if(str==NULL)5.6.cout<<"nodefound"<<endl;

Page 421:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

7.return0;8.9.if(root==NULL)10.11.cout<<"nodefound"<<endl;12.return0;13.14.while(root->child[*str-'a']&&*(str+1)!='\0'&&root->child[*str-'a']->ch==*str)15.16.root=root->child[*str-'a'];17.str++;18.19.//chardoesnotmatchorcharindexchilddoesnotexist20.if(!root->child[*str-'a']||root->child[*str-'a']->ch!=*str)21.22.cout<<"nodenotfound"<<endl;23.return0;24.25.if(*(str+1)=='\0')26.27.if(root->child[*str-'a']->ch==*str&&root->child[*str-'a']->flag==1)28.29.cout<<"nodefound"<<endl;30.return1;31.32.33.cout<<"nodenotfound"<<endl;34.return0;35.1.intmain()2.3.triePtrroot=NULL;4.chara[]="hemant";5.charb[]="heman";6.charc[]="hemantjain";7.chard[]="jain";8.root=trieInsert(root,a);9.root=trieInsert(root,d);10.printf(“%s”,findNode(root,a));11.printf(“%s”,findNode(root,b));12.printf(“%s”,findNode(root,c));13.printf(“%s”,findNode(root,d));14.

Page 422:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TernarySearchTrie/TernarySearchTreeTrieshaveaverygoodsearchperformanceofO(M)whereMisthemaximumsizeofthesearchstring.However, tries have a very high space requirement. Every node Trie contains references to multiplenodes,eachreferencecorrespondstopossiblecharactersofthekey.ToavoidthishighspacerequirementTernarySearchTrie(TST)isused.A TST avoid the heavy space requirement of the traditional Trie while still keeping many of itsadvantages. In aTST, eachnode contains a character, an endofkey indicator, and threepointers.Thethree pointers are corresponding to current char hold by the node (equal), characters less than andcharactergreaterthan.TheTimeComplexityofternarysearchtreeoperationisproportionaltotheheightoftheternarysearchtree.Intheworstcase,weneedtotraverseupto3timesthatmanylinks.However,thiscaseisrare.Therefore,TSTisaverygoodsolutionforimplementingSymbolTable,Partialmatchandrangequery.

Example14.8:structNode

chardata;unsignedisLastChar:1;structNode*left,*equal,*right;

;typedefNode*NodePtr;NodePtrnewNode(chardata)

NodePtrtemp=(NodePtr)malloc(sizeof(structNode));

Page 423:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

temp->data=data;temp->isLastChar=0;temp->left=temp->equal=temp->right=NULL;returntemp;

voidinsert(NodePtr*root,char*word)

if(!(*root))*root=newNode(*word);

if((*word)<(*root)->data)insert(&((*root)->left),word);elseif((*word)>(*root)->data)insert(&((*root)->right),word);elseif(*(word+1))insert(&((*root)->equal),word+1);else(*root)->isLastChar=1;

intsearchTST(NodePtrroot,char*word)

if(!root)return0;

if(*word<(root)->data)returnsearchTST(root->left,word);elseif(*word>(root)->data)returnsearchTST(root->right,word);elseif(*(word+1)=='\0')returnroot->isLastChar;

returnsearchTST(root->equal,word+1);

intsearchTSTWrapper(NodePtrroot,char*word)

intret=searchTST(root,word);

Page 424:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

printf("%s:",word);ret?printf("Found\n"):printf("NotFound\n");returnret;

intmain()

NodePtrroot=NULL;insert(&root,"banana");insert(&root,"apple");insert(&root,"mango");printf("\nSearchresultsforapple,banana,grapesandmango:\n");searchTSTWrapper(root,"apple");searchTSTWrapper(root,"banana");searchTSTWrapper(root,"grapes");searchTSTWrapper(root,"mango");return0;

Page 425:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinString

RegularExpressionMatchingImplementregularexpressionmatchingwiththesupportof‘?’and‘*’specialcharacter.‘?’Matchesanysinglecharacter.‘*’Matcheszeroormoreoftheprecedingelement.Example14.9:intmatchExpUtil(char*exp,char*str,inti,intj)

if(i==strlen(exp)&&j==strlen(str))return1;

if((i==strlen(exp)&&j!=strlen(str))||(i!=strlen(exp)&&j==strlen(str)))return0;

if(exp[i]=='?'||exp[i]==str[j])returnmatchExpUtil(exp,str,i+1,j+1);

if(exp[i]=='*')returnmatchExpUtil(exp,str,i+1,j)||matchExpUtil(exp,str,i,j+1)||matchExpUtil(exp,str,i+1,j+1);return0;

intmatchExp(char*exp,char*str)

returnmatchExpUtil(exp,str,0,0);

OrderMatchingGivenalongtextstringandapatternstring.Findifthecharactersofpatternstringareinthesameorderintextstring.Eg.TextString:ABCDEFGHIJKLMNOPQRSTUVWXYZPatternstring:JOSTExample14.10:intmatch(char*source,char*pattern)

intiSource=0;intiPattern=0;intsourceLen=strlen(source);intpatternLen=strlen(pattern);

Page 426:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

for(iSource=0;iSource<sourceLen;iSource++)if(source[iSource]==pattern[iPattern])iPattern++;if(iPattern==patternLen)return1;return0;

ASCIItoIntegerConversionWriteafunctionthattakeintegerasachararrayandconvertitintoanint.Example14.11:1.intmyAtoi(constchar*str)2.3.intvalue=0;4.while(*str)5.6.value=(value<<3)+(value<<1)+(*str-'0');7.str++;8.9.returnvalue;10.

UniqueCharactersWriteafunctionthatwilltakeastringasinputandreturn1ifitcontainuniquecharacterselsereturn0.Example14.12:intisUniqueChar(char*s)

intbitarr=0;intsize=strlen(s);for(inti=0;i<size;i++)charc=s[i];if('A'<=c&&'Z'>=c)c=c-'A';elseif('a'<=c&&'z'>=c)

Page 427:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

c=c-'a';elseprintf("UnknownChar!\n");return0;

if(bitarr&(1<<c))printf("Duplicatedetected!\n");return0;bitarr|=(1<<c);printf("Noduplicatedetected!\n");return1;

ToUpperCaseWriteafunctionthatwillconvertalllowercaselettersinastringtouppercase.Example14.13:ToUpper1.charToUpper(chars)2.3.if(s>=97&&s<=(97+25))4.s=s-32;5.returns;6.

ToLowerCaseWriteafunctionthatwillconvertuppercaseletterinastringtolowercaseExample14.14:ToLower1.charToLower(chars)2.3.if(s>=65&&s<=(65+25))4.s=s+32;5.returns;6.

PermutationCheckWriteafunctiontocheckiftwostringsarepermutationofeachother.

Page 428:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Example14.15:boolisPermutation(char*s1,char*s2)

intcount[256];intlength=strlen(s1);if(strlen(s2)!=length)printf("ispermutationreturnfalse\n");returnfalse;for(inti=0;i<256;i++)count[i]=0;

for(inti=0;i<length;i++)charch=s1[i];count[ch]++;ch=s2[i];count[ch]--;

for(inti=0;i<length;i++)if(count[i])printf("ispermutationreturnfalse\n");returnfalse;printf("ispermutationreturntrue\n");returntrue;

PalindromeCheckGivenastringasanarrayofcharactersfindifthestringisapalindromeornot?Example14.16:intisPalindrome(char*str)

inti=0,j=strlen(str)-1;while(i<j&&str[i]==str[j])

Page 429:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

i++;j--;if(i<j)printf("StringisnotaPalindrome");return0;elseprintf("StringisaPalindrome");return1;

TimeComplexityisO(n)andSpaceComplexityisO(1)

IntegertoASCIIConversionWriteafunctionthatconvertandintegerintoachararray.Example14.17:1.voidmyItoa(char*buffer,intvalue,)2.3.staticintindex=-1;4.intremender=value%10;5.value/=10;6.if(value)7.myItoa(buffer,value);8.buffer[++index]='0'+remender;9.buffer[index+1]='\0';10.

ASCIItofloatConversionWriteafunctionthattakefloatasachararrayandconvertitintoafloat.Example14.18:floatMyAtof(char*str)

floatnum=0.0F;floatfraction=0.1F;intdecimalStart=0;intsize=strlen(str);

Page 430:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

for(inti=0;i<size;i++)if(str[i]=='.')decimalStart=1;continue;if(!decimalStart)num=(num*10)+(str[i]-'0');elsenum+=(str[i]-'0')*fraction;fraction*=0.1F;returnnum;

ReverseCasefunctionWrite a function thatwill convertLower case letter in a string to upper case and upper case letter tolowercase.Example14.19:/*lowertoupper*/charLowerUpper(chars)

if(s>=97&&s<=(97+25))s=s-32;elseif(s>=65&&s<=(65+25))s=s+32;returns;

StringCopyfunctionWriteafunctiontocopystringprovidedasasource in thearrayprovidedasdestination, including theterminatingnullcharacter.Example14.20:1.char*myStrcpy(char*dst,char*src)2.3.char*ptr=dst;4.while(*dst++=*src++);

Page 431:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

5.returnptr;6.

PowerfunctionWriteafunctionwhichwillcalculatexn,Takingxandnasargument.Example14.21:Powerfunction1.intpow(intx,intn)2.3.intvalue;4.if(n==0)5.return(1);6.elseif(n%2==0)7.8.value=pow(x,n/2);9.return(value*value);10.11.else12.13.value=pow(x,n/2);14.return(x*value*value);15.16.

StringComparefunctionWriteafunctionstrcmp()tocomparetwostrings.Thefunctionreturnvaluesshouldbe:Thereturnvalueis0indicatesthatbothfirstandsecondstringsareequal.Thereturnvalueisnegativeindicatesthefirststringislessthanthesecondstring.Thereturnvalueispositiveindicatesthatthefirststringisgreaterthanthesecondstring.Example14.22:1.intmyStrcmp(char*a,char*b)2.3.while((*a)==(*b))4.5.if(*a=='\0')6.return0;7.a++;8.b++;9.10.if(*a=='\0')11.return-1;12.if(*b=='\0')

Page 432:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

13.return1;14.intvalue=(*a-*b);15.returnvalue;16.

SubstringfunctionWriteaCfunctionthatwillcopyfirstncharacterfromasourcestringtothedestinationstring.Example14.23:1.char*mySubstr(char*src,char*dst,intn)2.3.intcount=n;4.char*ptr=dst;5.do6.7.n--;8.if(n==0)9.10.ptr[count-1]='\0';11.break;12.13.else14.15.dst++=src++;16.17.while(src);18.returnptr;19.

StringduplicatefunctionWriteaCfunctionthatwillreturnapointertoanewstringthatisaduplicateoftheinputstring.Memoryforthenewstringisobtainedwithmallocandfreedwithfree.Example14.24:1.char*myStrdup(char*src)2.3.char*dst=(char*)malloc((strlen(src)+1)*sizeof(char));4.char*ptr=dst;5.while(*dst++=*src++);6.returnptr;7.

MemcpyFunction

Page 433:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ThefunctionMemcpyfunctioncopiesncharactersfromthesourcearraytodestinationarray.Example14.25:1.voidmymemcpy(void*destPtr,constvoid*srcPtr,intsize)2.3.char*destTemp=(char*)destPtr;4.constchar*srcTemp=(char*)srcPtr;5.while(size--)6.7.*destTemp++=*srcTemp++;8.9.

ReverseNcharactersExample14.26:ReversefirstNcharactersofastring1.voidreverse(char*s,intN)2.3.char*p,*q;4.chart;5.for(p=s,q=s+N-1;p<q;++p,--q)6.t=*q;7.*q=*p;8.*p=t;9.10.

MemmoveFunctionThe functionMemmove function copies n characters from the source array todestination array. It alsotakescaseifthesourceanddestinationmemoryarraysoverlaps.Example14.27:1.voidmymemmove(void*from,void*to,size_tsize)2.3.char*destTemp=(char*)to;4.char*srcTemp=(char*)from;5.size_ti;6.if(from==to)7.8.//Nothingtocopy!9.10.elseif(from>to)11.

Page 434:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

12.for(i=0;i<size;i++)13.destTemp[i]=srcTemp[i];14.15.else16.17.for(i=size-1;i>=0;i--)18.destTemp[i]=srcTemp[i];19.20.#ifdefBIG_ENDIAN21.reverse(destTemp,size);22.#endif23.

StringLengthfunctionWriteaCfunctiontofindthelengthofthechararray,stringpassedasargument.Example14.28:1.intmyStrlen(char*src)2.3.intlength=0;4.while(*src!='\0')5.6.length++;7.8.returnlength;16.

StringConcatenatefunctionWriteacfunctiontoconcatenatetwostrings.Assumingthatfirststringhasenoughspaceforthesecondstring.Example14.29:1.char*strcat(char*s1,char*s2)2.3.char*ptr=s1;4.while(*s1++);5.while(*s2!='\0')6.*s1++=*s2++;7.returnptr;8.

ReverseStringExample14.30:Reverseallthecharactersofastring.voidreverseString(char*a,intlower,intupper)

Page 435:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

chartempChar;while(lower<upper)tempChar=a[lower];a[lower]=a[upper];a[upper]=tempChar;lower++;upper--;

ReverseWordsExample14.31:Reverseorderofwordsinastringsentence.voidreverseWords(char*a)

intlength=strlen(a);intlower,upper=-1;lower=0;

for(inti=0;i<=length;i++)if(a[i]==''||a[i]=='\0')reverseString(a,lower,upper);lower=i+1;upper=i;elseupper++;reverseString(a,0,length-1);//-1becausewedonotwanttoreverse‘\0’

PrintAnagramExample14.32:Givenastringascharacterarray,printalltheanagramofthestring.voidprintAnagram(char*a)

intn=strlen(a);printAnagram(a,n,n);

Page 436:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

voidprintAnagram(char*a,intmax,intn)

if(max==1)printString(a,n);

for(inti=-1;i<max-1;i++)if(i!=-1)a[i]^=a[max-1]^=a[i]^=a[max-1];printAnagram(a,max-1,n);if(i!=-1)a[i]^=a[max-1]^=a[i]^=a[max-1];

ShuffleStringExample14.33:WriteaprogramtoconvertarrayABCDE12345toA1B2C3D4E5voidshuffle(charar[],intn)

intcount=0;intk=1;chartemp='\0';for(inti=1;i<n;i=i+2)temp=ar[i];k=i;dok=(2*k)%(2*n-1);temp^=ar[k]^=temp^=ar[k];count++;while(i!=k);if(count==(2*n-2))break;

BinaryAdditionExample14.34:Giventwobinarystring,findthesumofthesetwobinarystrings.char*addBinary(char*first,char*second)

Page 437:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

intsize1=strlen(first);intsize2=strlen(second);inttotalIndex;char*total;if(size1>size2)total=(char*)malloc((size1+2)*sizeof(char));totalIndex=size1;elsetotal=(char*)malloc((size2+2)*sizeof(char));totalIndex=size2;total[totalIndex+1]='\0';intcarry=0;intcurr=0;size1--;size2--;while(size1>=0||size2>=0)intfirstValue=(size1<0)?0:first[size1]-'0';intsecondValue=(size2<0)?0:second[size2]-'0';intsum=firstValue+secondValue+carry;

carry=sum>>1;sum=sum&1;

total[totalIndex]=(sum==0)?'0':'1';

totalIndex--;size1--;size2--;total[totalIndex]=(carry==0)?'0':'1';returntotal;

RemoveAllSpacesExample14.35:WriteaCfunctiontoremoveallspacesfromastring.voidremoveSpaces(char*str)

char*to=str;char*from=str;

Page 438:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

if(str==NULL)return;

while(*from!='\0')if(*from=='')from++;continue;

*to=*from;from++;to++;*to='\0';

Page 439:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise1.Givenastring,findthelongestsubstringwithoutreputedcharacters.2.Thefunctionmemset()copieschintothefirst'n'charactersofthestring3.Serializeacollectionof string intoa single stringanddeserializes thestring into thatcollectionof

strings.4.Writeasmartinputfunctionthattake20charactersasinputfromtheuser.Withoutcuttingsomeword.

Userinput:“HarryPottermustnotgo”First20chars:“HarryPottermustno”Smartinput:“HarryPottermust”

5.Writeacodethatreturnsifastringispalindromeanditshouldreturntrueforbelowinputstoo.

Stellawonnowallets.No,itisopenononeposition.Risetovote,Sir.Won'tloversrevoltnow?

6.Write anASCII to integer function that ignore the non-integral character and give the integer . For

example,iftheinputis“12AS5”itshouldreturn125.7.WritecodethatwouldparseaBashbraceexpansion.

Example:theexpression"(a,b,c)d,e"andwouldoutputallthepossiblestrings:ad,bd,cd,e8.Givenastringwriteafunctiontoreturnthelengthofthelongestsubstringwithonlyuniquecharacters9.Replacealloccurrencesof"a"with"the"10.Replacealloccurrencesof%20with''.

E.g.Input:www.Hello%20World.comOutput:www.HelloWorld.com

11.Write anexpansion function thatwill takean input string like "1..5,8,11..14,18,20,26..30"andwill

print"1,2,3,4,5,8,11,12,13,14,18,20,26,27,28,29,30"12.Supposeyouhaveastringlike"Thisisasentence".Writeafunctionthatwouldseparatethesewords.

Andwillprintwholesentencewithspaces.13.Giventhreestringstr1,str2andstr3.Writeacomplementfunctiontofindthesmallestsub-sequencein

str1whichcontainsallthecharactersinstr2andbutnotthoseinstr3.14.GiventwostringsAandB,findwhetheranyanagramofstringAisasubstringofstringB.

Page 440:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Foreg:IfA=xyzandB=afdgzyxksldfmthentheprogramshouldreturntrue.

15. Given a string, find whether it contains any permutation of another string. For example, given"abcdefgh"and"ba",thefunctionshouldreturntrue,because"abcdefgh"hassubstring"ab",whichisapermutationofthegivenstring"ba".

16.Giveanalgorithmwhichremovestheoccurrenceof“a”by“bc”fromastring?Thealgorithmmustbe

in-place.17.Givenastring,"1010101010"inbase2convertitintostringwithbase4.Donotuseanextraspace.

Page 441:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 442:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER15:ALGORITHMDESIGNTECHNIQUES

Page 443:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionInreallifewhenweareaskedtodosomework,wetrytocorrelateitwithourexperienceandthentrytosolveit.Similarly,whenwegetanewproblemtosolve.Wefirsttrytofindthesimilarityofthecurrentproblemwithsomeproblemsforwhichwealreadyknowthesolution.Thensolve thecurrentproblemandgetourdesiredresult.Thismethodprovidesfollowingbenefits:1)Itprovidesatemplateforsolvingawiderangeofproblems.2)Itprovidesustheideaofthesuitabledatastructurefortheproblem.3)Ithelpsusinanalysing,spaceandTimeComplexityofalgorithms.In the previous chapters,we have used various algorithms to solve different kind of problems. In thischapter,wewillreadaboutvarioustechniquesofsolvingalgorithmicproblems.VariousAlgorithmdesigntechniquesare:1)BruteForce2)GreedyAlgorithms3)Divide-and-Conquer,Decrease-and-Conquer4)DynamicProgramming5)Reduction/Transform-and-Conquer6)BacktrackingandBranch-and-Bound

Page 444:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BruteForceAlgorithmBruteForceisastraightforwardapproachofsolvingaproblembasedontheproblemstatement.Itisoneoftheeasiestapproachestosolveaparticularproblem.Itisusefulforsolvingsmallsizedatasetproblem.Someexamplesofbruteforcealgorithmsare:·Bubble-Sort·Selection-Sort·Sequentialsearchinanarray·Computingpow(a,n)bymultiplyinga,ntimes.·Convexhullproblem·Stringmatching·Exhaustivesearch:Travelingsalesman,Knapsack,andAssignmentproblems

Page 445:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

GreedyAlgorithmIn greedy algorithm, solution is constructed through a sequence of steps.At each step, choice ismadewhich is locally optimal. Greedy algorithms are generally used to solve optimization problems. Wealwaystakethenextdatatobeprocesseddependinguponthedatasetwhichwehavealreadyprocessedandthenchoosethenextoptimumdatatobeprocessed.Greedyalgorithmsdoesnotalwaysgiveoptimumsolution.Someexamplesofbruteforcealgorithmsare:·Minimalspanningtree:Prim’salgorithm,Kruskal’salgorithm·Dijkstra’salgorithmforsingle-sourceshortestpathproblem·GreedyalgorithmfortheKnapsackproblem·Thecoinexchangeproblem·Huffmantreesforoptimalencoding

Page 446:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Divide-and-Conquer,Decrease-and-ConquerDivide-and-Conqueralgorithmsinvolvebasicthreesteps,firstsplittheproblemintoseveralsmallersub-problems,secondsolveeachsubproblemandthenfinallycombinethesubproblemsresultstoproducetheresult.In divide-and-conquer the size of the problem is reduced by a factor (half, one-third, etc.),While indecrease-and-conquerthesizeoftheproblemisreducedbyaconstant.Examplesofdivide-and-conqueralgorithms:·Merge-Sortalgorithm(usingrecursion)·Quicksortalgorithm(usingrecursion)·Computingthelengthofthelongestpathinabinarytree(usingrecursion)·ComputingFibonaccinumbers(usingrecursion)·Quick-hullExamplesofdecrease-and-conqueralgorithms:·Computingpow(a,n)bycalculatingpow(a,n/2)usingrecursion.·Binarysearchinasortedarray(usingrecursion)·SearchinginBST·Insertion-Sort·Graphtraversalalgorithms(DFSandBFS)·Topologicalsort·Warshall’salgorithm(usingrecursion)·Permutations(Minimalchangeapproach,Johnson-Trotteralgorithm)·Computingamedian,Topologicalsorting,Fake-coinproblem(Ternarysearch)

Considertheproblemofexponentiation:ComputexnBruteForce: n-1multiplicationsDivideandconquer: T(n)=2*T(n/2)+1=n-1Decreasebyone: T(n)=T(n-1)+1=n-1

Decreasebyconstantfactor:T(n)=T(n/a)+a-1=(a-1)n=nwhena=2

Page 447:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DynamicProgrammingWhilesolvingproblemsusingDivide-and-Conquermethod, theremaybeacasewhenrecursivelysub-problemscanresultinthesamecomputationbeingperformedmultipletimes.Thisproblemariseswhenthereareidenticalsub-problemsariserepeatedlyinarecursion.Dynamicprogrammingisusedtoavoidtherequirementofrepeatedcalculationofsamesub-problem.Inthismethod,weusuallystoretheresultofsub-problemsinatableandreferthattabletofindifwehavealreadycalculatedthesolutionofsub-problemsbeforecalculatingitagain.Dynamicprogrammingisabottomuptechniqueinwhichthesmallersub-problemsaresolvedfirstandtheresultofthesearesuedtofindthesolutionofthelargersub-problems.Examples:·Fibonaccinumberscomputedbyiteration.·Warshall’salgorithmfortransitiveclosureimplementedbyiterations·Floyd’salgorithmsforall-pairsshortestpaths

intfibonacci(intn)

if(n<=1)returnn;returnfibonacci(n-1)+fibonacci(n-2);

Usingdivideandconquerthesamesubproblemissolvedagainandagain,whichreducetheperformanceofthealgorithm.ThisalgorithmhasanexponentialTimeComplexityandlinearSpaceComplexity.intfibo(intn)

intfirst=0,second=1;inttemp,i;

if(n==0)

Page 448:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

returnfirst;elseif(n==1)returnsecond;

for(i=2;i<=n;i++)temp=first+second;first=second;second=temp;returntemp;

Usingthisalgorithm,wewillgetFibonacciinlinearTimeComplexityandconstantSpaceComplexity.

Page 449:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Reduction/Transform-and-ConquerThesemethodsworksastwo-stageprocedure.First,theproblemistransformedintoaknownproblemforwhichweknowoptimalsolution.Inthesecondstage,theproblemissolved.Themostcommontypesoftransformationaresortofanarray.Forexample:Givenanarrayofnumbersfindsthetwoclosestnumber.Thebruteforcesolutionforthisproblemwilltakedistancebetweeneachelementinthearrayandwilltrytokeeptheminimumdistancepair,thisapproachwillhaveaTimeComplexityofO(n2)

Transformandconquer solution,willbe first sort thearray inO(nlogn) time and then find the closestnumberbyscanningthearrayinanotherO(n).WhichwillgivethetotalTimeComplexityofO(nlogn).Examples:·Gaussianelimination·HeapsandHeapsort

Page 450:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BacktrackingInreallife,letussupposesomeonegaveyoualockwithanumber(threedigitlock,numberrangefrom1to9).Youdonothavetheexactpasswordkeyforthelock.Youneedtotesteverycombinationuntilyougot therightone.Obviously,youneedtoteststartingfromsomethinglike“111”, then“112”andsoon.Moreover,youwillgetyourkeybeforeyoureach“999”.Therefore,whatyouaredoingisbacktracking.Supposethelockproducesomesound“click”correctdigitisselectedforanylevel.Ifwecanlistentothissoundsuchintelligence/heuristicswillhelpyoutoreachyourgoalmuchfaster.ThesefunctionsarecalledPruningfunctionorboundingfunctions.Backtracking is amethodbywhich solution is foundbyexhaustively searching through largebut finitenumberofstates,withsomepruningorboundingfunctionthatwillnarrowdownoursearch.Foralltheproblemslike(NPhardproblems)forwhichtheredoesnotexistanyothermethodweusebacktracking.Backtrackingproblemshavethefollowingcomponents:1.Initialstate2.Target/Goalstate3.Intermediatestates4.Pathfromtheinitialstatetothetarget/goalstate5.Operatorstogetfromonestatetoanother6.Pruningfunction(optional)The solvingprocessofbacktrackingalgorithmstartswith theconstructionof state’s tree,whosenodesrepresentsthestates.Therootnodeistheinitialstateandoneormoreleafnodewillbeourtargetstate.Eachedgeof the tree represents someoperation.Thesolution isobtainedby searching the treeuntil aTargetstateisfound.Backtrackingusesdepth-firstsearch:1)Storetheinitialstateinastack2)Whilethestackisnotempty,repeat:3)Readanodefromthestack.4)Whilethereareavailableoperators,do:

a.Applyanoperatortogenerateachildb.Ifthechildisagoalstate–returnsolutionc.Ifitisanewstate,andpruningfunctiondoesnotdiscarditpushthechildintothestack.

Therearethreemonksandthreedemonsatonesideofariver.Wewanttomoveallofthemtotheothersideusingasmallboat.Theboatcancarryonlytwopersonsatatime.Givenifonanyshorethenumberofdemonswillbemorethanmonksthentheywilleatthemonks.Howcanwemoveallofthesepeopletotheothersideoftheriversafely?Sameastheaboveproblemthereisafarmerwhohasagoat,acabbageandawolf.Ifthefarmerleaves,goatwithcabbage,goatwilleatthecabbage.Ifthefarmerleaveswolfalonewithgoat,wolfwillkillthegoat.Howcanthefarmermoveallhisbelongingstotheothersideoftheriver?

Page 451:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Youaregiventwojugs,a4-gallononeanda3-gallonone.Therearenomeasuringmarkersonjugs.Atapcanbeusedtofillthejugswithwater.Howcanyouget2gallonsofwaterinthe4-gallonjug?

Page 452:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Branch-and-boundBranchandboundmethodisusedwhenwecanevaluatecostofvisitingeachnodebyautilityfunctions.Ateachstep,wechoosethenodewithlowestcosttoproceedfurther.Branch-andboundalgorithmsareimplementedusingapriorityqueue.Inbranchandbound,wetraversethenodesinbreadth-firstmanner.

Page 453:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

A*AlgorithmA*issortofanelaborationonbranch-and-bound.Inbranch-and-bound,ateachiterationweexpandtheshortestpaththatwehavefoundsofar.InA*,insteadofjustpickingthepathwiththeshortestlengthsofar,wepickthepathwiththeshortestestimatedtotallengthfromstart togoal,wherethetotallengthisestimatedaslengthtraversedsofarplusaheuristicestimateoftheremainingdistancefromthegoal.

Branch-and-boundwillalwaysfindanoptimalsolution,whichisshortestpath.A*willalwaysfindanoptimal solution if theheuristic is correct.Choosingagoodheuristic is themost important part ofA*algorithm.

Page 454:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ConclusionUsuallyagivenproblemcanbesolvedusinganumberofmethods,howeveritisnotwisetosettleforthefirstmethodthatcomestoourmind.Somemethodsresultinmuchmoreefficientsolutionsthanothers.For example the Fibonacci numbers calculated recursively ( decrease-and-conquer approach), andcomputedbyiterations(dynamicprogramming).InthefirstcasethecomplexityisO(2n),andintheothercasethecomplexityisO(n).Anotherexample,considersortingbasedontheInsertion-Sortandbasicbubblesort.Foralmostsortedfiles, Insertion-Sort will give almost linear complexity, while bubble sort sorting algorithms havequadraticcomplexity.Sothemostimportantquestionis,howtochoosethebestmethod?First,youshouldunderstandtheproblemstatement.Secondbyknowingvariousproblemsandtheirsolutions.

Page 455:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 456:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER16:BRUTEFORCEALGORITHM

Page 457:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionBruteForceisastraightforwardapproachofsolvingaproblembasedontheproblemstatement.Itisoneoftheeasiestapproachestosolveaparticularproblem.Itisusefulforsolvingsmallsizedatasetproblem.Manytimes,otheralgorithmtechniquescanbeusedtogetabettersolutionofthesameproblem.Someexamplesofbruteforcealgorithmsare:·Bubble-Sort·Selection-Sort·Sequentialsearchinanarray·Computingpow(a,n)bymultiplyinga,ntimes.·Convexhullproblem·Stringmatching·Exhaustivesearch·Travelingsalesman·Knapsack·Assignmentproblems

Page 458:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsinBruteForceAlgorithm

Bubble-SortInBubble-Sort,adjacentelementsofthelistarecomparedandareexchangediftheyareoutoforder.//SortsagivenarraybyBubbleSort//Input:AnarrayAoforderableelements//Output:ArrayA[0..n-1]sortedinascendingorderAlgorithmBubbleSort(A[0..n-1])

sorted=falsewhile!sorteddosorted=trueforj=0ton-2doifA[j]>A[j+1]thenswapA[j]andA[j+1]sorted=false

TheTimeComplexityofthealgorithmisΘ(n2)

Selection-SortTheentiregivenlistofNelementsistraversedtofinditssmallestelementandexchangeitwiththefirstelement.Then, the list is traversed again to find the second element and exchanged itwith the secondelement.AfterN-1passes,thelistwillbefullysorted.//Sortsagivenarraybyselectionsort//Input:AnarrayA[0..n-1]oforderableelements//Output:ArrayA[0..n-1]sortedinascendingorderAlgorithmSelectionSort(A[0..n-1])

fori=0ton-2domin=iforj=i+1ton-1doifA[j]<A[min]min=jswapA[i]andA[min]

TheTimeComplexityofthealgorithmisΘ(n2)

SequentialSearchThealgorithmcomparesconsecutiveelementsofagivenlistwithagivensearchkeyworduntileitheramatchisfoundorthelistisexhausted.AlgorithmSequentialSearch(A[0..n],K)

i=0

Page 459:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

WhileA[i]≠Kdoi=i+1ifi<nreturnielsereturn-1

WorstcaseTimeComplexityisΘ(n).

ComputingPOW(a,n)Computingan(a>0,andnisanonnegativeinteger)basedonthedefinitionofexponentiation.N-1multiplicationsarerequiredinbruteforcemethod.//Input:Arealnumberaandanintegern=0//Output:apowernAlgorithmPower(a,n)

result=1fori=1tondoresult=result*areturnresult

ThealgorithmrequiresΘ(n)

StringmatchingAbruteforcestringmatchingalgorithmtakestwoinputs,firsttextconsistsofncharactersandapatternconsistofmcharacter (m<=n).Thealgorithmstartsbycomparing thepatternwith thebeginningof thetext.Each character of the patters is compared to the corresponding character of the text.Comparisonstartsfromlefttorightuntilallthecharactersarematchedoramismatchisfound.Thesameprocessisrepeateduntilamatchisfound.Eachtimethecomparisonstartsonepositiontotheright.//Input:AnarrayT[0..n-1]ofncharactersrepresentingatext//anarrayP[0..m-1]ofmcharactersrepresentingapattern//Output:Thepositionofthefirstcharacterinthetextthatstartsthefirst//matchingsubstringifthesearchissuccessfuland-1otherwise.AlgorithmBruteForceStringMatch(T[0..n-1],P[0..m-1])

fori=0ton-mdoj=0whilej<mandP[j]=T[i+j]doj=j+1ifj=mthenreturnireturn-1

Page 460:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Intheworstcase,thealgorithmisO(mn).

Closest-PairBrute-ForceAlgorithmTheclosest-pairproblemistofindthetwoclosestpointsinasetofnpointsina2-dimensionalspace.Abruteforceimplementationofthisproblemcomputesthedistancebetweeneachpairofdistinctpointsandfindthesmallestdistancepair.//Findstwoclosestpointsbybruteforce//Input:AlistPofn>=2points//Output:TheclosestpairAlgorithmBruteForceClosestPair(P)

dmin=infinitefori=1ton-1doforj=i+1tondod= +ifd<dminthendmin=dimin=ijmin=jreturnimin,jmin

IntheTimeComplexityofthealgorithmisΘ(n2)

Convex-HullProblemConvex-hullofasetofpointsisthesmallestconvexpolygoncontainingallthepoints.Allthepointsofthesetwilllieontheconvexhullorinsidetheconvexhull.Illustratetherubber-bandinterpretationoftheconvexhull.Theconvex-hullofasetofpointsisasubsetofpointsinthegivensets.Howtofindthissubset?Answer:Therestofthepointsofthesetareallononeside.

Page 461:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Twopoints(x1,y1),(x2,y2)makethelineax+by=cWherea=y2-y1,b=x1-x2,andc=x1y2-y1x2Anddividestheplanebyax+by-c<0andax+by-c>0Soweneedtoonlycheckax+by-cfortherestofthepointsIfwefindallthepointsinthesetliesonesideofthelinewitheitherallhaveax+by-c<0orallthepointshaveax+by-c>0thenwewilladdthesepointstothedesiredconvexhullpointset.Foreachofn(n-1)/2pairsofdistinctpoints,oneneedstofindthesignofax+by-cineachoftheothern-2points.Whatistheworst-casecostofthealgorithm?O(n3)fori=0ton-1

forj=0ton-1if(xi,yi)!=(xj,yj)drawalinefrom(xi,yi)to(xj,yj)fork=0ton-1if(i!=kandj!=k)if(allotherpointslieonthesamesideoftheline(xi,yi)and(xj,yj))add(xi,yi)to(xj,yj)totheconvexhullset

ExhaustiveSearchExhaustivesearchisabruteforceapproachappliestocombinatorialproblems.In exhaustive search, we generate all the possible combinations. See if the combinations satisfy theproblemconstraintsandthenfindingthedesiredsolution.Examplesofexhaustivesearchare:·Travelingsalesmanproblem·Knapsackproblem·Assignmentproblem

TravelingSalesmanProblem(TSP)In the travelingsalesmanproblemweneed to find theshortest tour throughagivensetofNcities thatsalesmanvisitseachcityexactlyoncebeforereturningtothecitywherehestarted.Alternatively:FindingtheshortestHamiltoniancircuitinaweightedconnectedgraph.Acyclethatpassesthroughalltheverticesofthegraphexactlyonce.

Page 462:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TourswhereAisstartingcity:TourCostA→B→C→D→A1+3+6+5=15A→B→D→C→A1+4+6+8=19A→C→B→D→A8+3+4+5=20A→C→D→B→A8+6+4+1=19A→D→B→C→A5+4+3+8=20A→D→C→B→A5+6+3+1=15AlgorithmTSP

SelectacityMinTourCost=infiniteFor(Allpermutationsofcities)doIf(LengthOfPathSinglePermutation<MinTourCost)MinTourCost=LengthOfPath

Totalnumberofpossiblecombinations=(n-1)!Costforcalculatingthepath=Θ(n)Sothetotalcostforfindingtheshortestpath=Θ(n!)

KnapsackProblemGivenanitemwithcostC1,C2,...,Cn,andvolumeV1,V2,...,VnandknapsackofcapacityVmax,findthemostvaluable(max∑Cj)thatfitintheknapsack(∑Vj≤Vmax).The solution is one of all the subset of the set of object taking 1 to n objects at a time, so the TimeComplexitywillbeO(2n)AlgorithmKnapsackBruteForce

MaxProfit=0For(Allpermutationsofobjects)doCurrProfit=sumofobjectsselectedIf(MaxProfit<CurrProfit)

Page 463:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

MaxProfit=CurrProfitStorethecurrentsetofobjectsselected

Page 464:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ConclusionBruteforceisthefirstalgorithmthatcomesintomindwhenweseesomeproblem.Theyarethesimplestalgorithms that are very easy to understand. However, these algorithms rarely provide an optimumsolution.Many caseswewill find other effective algorithm that ismore efficient than the brute forcemethod.Thisisthemostsimpletounderstandthekindofproblemsolvingtechnique.

Page 465:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 466:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER17:GREEDYALGORITHM

Page 467:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionGreedyalgorithmsaregenerallyusedtosolveoptimizationproblems.Tofindthesolutionthatminimizesormaximizessomevalue(cost/profit/countetc.).In greedy algorithm, solution is constructed through a sequence of steps.At each step, choice ismadewhichislocallyoptimal.Wealwaystakethenextdatatobeprocesseddependinguponthedatasetwhichwehavealreadyprocessedandthenchoosethenextoptimumdatatobeprocessed.Greedyalgorithmsdoesnotalwaysgiveoptimumsolution.Forsomeproblems,greedyalgorithmgivesanoptimalsolution.Formost,theydonot,butcanbeusefulforfastapproximations.Greedyisastrategythatworkswellonoptimizationproblemswiththefollowingcharacteristics:1.Greedychoice:Aglobaloptimumcanbearrivedatbyselectingalocaloptimum.2. Optimal substructure: An optimal solution to the problem is made from optimal solutions of subproblems.Someexamplesofbruteforcealgorithmsare:Optimalsolutions:·Minimalspanningtree:

oPrim’salgorithm,oKruskal’salgorithm

·Dijkstra’salgorithmforsingle-sourceshortestpath·Huffmantreesforoptimalencoding·SchedulingproblemsApproximatesolutions:·GreedyalgorithmfortheKnapsackproblem·Coinexchangeproblem

Page 468:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsonGreedyAlgorithm

CoinexchangeproblemHowcanagivenamountofmoneyNbemadewiththeleastnumberofcoinsofgivenDoneminationsD=d1…dn?TheIndiancoinsystem5,10,20,25,50,100Supposewewanttogivechangeofacertainamountof40paisa.Wecanmakeasolutionbyrepeatedlychoosingacoin≤tothecurrentamount,resultinginanewamount.Thegreedysolutionalwayschoosethelargestvaluecoinwithoutexceedingthetotalamount.For40paisa:25,10,and5Theoptimalsolutionwillbe20,20Thegreedyalgorithmdidnotgiveusoptimalsolution,butitgaveafairapproximation.AlgorithmMAKE-CHANGE(N)

C=5,20,25,50,100//constant.S=//setthatwillholdthesolutionset.Value=NWHILEValue!=0x=largestiteminsetCsuchthatx<ValueIFnosuchitemTHENRETURN"NoSolution"S=S+xValue=Value-xRETURNS

MinimumSpanningTreeAspanningtreeofaconnectedgraphisatreecontainingallthevertices.A minimum spanning tree of a weighted graph is a spanning tree with the smallest sum of the edgeweights.

Page 469:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Prim’sAlgorithmPrim’salgorithmgrowsasingletreeT,oneedgeatatime,untilitbecomesaspanningtree.WeinitializeTwithzeroedges.Uwithsinglenode.WhereTisspanningtreeedgessetandUisspanningtreevertexset.Ateachstep,Prim’salgorithmaddsthesmallestvalueedgewithoneendpointinUandothernotinus.SinceeachedgeaddsonenewvertextoU,aftern−1additions,UcontainalltheverticesofthespanningtreeandTbecomesaspanningtree.//ReturnstheMSTbyPrim’sAlgorithm//Input:AweightedconnectedgraphG=(V,E)//Output:SetofedgescomprisingaMSTAlgorithmPrim(G)

T=LetrbeanyvertexinGU=rfori=1to|V|-1doe=minimum-weightedge(u,v)WithuinUandvinV-UU=U+vT=T+ereturnT

Prim’sAlgorithmusingapriorityqueue(minheap)togettheclosestfringevertexTimeComplexitywillbeO(mlogn)wherenverticesandmedgesoftheMST.

Kruskal’sAlgorithmKruskal’s Algorithm is used to create minimum spanning tree. Spanning tree is created by choosingsmallestweightedgethatdoesnotformacycle.Repeatthisprocessuntilalltheedgesfromtheoriginalsetisexhausted.Sorttheedgesinnon-decreasingorderofcost:c(e1)≤c(e2)≤···≤c(em).SetTtobetheemptytree.Addedgestotreeonebyoneifitdoesnotcreateacycle.(Ifthenewedgeformcyclethenignorethatedge.)//ReturnstheMSTbyKruskal’sAlgorithm//Input:AweightedconnectedgraphG=(V,E)//Output:SetofedgescomprisingaMSTAlgorithmKruskal(G)

SorttheedgesEbytheirweightsT=

Page 470:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

while|T|+1<|V|doe=nextedgeinEifT+edoesnothaveacyclethenT=T+ereturnT

Kruskal’sAlgorithmisO(ElogV)usingefficientcycledetection.

Dijkstra’salgorithmforsingle-sourceshortestpathproblemDijkstra’salgorithmforsingle-sourceshortestpathproblemforweightededgeswithnonegativeweight.Itdeterminethelengthoftheshortestpathfromthesourcetoeachoftheothernodesofthegraph.GivenaweightedgraphG,weneedtofindshortestpathsfromthesourcevertexs toeachof theothervertices.

Thealgorithmstartsbykeepingtrackofthedistanceofeachnodeanditsparents.Allthedistanceissettoinfiniteinthebeginningaswedonotknowtheactualpathtothenodesandparentsofalltheverticesaresettonull.Alltheverticesareaddedtoapriorityqueue(minheapimplementation)Ateachstepalgorithmtakesonevertexfromthepriorityqueue(whichwillbethesourcevertexinthebeginning).Thenupdatethedistancearraycorrespondingtoalltheadjacentvertices.Whenthequeueisempty,thenwewillhavethedistanceandparentarrayfullypopulated.//SolvesSSSPbyDijkstra’sAlgorithm//Input:AweightedconnectedgraphG=(V,E)//withnonegativeweights,andsourcevertexv//Output:ThelengthandpathfromstoeveryvAlgorithmDijkstra(G,s)

foreachvinVdoD[v]=infinite//UnknowndistanceP[v]=null//unknownpreviousnodeaddvtoPQ//addingallnodestopriorityqueue

Page 471:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

D[source]=0//Distancefromsourcetosource

while(Qisnotempty)u=vertexfromPQwithsmallestD[u]removeufromPQforeachvadjacentfromudoalt=D[u]+length(u,v)ifalt<D[v]thenD[v]=altP[v]=uReturnD[],P[]

TimeComplexitywillbeO(|E|log|V|).Note:Dijkstra’salgorithmdoesnotworkforgraphswithnegativeedgesweight.Note:Dijkstra’salgorithmisapplicabletobothundirectedanddirectedgraphs.

HuffmantreesforoptimalencodingCodingisanassignmentofbitstringsofalphabetcharacters.Therearetwotypesofencoding:·Fixed-lengthencoding(eg.,ASCII)·Variable-lengthencoding(eg.,Huffmancode)Variable length encoding canonlyworkonprefix free encoding.Whichmeans that no codeword is aprefixofanothercodeword.Huffmancodesarethebestprefixfreecode.Anybinarytreewithedgeslabelledas0and1willproduceaprefixfreecodeofcharactersassignedtoitsleafnodes.Huffman’s algorithm is used to construct a binary treewhose leaf value is assigned a code,which isoptimal for the compressionof thewhole text need to be processed.For example, themost frequentlyoccurringwordswillgetthesmallestcodesothatthefinalencodedtextiscompressed.Initializenone-nodetreeswithwordsandthetreeweightswiththeirfrequencies.Jointhetwobinarytreewithsmallestweightintooneandtheweightofthenewformedtreeasthesumofweightofthetwosmalltrees.RepeattheaboveprocessN-1timesandwhenthereisjustonebigtreeleftyouaredone.Markedgesleadingtoleftandrightsubtreeswith0’sand1’s,respectively.Word FrequencyApple 30Banana 25Mango 21Orange 14

Page 472:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Pineapple 10

Word Value CodeApple 30 11Banana 25 10Mango 21 01Orange 14 001Pineapple 10 000ItisclearthatmorefrequencywordsgetssmallerHuffman’scode.//Computesoptimalprefixcode.//Input:ArrayWofcharacterprobabilities//Output:TheHuffmantree.AlgorithmHuffman(C[0..n-1],W[0..n-1])

PQ=//priorityqueuefori=0ton-1doT.char=C[i]T.weight=W[i]addTtopriorityqueuePQ

fori=0ton-2doL=removeminfromPQR=removeminfromPQT=nodewithchildrenLandRT.weight=L.weight+R.weightaddTtopriorityqueuePQreturnT

TheTimeComplexityisO(nlogn).

Page 473:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ActivitySelectionProblemSuppose that activities require exclusiveuseof common resources, andyouwant to schedule asmanyactivitiesaspossible.LetS=a1,...,anbeasetofnactivities.Eachactivityaineedstheresourceduringatimestartingatsiandfinishingbeforefi,i.e.,during[si,fi).Theoptimizationproblemistoselectthenon-overlappinglargestsetofactivitiesfromS.WeassumethatactivitiesS=a1,...,anaresortedinfinishtimef1≤f2≤...fn-1≤fn(thiscanbedoneinΘ(nlogn)).ExampleConsidertheseactivities:

I 1 2 3 4 5 6 7 8 9 10 11

S[i] 1 3 0 5 3 5 6 8 8 2 11

F[i] 4 5 6 7 8 9 10 11 12 13 14

Hereisagraphicrepresentation:

Wechoseanactivitythatstartfirst,andthenlookforthenextactivitythatstartsafteritisfinished.Thiscouldresultina4,a7,a8,butthissolutionisnotoptimal.Anoptimal solution is a1, a3, a6, a8. (Itmaximizes theobjective functionof a numberof activities

Page 474:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

scheduled.)Anotheroneisa2,a5,a7,a9.(Optimalsolutionsarenotnecessarilyunique.)Howdowefind(oneof)theseoptimalsolutions?Letusconsideritasadynamicprogrammingproblem...Wearetryingtooptimizethenumberofactivities.Letusbegreedy!

·Themoretimeleftafterrunninganactivity,themoreactivitieswecanfitin.·Ifwechoosethefirstactivitytofinish,themoretimewillbeleft.·Sinceactivitiesaresortedbyfinishtime,wewillalwaysstartwitha1.·Thenwecansolvethesinglesubproblemofactivityschedulinginthisremainingtime.

AlgorithmActivitySelection(S[],F[],N)

SortS[]andF[]inincreasingorderoffinishingtimeA=a1K=1Form=2toNdoIfS[m]>=F[k]A=A+amK=mReturnA

KnapsackProblemAthiefentersastoreandseesanumberofitemswiththeircostandweightmentioned.HisKnapsackcanholdamaxweight.Whatshouldhestealtomaximizeprofit?

FractionalKnapsackproblemAthiefcantakeafractionofanitem(theyaredivisiblesubstances,likegoldpowder).

The fractional knapsack problem has a greedy solution one should first sort the items in term of costdensityagainstweight.Thenfillupasmuchof themostvaluablesubstancebyweightasonecanhold,thenasmuchofthenextmostvaluablesubstance,etc.UntilWisreached.

Page 475:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Item A B CCost 300 190 180Weight 3 2 2Cost/weight 100 95 90Foraknapsackofcapacityof4kg.Theoptimumsolutionoftheabovewilltake3kgofAand1kgofB.AlgorithmFractionalKnapsack(W[],C[],Wk)

Fori=1tondoX[i]=0Weight=0//UseMaxheapH=BuildMaxHeap(C/W)WhileWeight<Wkdoi=H.GetMax()If(Weight+W[i]<=Wk)doX[i]=1Weight=Weight+W[i]ElseX[i]=(Wk–Weight)/W[i]Weight=WkReturnX

0/1KnapsackProblemAthiefcanonlytakeorleavetheitem.Hecannottakeafraction.Agreedy strategy same as above could result in empty space, reducing the overall cost density of theknapsack.Intheaboveexample,afterchoosingobjectAthereisnoplaceforBorCsothereleavesemptyspaceof1kg.Moreover,theresultofthegreedysolutionisnotoptimal.The optimal solutionwill bewhenwe take objectB andC.This problem can be solved by dynamicprogrammingthatwewillseeinthecomingchapter.

Page 476:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 477:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER18:DIVIDE-AND-CONQUER,DECREASE-AND-CONQUER

Page 478:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionDivide-and-Conqueralgorithmsworksby recursivelybreakingdownaproblem into twoormore sub-problems (divide), until these sub problems become simple enough so that can be solved directly(conquer).Thesolutionofthesesubproblemsisthencombinedtogiveasolutionoftheoriginalproblem.Divide-and-Conqueralgorithmsinvolvebasicthreesteps1.Dividetheproblemintosmallerproblems.2.Conquerbysolvingtheseproblems.3.Combinetheseresultstogether.In divide-and-conquer the size of the problem is reduced by a factor (half, one-third etc.),While indecrease-and-conquerthesizeoftheproblemisreducedbyaconstant.

Examplesofdivide-and-conqueralgorithms:·Merge-Sortalgorithm(recursion)·Quicksortalgorithm(recursion)·Computingthelengthofthelongestpathinabinarytree(recursion)·ComputingFibonaccinumbers(recursion)·ConvexHullExamplesofdecrease-and-conqueralgorithms:·ComputingPOW(a,n)bycalculatingPOW(a,n/2)usingrecursion·Binarysearchinasortedarray(recursion)·SearchinginBST·Insertion-Sort·Graphtraversalalgorithms(DFSandBFS)·Topologicalsort·Warshall’salgorithm(recursion)·Permutations(Minimalchangeapproach,Johnson-Trotteralgorithm)

Page 479:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

·Fake-coinproblem(Ternarysearch)·Computingamedian

Page 480:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

GeneralDivide-and-ConquerRecurrenceT(n)=aT(n/b)+f(n)·Wherea≥1andb>1.·"n"isthesizeofaproblem.·"a"isanumberofsub-problemintherecursion.·“n/b”isthesizeofeachsub-problem.·"f(n)"isthecostofthedivisionoftheproblemintosubproblemormergeoftheresultsofsub-problem

togettheresult.

Page 481:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

MasterTheoremThemastertheoremsolvesrecurrencerelationsoftheform:T(n)=aT(n/b)+f(n)Itispossibletodetermineanasymptotictightboundinthesethreecases:Case1:when )andconstantϵ>1,thenthefinalTimeComplexitywillbe:

Case2:when )andconstantk≥0,thenthefinalTimeComplexitywillbe:

)Case3:when andconstantϵ>1,ThenthefinalTimeComplexitywillbe:T(n)=Ɵ(f(n))

ModifiedMastertheorem:Thisisashortcuttosolvingthesameproblemeasilyandfast.IftherecurrencerelationisintheformofT(n)=aT(n/b)+dxs

Example1:TakeanexampleofMerge-Sort,T(n)=2T(n/2)+nSol:-Logba=log22=1

Page 482:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

)Case2appliesand )T(n)=Ɵ(nlog(n))Example2:BinarySearchT(n)=T(n/2)+O(1)Logba=log21=0

)Case2appliesand )T(n)=Ɵ(log(n))Example3:BinarytreetraversalT(n)=2T(n/2)+O(1 )Logba=log22=1

)Case1appliesandT(n)=Ɵ(n)

Page 483:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsonDivide-and-ConquerAlgorithm

Merge-Sortalgorithm

//Sortsagivenarraybymergesort//Input:AnarrayAoforderableelements//Output:ArrayA[0..n−1]inascendingorder

AlgorithmMergesort(A[0..n−1])ifn≤1thenreturn;copyA[0..⌊n/2⌋−1]toB[0..⌊n/2⌋−1]copyA[⌊n/2⌋..n−1]toC[0..⌈n/2⌉−1]Mergesort(B)Mergesort(C)Merge(B,C,A)

//Mergestwosortedarraysintoonearray//Input:SortedarraysBandC//Output:SortedarrayAAlgorithmMerge(B[0..p−1],C[0..q−1],A[0..p+q−1])

i=0j=0fork=0top+q−1doifi<pand(j=qorB[i]≤C[j])thenA[k]=B[i]i=i+1elseA[k]=C[j]j=j+1

Page 484:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TimeComplexity:O(nlogn),SpaceComplexity:O(n)TheTimeComplexityofMerge-SortisO(nlogn)inall3cases(worst,averageandbest)asMerge-Sortalwaysdividesthearrayintotwohalvesandtakelineartimetomergetwohalves.Itrequirestheequalamountofadditionalspaceastheunsortedlist.Hence,itisnotatallrecommendedforsearchinglargeunsortedlists.

Quick-Sort

//Sortsasubarraybyquicksort//Input:AnsubarrayofA//Output:ArrayA[l..r]inascendingorderAlgorithmQuicksort(A[l..r])

ifl<rthenp←Partition(A[l..r])//pisindexofpivotQuicksort(A[l..p−1])Quicksort(A[p+1..r])

//PartitionsasubarrayusingA[..]aspivot

Page 485:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

//Input:SubarrayofA//Output:FinalpositionofpivotAlgorithmPartition(A[],left,right)

pivot=A[left]lower=leftupper=rightwhilelower<upperwhileA[lower]<=pivotlower=lower+1whileA[upper]>pivotupper=upper–1iflower<upperthenswapA[lower]andA[upper]swapA[lower]andA[upper]//upperisthepivotpositionreturnupper

WorstCaseTimeComplexity:O(n2)BestCaseTimeComplexity:O(nlogn)AverageTimeComplexity:O(nlogn)SpaceComplexity:O(nlogn)ThespacerequiredbyQuick-Sortisveryless,onlyO(nlogn)additionalspaceisrequired.Quicksortisnotastablesortingtechnique,soitmightchangetheoccurrenceoftwosimilarelementsinthelistwhilesorting.

ExternalSortingExternalsortingisalsodoneusingdivideandconqueralgorithm.

Page 486:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

BinarySearchWegetthemiddlepointfromthesortedarrayandstartcomparingwiththedesiredvalue.Note:Binarysearchrequiresthearraytobesortedotherwisebinarysearchcannotbeapplied.//Searchesavalueinasortedarrayusingbinarysearch//Input:AnsortedarrayAandakeyK//Output:TheindexofKor−1AlgorithmBinarySearch(A[0..N−1],N,K)

low=0high=N-1whilelow<=highdomid=⌊(low+high)/2⌋ifK=A[mid]thenreturnmidelseifA[mid]<Klow=mid+1elsehigh=mid-1return−1

//Searchesavalueinasortedarrayusingbinarysearch//Input:AnsortedarrayAandakeyK//Output:TheindexofKor−1AlgorithmBinarySearch(A[],low,high,K)

Iflow>highreturn-1mid=⌊(low+high)/2⌋ifK=A[mid]thenreturnmidelseifA[mid]<KreturnBinarySearch(A[],mid+1,high,K)elsereturnBinarySearch(A[],low,mid-1,K)

TimeComplexity:O(logn).Ifyounoticetheaboveprograms,youseethatwealwaystakehalfinputandthrowingouttheotherhalf.SotherecurrencerelationforbinarysearchisT(n)=T(n/2)+c.Usingadivideandconquermastertheorem,wegetT(n)=O(logn).SpaceComplexity:O(1)

Powerfunction//ComputeNthpowerofXusingdivodeandconquerusingrecursion//Input:ValueXandpowerN//Output:Power(X,N)

Page 487:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

AlgorithmPower(X,N)IfN=0Return1ElseifN%2==0Value=Power(X,N/2)ReturnValue*ValueElseValue=Power(X,N/2)ReturnValue*Value*X

ConvexHullSortpointsbyX-coordinates.DividepointsintoequalhalvesAandB.RecursivelycomputeHAandHB.MergeHAandHBtoobtainCH

LowerTangent(HA,HB)A=rightmostpointofHAB=leftmostpointofHBWhileabisnotalowertangentforHAandHBdo

WhileabisnotalowertangenttoHAdoa=a−1(moveaclockwise)WhileabisnotalowertangenttoHBdob=b+1(movebcounterclockwise)

ReturnabSimilarlyfinduppertangentandcombinethetwohulls.

Page 488:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

InitialsortingtakesO(nlogn)timeRecurrencerelationT(N)=2T(N/2)+O(N)Where,O(N)timefortangentcomputationinsidemergingFinalTimeComplexitywillbeT(N)=O(nlogn).

ClosestPairGivenNpointsin2-dimensionalplane,findtwopointswhosemutualdistanceissmallest.

Abruteforcealgorithmtakeseverypointandfinditsdistancewithalltheotherpointsintheplane.Thenkeeptrackoftheminimumdistancepointsandminimumdistance.TheclosestpairwillbefoundinO(n2)time.Letussupposethereisaverticalline,whichdividethegraphintotwoseparateparts(letuscallitleftandrightpart).Thebruteforcealgorithm,wewillnoticethatwearecomparingallthepointsinthelefthalfwiththepointsintherighthalf.Thisisthepointwherewearedoingsomeextrawork.

Page 489:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Tofindtheminimumweneedtoconsideronlythreecases:1)Closestpairintherighthalf2)Closestpairinthelefthalf.3)Closestpairintheboundaryregionofthetwohalves.(Grey)EverytimewewilldividethespaceSintotwopartsS1andS2byaverticalline.RecursivelywewillcomputetheclosestpairinbothS1andS2.LetuscallminimumdistanceinspaceS1asδ1andminimumdistanceinspaceS2asδ2.Wewillfindδ=min(δ1,δ2)Nowwewillfindtheclosestpairintheboundaryregion.BytakingonepointeachfromS1andS2intheboundaryrangeofδwidthonbothsides.Thecandidatepairofpoint(p,q)wherepЄS1andqЄS2.

Wecanfindthepoints,whichlieinthisregioninlineartimeO(N)byjustscanningthroughallthepoints,andfindingthatallpointslieinthisregion.NowwecansorttheminincreasingorderinY-axisinjustO(nlogn)time.Thenscanthroughthemandgettheminimuminjustoneextralinearpass.Closestpaircannotbefarapartfromeachother.Letuslookintothenextfigure.

Page 490:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Thenthequestionishowmanypointsweneedtocompare.WeneedtocomparethepointssortedinY-axisonlyintherangeofδ.Therefore,thenumberofpointswillcomedowntoonly6points.

Bydoingthis,wearegettingequation.T(N)=2T(N/2)+N+NlogN+6N=O(n(logn)2)Canweoptimizethisfurther?YesInitially,whenwearesortingthepointsinXcoordinatewearesortingtheminYcoordinatetoo.When we divide the problem, then we traverse through the Y coordinate list too, and construct thecorrespondingYcoordinatelistforbothS1andS2.Thenpassthatlisttothem.SincewehavetheYcoordinatelistpassedtoafunctiontheδregionpointscanbefoundsortedintheYcoordinatesinjustonesinglepassinjustO(N)time.T(N)=2T(N/2)+N+N+6N=O(nlogn)//Findsclosestpairofpoints//Input:Asetofnpointssortedbycoordinates//Output:DistancebetweenclosestpairAlgorithmClosestPair(P)

ifn<2thenreturn∞elseifn=2thenreturndistancebetweenpairelsem=medianvalueforxcoordinateδ1=ClosestPair(pointswithx<m)δ2=ClosestPair(pointswithx>m)δ=min(δ1,δ2)δ3=processpointswithm−δ<x<m+δ

Page 491:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

returnmin(δ,δ3)Firstpre-processthepointsbysortingtheminXandYcoordinates.Usetwoseparateliststokeepthesesortedpoints.Beforerecursivelysolvingsub-problempassthesortedlistforthatsub-problem.

Page 492:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 493:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER19:DYNAMICPROGRAMMING

Page 494:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionWhilesolvingproblemsusingDivide-and-Conquermethod, theremaybeacasewhenrecursivelysub-problemscanresultinthesamecomputationbeingperformedmultipletimes.Thisproblemariseswhenthereareidenticalsub-problemsariserepeatedlyinarecursion.Dynamicprogrammingisusedtoavoidtherequirementofrepeatedcalculationofsamesub-problem.Inthismethod,weusuallystoretheresultofsub-problemsinsomedatastructure(likeatable)andreferittofindifwehavealreadycalculatedthesolutionofsub-problemsbeforecalculatingitagain.Dynamicprogrammingisappliedtosolveproblemswiththefollowingproperties:1.OptimalSubstructure:Anoptimalsolutionconstructedfromtheoptimalsolutionsofitssub-problems.2.OverlappingSubproblems:Whilecalculatingtheoptimalsolutionofsubproblemssamecomputationisrepeatedagainandagain.Examples:1.Fibonaccinumberscomputedbyiteration.2.Assembly-lineScheduling3.Matrix-chainMultiplication4.0/1KnapsackProblem5.LongestCommonSubsequence6.OptimalBinaryTree7.Warshall’salgorithmfortransitiveclosureimplementedbyiterations8.Floyd’salgorithmsforall-pairsshortestpaths9.OptimalPolygonTriangulation10.Floyd-Warshall’sAlgorithmStepsforsolving/recognizingifDPapplies.1.OptimalSubstructure:Trytofindifthereisarecursiverelationbetweenproblemandsub-problem.2.Writerecursiverelationoftheproblem.(ObserveOverlappingSubproblemsatthisstep.)3.Computethevalueofsubproblemsinabottomupfashionandstorethisvalueinsometable.4.Constructtheoptimalsolutionfromthevaluestoredinstep3.5.Repeatstep3and4untilyougetyoursolution.

Page 495:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsonDynamicprogrammingAlgorithm

Fibonaccinumbersintfibonacci(intn)

if(n<=1)returnn;returnfibonacci(n-1)+fibonacci(n-2);

Usingdivideandconquersamesub-problemissolvedagainandagain,whichreducetheperformanceofthealgorithm.ThisalgorithmhasanexponentialTimeComplexity.SameproblemofFibonaccicanbesolvedinlineartimeifwesorttheresultsofsubproblems.intfibonacci(intn)

intfirst=0,second=1;inttemp,i;

if(n==0)returnfirst;elseif(n==1)returnsecond;

for(i=2;i<=n;i++)temp=first+second;first=second;second=temp;returntemp;

Usingthisalgorithm,wewillgetFibonacciinlinearTimeComplexityandconstantSpaceComplexity.

Page 496:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Assembly-lineScheduling

Weconsider theproblemofcalculating the leastamountof timenecessary tobuildacarwhenusingamanufacturingchainwithtwoassemblinglines,asshowninthefigureTheproblemvariables:·e[i]:entrytimeinassemblylinei·x[i]:exittimefromassemblylinei·a[i,j]:TimerequiredatstationS[i,j](assemblylinei,stagej)·t[i,j]:TimerequiredtotransitfromstationS[i,j]totheotherassemblylineYourprogrammustcalculate:·Theleastamountoftimeneededtobuildacar·Thelistofstationstotraverseinordertoassembleacarasfastaspossible.Themanufacturingchainwillhavenomorethan50stations.If we want to solve this problem in the brute force approach, there will be in total 2n DifferentcombinationssotheTimeComplexitywillbeO(2n)Step1:CharacterizingthestructureoftheoptimalsolutionTocalculatethefastestassemblytime,weonlyneedtoknowthefastesttimetoS1;nandthefastesttimetoS2;n,includingtheassemblytimeforthenthpart.Thenwechoosebetweenthetwoexitingpointsbytakingintoconsiderationtheextratimerequired,x1andx2.TocomputethefastesttimetoS1;nweonlyneedtoknowthefastesttimetoS1;n1andtoS2;n1.Thenthereareonlytwochoices...Step2:Arecursivedefinitionofthevaluestobecomputed

Page 497:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Step3:Computingthefastesttimefinally,computef*asStep4:Computingthefastestpathcomputeasli[j]asthechoicemadeforfi[j](whetherthefirstorthesecondtermgivestheminimum).Also,computethechoiceforf*asl*.FASTEST-WAY(a,t,e,x,n)

f1[1]←e1+a1,1f2[1]←e2+a2,1forj←2tondoiff1[j-1]+a1,j≤f2[j-1]+t2,j-1+a1,jthenf1[j]←f1[j-1]+a1,jl1[j]←1elsef1[j]←f2[j-1]+t2,j-1+a1,jl1[j]←2iff2[j-1]+a2,j≤f1[j-1]+t1,j-1+a2,jthenf2[j]←f2[j-1]+a2,jl2[j]←2elsef2[j]∞f1[j-1]+t1,j-1+a2,jl2[j]←1iff1[n]+x1≤f2[n]+x2

thenf*=f1[n]+x1l*=1elsef*=f2[n]+x2l*=2

MatrixchainmultiplicationSameproblemisalsoknownasMatrixChainOrderingProblemorOptimal-parenthesizationofmatrixproblem.Givenasequenceofmatrices,M=M1,…,Mn.Thegoalofthisproblemistofindthemostefficientwaytomultiplythesematrices.Theguildisnottoperformtheactualmultiplication,buttodecidethesequenceofthematrixmultiplications,sothattheresultwillbecalculatedinminimaloperations.Tocomputetheproductof twomatricesofdimensionspXqandqXr,pqrnumberofoperationswillberequired.Matrixmultiplicationoperationsareassociativeinnature.Therefore,matrixmultiplicationcanbedoneinmanyways.Forexample,M1,M2,M3andM4,canbefullyparenthesizedas:(M1·(M2·(M3·M4)))(M1·((M2·M3)·M4))((M1·M2)·(M3·M4))(((M1·M2)·M3)·M4)((M1·(M2·M3))·M4)Forexample,LetM1dimensionsare10×100,M2dimensionsare100×10,andM3dimensionsare10×50.

Page 498:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

((M1·M2)·M3)=(10*100*10)+(10*10*50)=15000(M1·(M2·M3)=(100*10*50)+(10*100*50)=100000Therefore, in thisproblemweneed toparenthesize thematrix chain so that totalmultiplicationcost isminimized.GivenasequenceofnmatricesM1,M2,…Mn.Andtheirdimensionsarep0,p1,p2,…,pn.WherematrixAi has dimension pi − 1 × pi for 1 ≤ i ≤ n.Determine the order ofmultiplication thatminimizesthetotalnumberofmultiplications.If you try to solve this problem using the brute - force method, then you will find all possibleparenthesization. Thenwill compute the cost ofmultiplication. Thenwill pick the best solution. Thisapproachwillbeexponentialinnature.Thereisaninsufficiencyinthebruteforceapproach.TakeanexampleofM1,M2,…,Mn.Whenyouhavecalculated that ((M1·M2) ·M3) is better than (M1· (M2·M3) so there is no point of calculating thencombinationsof(M1·(M2·M3)with(M4,M5….Mn).Optimalsubstructure:AssumethatM(1,N)istheoptimumcostofproductionoftheM1,…,Mn.Anarrayp[]torecordthedimensionsofthematrices.P[0]=rowoftheM1p[i]=colofMi1<=i<=NForsomekM(1,N)=M(1,K)+M(K+1,N)+p0*pk*pnIfM(1,N)isminimalthenbothM(1,K)&M(K+1,N)areminimal.Otherwise,ifthereissomeM’(1,K)istherewhosecostislessthanM(1..K),thenM(1..N)can'tbeminimalandthereisamoreoptimalsolutionpossible.Forsomegeneraliandj.M(i,j)=M(i,K)+M(K+1,j)+pi-1*pk*pjRecurrencerelation:

M(i,j)=OverlappingSubproblems:

Page 499:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Directlycallingrecursivefunctionwillleadtocalculationofsamesub-problemmultipletimes.Thiswillleadtoexponentialsolution.AlgorithmMatrixChainMultiplication(p[])

fori:=1tonM[i,i]:=0;forl=2ton//listhemovinglinefori=1ton−l+1j=i+l−1;M[i,j]=i≤k<j

TimeComplexitywillO(n3ConstructingoptimalparenthesisSolutionUse another table s[1..n, 1..n]. Each entry s[i, j] records the value of k such that the optimalparenthesizationofMiMi+1...MjsplitstheproductbetweenMkandMk+1.AlgorithmMatrixChainMultiplication(p[])fori:=1ton

M[i,i]:=0;forl=2ton//listhemovingline

fori=1ton−l+1j=i+l−1;M[i,j]=i≤k<jS[i,j]=i≤k<j

AlgorithmMatrixChainMultiplication(p[])

fori:=1ton

Page 500:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

M[i,i]:=0;forl=2ton//listhemovinglinefori=1ton−l+1j=i+l−1;fork=itojif((M[i,j]=(S[i,j]=k

AlgorithmPrintOptimalParenthesis(s[],i,j)

Ifi=jPrintAiElsePrint“(”PrintOptimalParenthesis(s[],i,s[i,j])PrintOptimalParenthesis(s[],s[i,j],j)Print“)”

LongestCommonSubsequenceLetX=x1,x2,….,xmisasequenceofcharacters.AndY=y1,y2,…,ynisanothersequence.ZisasubsequenceofXifitcanbedrivenbydeletingsomeelementsofX.ZisasubsequenceofYifitcanbedrivenbydeletingsomeelementsformY.ZisLCSofitissubsequencetobothXandY,andthereisnosubsequencewhoselengthisgreaterthanZ.OptimalSubstructure:LetX=<x1,x2,...,xm>andY=<y1,y2,...,yn>betwosequences,andletZ=<z1,z2,...,zk>beaLCSofXandY.·Ifxm=yn,thenzk=xm=yn⇒Zk−1isaLCSofXm−1andYn−1·Ifxm!=yn,then:

ozk!=xm⇒ZisanLCSofXm−1andY.ozk!=yn⇒ZisanLCSofXandYn−1.

RecurrencerelationLetc[i,j]bethelengthofthelongestcommonsubsequencebetweenX=x1,x2,….,xiandY=y1,y2,…,yj.Thenc[n,m]containsthelengthofanLCSofXandY

AlgorithmLCS(X[],m,Y[],n)

Page 501:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

fori=1tomc[i,0]=0forj=1tonc[0,j]=0;fori=1tomforj=1tonifX[i]==Y[j]c[i,j]=c[i-1,j-1]+1b[i,j]=elseifc[i-1,j]≥c[i,j-1]c[i,j]=c[i-1,j]b[i,j]=↑elsec[i,j]=c[i,j-1]b[i,j]=←

AlgorithmPrintLCS(b[],X[],i,j)

ifi=0returnifj=0returnifb[i,j]=PrintLCS(b[],X[],i−1,j−1)printX[i]elseifb[i,j]=↑PrintLCS(b[],X[],i−1,j)elsePrintLCS(b[],X[],i,j−1)

CoinExchangingproblemHowcanagivenamountofmoneyNbemadewiththeleastnumberofcoinsofgivenDoneminationsD=d1…dn?Forexample,Indiancoinsystem5,10,20,25,50,100.Supposewewanttogivechangeofacertainamountof40paisa.Wecanmakeasolutionbyrepeatedlychoosingacoin≤tothecurrentamount,resultinginanewamount.Thegreedysolutionalwayschoosethelargestcoinvaluepossible.For40paisa:25,10,and5Thisishowbillionsofpeoplearoundtheglobedochangeeveryday.Thatisanapproximatesolutionoftheproblem.Butthisisnottheoptimalway,theoptimalsolutionfortheaboveproblemis20,20

Page 502:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Step(I):Characterizethestructureofacoin-changesolution.DefineC[j]tobetheminimumnumberofcoinsweneedtomakeachangeforjcents.If we knew that an optimal solution for the problem of making change for j cents used a coin ofDoneminationdi,wewouldhave:C[j]=1+C[j−di]Strep(II):Recursivelydefinesthevalueofanoptimalsolution.

Step(III):Computevaluesinabottom-upfashion.AlgorithmCoinExchange(n,d[],k)

C[0]=0forj=1tondoC[j]=infinitefori=1tokdoifj<diand1+C[j−di]<C[j]thenC[j]=1+C[j−di]returnC

Complexity:O(nk)Step(iv):ConstructanoptimalsolutionWeuseanadditionalarrayDone[1..n],whereDone[j]istheDoneminationofacoinusedinanoptimalsolution.AlgorithmCoinExchange(n,d[],k)

C[0]=0forj=1tondoC[j]=infinitefori=1tokdoifj<diand1+C[j−di]<C[j]thenC[j]=1+C[j−di]Done[j]=direturnC

AlgorithmPrintCoins(Done[],j)

ifj>0PrintCoins(Done,j−Done[j])printDone[j]

Page 503:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 504:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER20:BACKTRACKINGANDBRANCH-AND-BOUND

Page 505:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionSupposethelockproducesomesound“click”correctdigitisselectedforanylevel.Youjustwillfindthefirstdigit, thenfindtheseconddigit, thenfindthethirddigitanddone.Thiswillbeagreedyalgorithmandyouwillfindthesolutionveryquickly.However,letussupposethelockissomeoldoneanditcreatessamesoundnotonlyatthecorrectdigitbut at some other digits. Therefore,when you are trying to find the digit of the first ring, then itmayproductsoundatmultipleinstances.Soatthispointyouarenotdirectlygoingstraighttothesolution,butyouneedtotestvariousstatesandincasethosestatesarenotthesolutionyouarelookingfor,thenyouneedtobacktrackonestepatatimeandfindthenextsolution.Sure,thisintelligence/heuristicsofclicksound will help you to reach your goal much faster. These functions are called Pruning function orboundingfunctions.

Page 506:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ProblemsonBacktrackingAlgorithm

NQueensProblemThere areN queens given, you need to arrange them in aNxN chessboard, such that no queen shouldattacheachother.voidprint(int*Q,intn)

for(inti=0;i<n;i++)printf("%d",Q[i]);

intFeasible(int*Q,intk)

for(inti=0;i<k;i++)if(Q[k]==Q[i]||abs(Q[i]-Q[k])==abs(i-k))return0;return1;

voidNQueens(int*Q,intk,intn)

if(k==n)print(Q,n);return;for(inti=0;i<n;i++)Q[k]=i;if(Feasible(Q,k))NQueens(Q,k+1,n);

intmain()

intQ[8];NQueens(Q,0,8);return0;

Page 507:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TowerofHanoiTheTowerofHanoipuzzle,disksneedtobemovedfromonepillartoanothersuchthatanylargediskcannotrestaboveanysmalldisk.Thisisafamouspuzzleintheprogrammingworld,itsoriginscanbetrackedbacktoIndia."There isastoryaboutanIndian temple inKashiViswanathanwhichcontainsa largeroomwith threetimeworn posts in it surrounded by 64 golden disks. Brahmin priests, acting out the command of anancientHinduprophecy, have beenmoving these disks, in accordancewith the immutable rules of theBrahma thecreatorofuniverse, since thebeginningof time.Thepuzzle is thereforealsoknownas theTowerofBrahmapuzzle.Accordingtotheprophecy,whenthelastmoveofthepuzzlewillbecompleted,theworldwillend.";););)

voidtowers(intnum,charfrom,charto,chartemp)if(num<1)return;towers(num-1,from,temp,to);printf("\nMovedisk%dfrompeg%ctopeg%c",num,from,to);towers(num-1,temp,to,from);

intmain()

intnum=10;printf("ThesequenceofmovesinvolvedintheTowerofHanoiare:\n");towers(num,'A','C','B');return0;

Page 508:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 509:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER21:COMPLEXITYTHEORYANDNPCOMPLETENESS

Page 510:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionComputational complexity is the measurement of how much resources are required to solve someproblem.Therearetwotypesofresources:1.Time:howmanystepsittakestosolveaproblem2.Space:howmuchmemoryittakestosolveaproblem.

Page 511:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Decisionproblem

MuchofComplexity theorydealswithdecisionproblems.Adecisionproblemalwayshasayesornoanswer.Manyproblemscanbeconvertedtoadecisionproblemthathaveansweredasyesorno.Forexample:1.Searching:Theproblemofsearchingelementcanbeadecisionproblemifweasktofindifaparticular

numberisthereinthelist.2.Sortingof list and find if the list is sortedyou canmakeadecisionproblem is the list is sorted in

increasingorderornot?3.Graphcolouringalgorithms:thisisalsocanbeconvertedtoadecisionproblem.Canwedothegraph

colouringbyusingXnumberofcolours?4.Hamiltoniancycle:Is thereisapathfromall thenodes,eachnodeisvisitedexactlyonceandcome

backtothestartingnodewithoutbreaking?

Page 512:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ComplexityClassesProblemsaredividedintomanyclassessuchthathowdifficulttosolvethemorhowdifficulttofindifthegivensolutioniscorrectornot.

Page 513:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ClassPproblemsTheclassPconsistsofasetofproblemsthatcanbesolvedinpolynomialtime.ThecomplexityofaPproblemisO(nk)Wherenisinputsizeandkissomeconstant(itcannotdependonn).Class PDefinition: The class P contains all decision problems forwhich a Turingmachine algorithmleadstothe“yes/no”answerinadefinitenumberofstepsboundedbyapolynomialfunction.Forexample:Givenasequencea1,a2,a3….an.FindifanumberXisinthisarray.Wecansearch,thenumberXinthisarrayinlineartime(polynomialtime)Anotherexample:Givenasequencea1,a2,a3….an.Ifweareaskedtosortthesequence.WecansortandarrayinpolynomialtimeusingBubble-Sort,thisisalsolineartime.Note:O(logn)isalsopolynomial.Anyalgorithmthathascomplexitylessthansomepolynomialfunctionisalsopolynomial.SomeproblemofPclassis:1.Shortestpath2.Minimumspanningtree3.Maximumproblem.4.Maxflowgraphproblem.5.Convexhull

Page 514:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ClassNPproblemsSet of problems forwhich there is a polynomial time checking algorithm.Given a solution ifwe cancheckinapolynomialtimeifthatsolutioniscorrectornotthen,theproblemisNPproblem.ClassNPDefinition:TheclassNPcontainsalldecisionproblemsforwhich,givenasolution,thereexistsapolynomialtime“proof”or“certificate”thatcanverifyifthesolutionistheright“yes/no”answer

Note:Thereisnoguaranteethatyouwillbeabletosolvethisprobleminpolynomialtime.However,ifaproblemisanNPproblem,thenyoucanverifyananswerinpolynomialtime.NPdoesnotmeans“non-polynomial”.Actually, it is“Non-DeterministicPolynomial” typeofproblem.They are the kind of problems that can be solved in polynomial time by a Non-Deterministic Turingmachine.Ateachpoint,allthepossibilitiesareexecutedinparallel.Iftherearenpossiblechoices,thenallncaseswillbeexecutedinparallel.Wedonothavenon-deterministiccomputers.DonotconfuseitwithparallelcomputingbecausethenumberofCPUislimitedinparallelcomputingitmaybe16coreor32core,butitcannotbeN-Core.InshortNPproblemsarethoseproblemsforwhich,ifasolutionisgiven.Wecanverifythatsolution(ifitiscorrectornot)inpolynomialtime.

BooleanSatisfiabilityproblemABooleanformulaissatisfiedifthereexistsomeassignmentofthevalues0and1toitsvariablesthatcausesittoevaluateto1.

ThereareintotalNDifferentBooleanVariablesA1,A2…AN.ThereareanMnumberofbrackets.EachbrackethasKvariables.There isNvariable so thenumberof solutionswill be2n In addition, to verify if the solutions reallyevaluatetheequationto1willtaketotal2n*kmstepsGivensolutionofthisproblemyoucanfindiftheformulasatisfiesornotinKMsteps.

HamiltoniancycleHamiltoniancycle isapath fromall thenodesofagraph,eachnode isvisitedexactlyonce and comebacktothestartingnodewithoutbreaking.IsanNPproblem,ifyouhaveasolutiontoit,thenyoujustneedtoseeifallthenodesarethereinthepath

Page 515:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

andyoucamebacktowhereyoustartedandyouaredone?Thecheckingisdoneinlineartimeandyouaredone.DeterminingwhetheradirectedgraphhasaHamiltoniancycledoesnothaveapolynomialtimealgorithm.O(n!)However, ifsomeonehavegivenyouasequenceofvertices,determiningwhether thatsequenceformsaHamiltoniancyclecanbedone inpolynomial time(Linear time).HamiltoniancyclesareinNP

CliqueProblemIn a graph given is there is a clique of size K or more. A clique is a subset of nodes that are fullyconnectedtoeachother.ThisproblemisNPproblem.Givenasetofnodes,youcanveryeasilyfindoutwhetheritisacliqueornot.Forexample:

PrimeNumberFindingPrimenumberisNP.Givenasolution,itiseasytofindifitisaPrimeornotinpolynomialtime.Findingprimenumbersisimportantascryptographyheavilyusesprimenumbers.intisPrime(intn)

intanswer=(n>1)?1:0;

for(inti=2;i*i<=n;++i)if(n%i==0)answer=0;break;returnanswer;

Checkingwill happen until the square root of number so the TimeComplexitywill beO(√n).Hence,primenumberfindingisanNPproblemaswecanverifythesolutioninpolynomialtime.

Page 516:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Graphtheoryhavewonderfulsetofproblems•Shortestpathalgorithms?•LongestpathisNPcomplete.•Euleriantoursisapolynomialtimeproblem.•HamiltoniantoursisaNPcomplete

Page 517:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Classco-NPSet of problems forwhich there is a polynomial time checking algorithm.Given a solution, ifwe cancheckinapolynomialtimeifthatsolutionisincorrecttheproblemisco-NPproblem.Class co-NP Definition: The class co-NP contains all decision problems such that there exists apolynomialtimeproofthatcanverifyiftheproblemdoesnothavetheright“yes/no”answer.

ClassPisSubsetofClassNPAllproblemsthatarePalsoareNP(P NP).ProblemsetPisasubsetofproblemsetNP.SearchingIfwehavesomenumbersequencea1,a2,a3….an.WealreadyknowthatsearchinganumberXinsidethisarrayisoftypeP.IfitisgiventhatnumberXisinsidethissequence,thenwecanverifybylookingintoeveryentryagainandfindiftheansweriscorrectinpolynomialtime(lineartime.)SortingAnotherexampleofsortinganumbersequence,ifitisgiventhatthearrayb1,b2,b3..bnisasortedthenwecanloopthroughthisgivenarrayandfindifthelistisreallysortedinpolynomialtime(lineartimeagain.)

Page 518:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

NP–Hard:AproblemisNP-HardifalltheproblemsinNPcanbereducedtoitinpolynomialtime.

Page 519:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

NP–CompleteProblemsSetofproblemisNP-CompleteifitisanNPproblemandanNP-Hardproblem.Itshouldfollowboththeproperties:1)Itssolutionscanbeverifiedinapolynomialtime.2)AllproblemsofNParereducedtoNPcompleteproblemsinpolynomialtime.YoucanalwaysreduceanyNPproblemintoNP-Completeinpolynomialtime.Moreover,whenyougettheanswertotheproblem,thenyoucanverifythissolutioninpolynomialtime.

AnyNPproblemispolynomialreducedtoNP-Completeproblem, ifwecanfindasolutiontoasingleNP-Completeproblem inpolynomial time, thenwecansolveall theNPproblems inpolynomial time.However,sofarnooneisabletofindanysolutionofNP-Completeprobleminpolynomialtime.P≠NP

Page 520:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Reduction

Itisaprocessoftransformationofoneproblemintoanotherproblem.Thetransformationtimeshouldbepolynomial.IfaproblemAistransformedintoBandweknowthesolutionofBinpolynomialtime,thenAcanalsobesolvedinpolynomialtime.Forexample,QuadraticEquationSolver:WehaveaQuadraticEquationSolver,whichsolvesequationoftheformax2+bx+c=0.IttakesInputa,b,candgenerateoutputr1,r2.Nowtry tosolvea linearequation2x+4=0.Usingreductionsecondequationcanbe transformedto thefirstequation.2x+4=0x2+2x+4=0ATLAS:Wehaveanatlasandweneedtocolourmapssothatnotwocountrieshavethesamecolour.Letussupposebelowisthevariouscountries.Inaddition,differentpatternrepresentsdifferentcolour.

Wecanseethatsameproblemofatlascolouringcanbereducedtographcolouringandifweknowthesolutionofgraphcolouringthensamesolutioncanworkforatlascolouringtoo.Whereeachnodeofthegraphrepresentsonecountryandtheadjacentcountryrelationisrepresentedbytheedgesbetweennodes.

Thesortingproblemreduces(≤)toConvexHullproblem.SATreduces(≤)to3SAT

TravelingSalesmanProblem(TSP)

Page 521:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Thetravelingsalesmanproblemtriestofindtheshortesttourthroughagivensetofncitiesthatvisitseachcityexactlyoncebeforereturningtothecitywhereitstarted.Alternatively find the shortestHamiltonian circuit in aweighted connected graph.A cycle that passesthroughalltheverticesofthegraphexactlyonce.AlgorithmTSPSelectacityMinTourCost=infiniteFor(Allpermutationsofcities)do

If(LengthOfPathSinglePermutation<MinTourCost)MinTourCost=LengthOfPath

Totalnumberofpossiblecombinations=(n-1)!Costforcalculatingthepath:Θ(n)Sothetotalcostforfindingtheshortestpath:Θ(n!)It is anNP-Hard problem there is no efficient algorithm to find its solution. Even if some solution isgiven, it is equally hard to verify that this is a correct solution or not. However, some approximatealgorithmscanbeusedtofindagoodsolution.Wewillnotalwaysget thebestsolution,butwillgetagoodsolution.Our approximate algorithm is based on the minimum spanning tree problem. In which we have toconstructatreefromagraphsuchthateverynodeisconnectedbyedgesofthegraphandthetotalsumofthecostofalltheedgesitminimum.

Intheabovediagram,wehaveagroupofcities(eachcityisrepresentedbyacircle.)Whicharelocatedinthegridandthedistancebetweenthecitiesissameaspertheactualdistance.Andthereisapathfromeachcitytoanothercitywhichisastraightpathfromonetoanother.

Page 522:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Wehavemadeaminimumspanningtreefortheabovecitygraph.Whatwewant toprove that the shortestpath inaTSPwill alwaysbegreater than the lengthofMST.Since inMST all nodes are connected to the next node,which is also theminimumdistance from thegroupofnode.Therefore,tomakeitapathwithoutrepeatingthenodesweneedtogodirectlyfromonenodetootherwithoutfollowingMST.Atthatpoint,whenwearenotfollowingMSTwearechoosinganedge,whichisgrater,thentheedgesprovidedbyMST.SoTSPpathwillalwaysbegreaterthanorequaltoMSTpath.

Nowletustakeapathfromstartingnodeandtraverseeachnodeonthewaygivenaboveandthencomebacktothestartingnode.Thetotalcostofthepathis2MST.Theonlydifferenceisthatwearevisitingmanynodesmultipletimes.

Page 523:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

NowletuschangeourtraversalalgorithmsothatitwillbecomeTSPinourtraversal,wedidnotvisitanalreadyvisitednodewewillskipthemandwillvisitthenextunvisitednode.Inthisalgorithm,wewillreach thenextnodebyas shorterpath. (The sumof the lengthof all the edgesof apolygon is alwaysgreaterthanasingleedge.)Ultimately,wewillgettheTSPanditspathlengthisnomorethantwicetheoptimalsolution.Therefore,theproposedalgorithmgivesagoodresult.

Page 524:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

EndNoteNobody has come upwith such a polynomial-time algorithm to solve aNP-Complete problem.Manyimportantalgorithmsdependsuponit.However,atthesametimenobodyhasproventhatnopolynomialtime algorithm is possible.There is amillionUSdollars for anyonewho cando either solve anyNPCompleteprobleminpolynomial time.Thewholeeconomyof theworldwill fallasmostof thebanksdependsonpublickeyencryptionwillbeeasytobreakifP=NPsolutionisfound.

Page 525:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 526:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER22:INTERVIEWSTRATEGY

Page 527:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

IntroductionSuccessintechinterviewdependsonsomanyfactors,yournon-technicalskills,yourtechnicalskills,etc.Abovealltheinterviewersshouldbeconvincedthattheywouldenjoyworkingwithyou.

Page 528:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ResumeAgoodresumeisonethatcommunicateyourskillsandaccomplishmentsinaclearandeffectiveway.Agoodresumeformathasthefollowingattributes:1. Multiple Columns: Multiple columns make it easier for someone to skim your company name,

positions,collage,andotherkeyfacts.2.Brief:Interviewerisgoingtospendabout30Secreadingyourresume.Youshouldjustfocusonthe

highlights.Onepageisallyouneed,butifyouare10+yearsofexperience,thenyoucanjustifytwopages.

3.NoJunk:Noobjective,Nooath,Summarysection/Keyskills sectionmaybe fine, ifyour resume isshortandconcisethenyoudonotneedasummarysection.

4.UseTables:Youcanusetables,butitshouldnotwastespace.5.Highlights:highlightsshouldbeshort.Keepyourhighlightstoone-liner.6. Neat: Keep your resume neat and clean. Use appropriate Fonts and Formatting. Bold to represent

highlightsandmaybeitalicsinsomeplaces.

Page 529:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

NontechnicalquestionsPrepareforvariousnon-technicalquestions.Thefirst thingtodois toprepareanswersofanyquestionthatisrelatedtoyourresume.Theinterviewerisgoingtolookintoitandaskafewquestionstogetanideaaboutyou.Sogothroughallthepast/currentjobandprojectsandmakesureyouknowaboutthemandyourrole.Thesequestionsmaybelike:1.WhatwasthemostchallengingactivityyouhavedoneinprojectABC?2.WhatdidyoulearnfromprojectABC?3.Whatareyourresponsibilitiesinthecurrentjob?4.Whatwasthemostinterestingthingyouhavedoneinyourcurrentjob?5.Whichcourseinuniversitydidyoulikemostandwhy?

Page 530:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

TechnicalquestionsSolving a technical question is not just about knowing the algorithms and designing a good softwaresystem.Theinterviewerwantstoknowyouapproachtowardsanygivenproblem.Manypeoplemakemistakes,astheydonotaskclarifyingquestionsaboutagivenproblem.Theyassumemanythingsandbeginworkingwith that.Well the truth is the interviewer toactuallyexpectyoutoaskconstraintsquestions.Thereislotofdatathatismissingthatyouneedtocollectfromyourinterviewerbeforebeginningtosolveaproblem.Forexample,Letussupposetheintervieweraskyoutogiveabestsortingalgorithm.Some interviewee will directly jump to Quick-SortO(nlogn). Oops, mistake you need to ask manyquestionsbeforebeginningtosolvethisproblem.Questions:1.Whatkindofdatawearegoingtosort?Aretheyintegers?2.Howmuchdataarewegoingtosort?3.Whatexactlyisthisdataabout?4.Whatkindofdata-structureusedtoholdthisdata?5.Canwemodifythegivendata-structure?Andmore…?Answer:1.Yes,theyareintegers.2.Maybethousands.3.Theystoreaperson’sage.4.Dataaregivenintheformofsomearray.5.No,youcannotmodifythedatastructureprovided.Okfromthefirstanswer,wewilldeducethatthedataisinteger.Thedataisnotsobigitjustcontainsafewthousandentries.Thethirdanswerisinterestingfromthiswededucethattherangeofdatais1-150.Dataisprovidedinanarray.Fromfifthsanswerwededucethatwehavetocreateourowndatastructureandwecannotmodifythearrayprovided.Sofinally,weconclude,wecanjustusebucketsorttosortthedata.Therangeisjust1-150soweneedjust151-capacityintegralarray.DataisunderthousandssowedonothavetoworryaboutdataoverflowandwegetthesolutioninlineartimeO(N).

Page 531:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 532:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

CHAPTER23:SYSTEMDESIGN

Page 533:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

SystemDesignThesectionwewilllookintoquestionsinwhichintervieweraskstodesignahigh-levelarchitectureofanysoftwaresystem.Note:-ThisisanadvancechapterItmaybethattheuserisnotabletounderstanditcompletely.Iwouldsuggest that give it some time read the chapter and try to read online.Themore time you give to thischapterthebetterunderstandingyouwillget.Itmayalsohelpifyougivemultipleroundsofreading.Therearetwokindsofquestionsinthisandwhichwillbeaskeddependsonthetypeofcompanies.Thefirstkindofquestions is todesign somekindofelevator system,valetparkingsystem,etc. In this, theinterviewerjustwantstotesthowwellyouareabletodesignasystem,especiallyhowwellyourclassesareinteracting.The Second kind of systemdesign problems ismore interesting, inwhich the interviewer asks you todesignsomekindofwebsiteorsomekindofserviceorsomeAPIinterface.Forexample,designgooglesearchengineordesignsomefeatureofFacebooklikehowfriendsmappingisdoneonFacebook,designa web-based game that allows 4 people play poker etc. They are interesting one and in this, theinterviewercanaskaboutscalabilityaspect.Nowcomesaquestiontoourmind,howwouldyoudesigngooglesearchenginein10-15minutes?Well,theanswerisyoucannot.Ittookmanydaysifnotyearsbyagroupofasmartengineertodesigngooglesearchengine.TheinterviewerisexpectingaHigher-levelarchitectureofthesystemthatcanaddressthegivenUse-Cases and Constraints of the problem in hand. There is no single right solution. The sameproblemcanbesolvedinanumberofways.Themostimportantthingisthatyoushouldbeabletojustifyyoursolution.

Page 534:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

SystemDesignProcessLetuslookintoa5Stepsapproachforsolvingsystemdesignproblems:1.UseCasesGeneration2.ConstraintsandAnalysis3.BasicDesign4.Bottlenecks5.Scalability

UseCasesJust like algorithm design problems, the system design questions are alsomost likelyweakly defined.Thereissomuchinformationthatismissingandwithoutthis,thedesignisimpossible.Sofirstthinginthedesignprocessistogatherallthepossibleusecases.Youshouldaskquestionstotheinterviewertofindtheusecaseofthesystem.Theinterviewerwantstoseeyourrequirementgatheringcapability.Sameasalgorithmquestionsneverassumethings,whicharenotstated.

ConstraintsandAnalysisThis is thestepinwhichyouwilldefinevariousconstraintsof thesystemandthenanalyse them.Yoursystemdesignwilldependontheanalysisthatyoudointhisstep.Inthisstep,youneedtofindanswerstoquestionslike.Howmanyuserswillbeusingthesystem?Whatkindofdatathatwearegoingtostore?Etc.

BasicDesignInthisstep,youwilldesignthemostbasicdesignofthesystem.Drawyourmaincomponentsandmakeconnectionsbetweenthem.Inthisstep,youneedtodesignasystemwiththesuppositionthatthereisnomemorylimitationandalldatacanfitinonesinglemachine.Youshouldbeabletojustifyyouridea.Inthisstep,youneedtohandlealltheuse-cases.

BottlenecksAnalysisIn this step, you will find the one or more bottlenecks on the basic design you had proposed. The“Scalability Theory” given belowwill help to identify the bottlenecks. You need to know the belowtheory which experts had developed over time. In this step, you will consider how much data yourproposedsystemcanhandle,memorylimitationsetc.

ScalabilityInthisstep,youwillremoveallthebottlenecksofthesystemandyouaredone.Theremaybemultipleiterationsbetween“Bottlenecksanalysis”and“Scalability”untilwereachourfinalsolution.Wewillbereading various concepts like Vertical scaling, Horizontal scaling, Load-Balancer, Redundancy andCachinginthischapter.“ScalabilityTheory”givenbelowwillhelpyoutounderstandtheseconcepts.

Page 535:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ScalabilityTheoryIn this section,wewill be designing a genericweb server,whichwill be handling a large number ofrequests.YoucanimagineitassomesortofwebsitelikeFacebookinwhichlargenumberofusersareaccessingit.

VerticalscalingVerticalscalingmeansthatyouscalebyaddingmoreresources(HigherspeedCPU,MoreRAMetc.)Toyourexistingmachine.Verticalscalinghasitsownlimititcanhelpyoutohandlemoreload,butuntilitslimitisreached,thenwehavetogoforhorizontalscaling.

HorizontalscalingHorizontalscalingmeansthatyouscalebyaddingmoremachinestoyourpoolofresources.Distributetherequestbydistributingtherequestamongmorethanonewebserver.Indoingthisweneedtohavealoadbalancer,whichwilldistributetherequestamongtheservers.

LoadBalancer(Applicationlayer)Loadbalancerhastodecidewhichservershouldservethenextrequest.Sodistributingtheloadcanbemadeusingdifferentstrategies:1.RoundRobbin:Roundrobinisthewayofdistributingrequestsinasequentialfashion.Therequestis

sent to theserver1 then thenext request issent toserver2andsoonuntilwereach theendof theserverlist.Thenwhenwereachtheend,itissentagaintoserver1.Roundrobinhasaproblemthataserver,which isalreadybusy,maygetanother request.Round robinalsohasaproblemwithstickysessions.Wewantthatarequesttobesenttothesameserverthenexttime.

2.Anotherapproachistoselectservercorrespondstothehashvalueofthedata.Findthehashvalueofthedata,modthehashvaluebythenumberofservers.Assignthejobtoamachinewhosevaluewegotaftermod.Sticksessionproblemisalreadysolvedinhashvalueapproach.However,theproblemofuneven load distribution is there, there is possible to have amore load sent to a server, which isalreadybusy.

3.May be the load balancer know, howmuch load each server has or how busy each the server is.

Page 536:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Moreover,willsendthenextrequesttotheleastbusyserver.4.Theservercanbeaspecializedoneservingimagesomeservingvideoandsomeservingotherdata.

ProblemsofLoadBalancingConsideracustomerwhohadselectedsomeitemsinhisbuycartonAmazon.Whenheselectsanotheritemthenitshouldbeaddedtothesamecartsoitshouldbesenttothesameserver.Inaddition,theuserprofile that is saved to one server and if the user request reaches the other server his profilewill beemptythisisalsonotagoodidea.This problem can be solved bymaking the load balancer decide that a particular user requestwouldalwaysgotothesameserver.Theuserprofileandcartdetailsshouldbesavedinsomedatabase.Sticksession:samesessionsshouldlendtothesameserver.Howtogetthisdone.ThefirstapproachisthatwestoretheIPaddressreturnedbyloadbalancingintoacookieandthenusethisIPaddressinthesubsequentrequests.However,thisrevealstheIPaddressoftheservertotheworldthatwedonotwant.Therefore,anothersolutionisthatweusesomesessionidthatisanumberthattheloadbalancerknowsthatbelongstowhichserver.Bythis,wearepreventingourserversbeingexposedtotheouterworldandpreventitfrombeingattacked.

LoadBalancer(Databaselayer)1.ThemostbasicapproachisRoundRobin.Dataisdistributedinacircularfashion.First,datagotothe

first database, the secondwill go to the second database and so one.Each database server had anequalload.However,ithasadisadvantagethatthedatalookupiscomplex.Andneedalargelookuptable.

2.Anotherapproachistodividethedatainsuchawaythatallthedatawillgotothefirstmachineuntilit

reaches its maximum capacity. When maximum capacity is reached, then data goes to the secondmachineandsoon.Thisapproachhasanadvantagethatonlytherequirednumberofmachinesisused.However,ithasadisadvantagethatthedatalookupiscomplex.Andneedalargelookuptable.

3.Anotherapproachistoselectdatabasecorrespondstothehashvalueofthedata.Findthehashvalueof

thedata.Modthehashvaluebythenumberofdatabases.Thedataarethenstoredinthedatabasevalue

Page 537:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

wegotaftermodulus.Forhasavalueapproachwedonotrequireanylookuptable.Wecanfindthedatabase, which is storing the data, by finding the hash value. However, the problem of unevendistributionofdataisthere,thereispossibletohaveamoredatasenttoadatabase,whichhasalreadyreached itsmaximumcapacity. In thiscase,weneed to findabetter load-balancingkeyor split thedatafromthedatabaseintoanumberofdatabases.

4. In thehashvalue,baseddistributionofdata there isno relationbetween thedata that is stored ina

particulardatabase.Informationaboutthedatacanbeusedtomakethedatabaseaccessiblefaster.Forexample, in social networking likeFacebook, if someonewho lives in India ismore likely tohavefriendsfromIndia.AndsomeonewholivesintheUSAismorelikelytohavefriendsintheUSA.

5.Perhapslocationaware(approach4)andthehashvaluebased(approach3)distributionofdatamaybe

thebestapproachtokeepthedatasothatitcantakeadvantageofboththeapproaches.CountrycodeanduserIDcanbeusedtogetthelocationofthedatabase.

RedundancyThereisoneprobleminoursystem,thereisaredundancyintheserversbutourloadbalancerisnowoursinglepointof failure.Weadda secondary loadbalancer incase theprimary loadbalancerdies, thensecondaryloadbalancerbecomesprimaryandthenalltherequestswillbehandledbyit.

Raid (Redundant Array of Inexpensive Disk): Raid is a technology to create redundancy in thedatabases.Multipleharddrivesareusedtoreplicatedata,therebyprovingredundancy.

CachingAcacheisasimplekey-valuestoreanditshouldresideasabufferinglayerbetweenyourapplicationandyourdatastorage.Wheneveryourapplicationwants toread, it first tries toretrieve thedatafromyourcache.Onlyifdataisnotpresentinthecache,thenonlyittriestogetthedatafromthemaindatabase.Cachingimprovesapplicationperformancebystoringportionofdatainmemoryforlow-latencyaccess.Weneeddatabasesandaccesstothedatabaseisslow,soweusemultipletypesofcachingtomakeoursystemfaster.Databaseservers itselfdoescachingsodo theotherentities inbetween theuserand thedatabase.

Page 538:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Memcached:Itisaserversoftware,whatitdoesisitkeptwhateveryouaccessinmemory.Itcanrunonthesameserverasthewebserveroritcanrunonaseparatemachinealltogether.Redis:ItisadataserverbasedonNoSQL,whichisakey-valuedatastore.Dataisstoredasthevaluewith respect tocorrespondingkey.Thisdata is later retrievedby theuseof thekey.Redis isused forcachingitisbesttostorethewholeobjectasoneinstancesothatthedatacanbeaccessedinparallelanddataexpirationwillflushoutthewholeobject.Thereisaproblemsinceramisfinite,thenthecachewillgetfull.Theexpiredobjectwillberemovedsoeverythingthatisaccessedthenitsexpirywillberesetandifthereisanobjectthatisnotusedforsometimethenitwasdeleted.Cacheismoreimportantwhenthewebsitethatwearedesigningismorereadheavierthanawrite.

AcompletewebserverimplementationThesummaryoftheabovesystem.1.TheWeb-Serversofscalablewebserviceishiddenbehindaloadbalancer.Theloadbalancerevenly

distributesloadacrossalltheservers.2.Theusershouldget thesameresult fromweb-server regardlesswhichserver isactuallyserving the

request.Therefore,everyservershouldbeidenticaltoeachother.Serversshouldnotcontainanydatalikesessioninformationoruserprofile.

3.Sessionneedtobestoredinacentralizeddatastore(DB)whichisaccessibletoalltheservers.Datacanbestoredinsomeexternaldatabase.Redundancyinthedatabaseisprovidedbyraidtechnology.

4.Thedatabaseisslow,soweneedacache.In-memorybasedcachelikeRedisorMemcached.5.However,thecachehasaproblemofexpiring.Whenatablechanges,thenthecacheisoutdated.6.ForMemcachedtherearetwooptions:

a.WecansavequeriestotheDBb.Wecansavethewholeobjectthatwillkeepusclosetoweb-server.

7.CDN(Contentdeliverynetworks)canbeusedtoprovideapre-processedwebpage.

Page 539:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Belowdiagramwillgiveyouacompletepictureofthewholesystem.

Page 540:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DesignsimplifiedFacebookDesignsimplifiedFacebookwherepeoplecanaddotherpeopleasfriends.Inaddition,wherepeoplecanpostmessagesandthatmessagesarevisibleontheirfriend’spage.Thedesignshouldbesuchthatitcanhandle10millionofpeople.Theremaybe,onanaverage100friendseachpersonhas.Everydayeachpersonpostssome10messagesonanaverage.

UseCase1.Ausercancreatetheirownprofile.2.Ausercanaddotheruserstohisfriendlist.3.Userscanpostmessagestotheirtimeline.4.Thesystemshoulddisplaypostsoffriendstothedisplayboard/timeline.5.Peoplecanlikeapost.6.Peoplecansharetheirfriendsposttotheirowndisplayboard/timeline.

Constraints1.Considerawholenetworkofpeopleasrepresentedbyagraph.Eachpersonisanodeandeachfriend

relationshipisanedgeofthegraph.2.Totalnumberofdistinctusers/nodes:10million3.Totalnumberofdistinctfriend’srelationship/edgesinthegraph:100*10million4.Numberofmessagespostedbyasingleuserperday:105.Totalnumberofmessagespostedbythewholenetworkperday:10*10million

BasicDesignOursystemarchitectureisdividedintotwoparts:1.First,thewebserverthatwillhandlealltheincomingrequests.2.Theseconddatabase,whichwillstoretheentireperson'sprofile,theirfriendrelationsandposts.

First,threerequirementscreatingaprofile,addingfriends,postingmessagesarewrittensomeinformationtothedatabase.Whilethelastoperationisreadingdatafromthedatabase.Thesystemwilllooklikethis:1.Eachuserwillhaveaprofile.2.Therewillbealistoffriendsineachuserprofile.

Page 541:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

3.Eachuserwillhavetheirownhomepagewherehispostswillbevisible.Auser can like anypostof their friendand that likeswill reflecton the actualmessage sharedbyhisfriend.Ifausersharessomepost,thenthispostwillbeaddedtotheuserhomepageandalltheotherfriendsoftheuserwillseethispostasanewpost.

BottleneckA number of requests posted per day is 100million.Approximate some 1000 request are posted persecond.Therewillbeanunevendistributionofloadsothesystemthatwewilldesignshouldbeabletohandleafewthousandrequestsperseconds.

ScalabilitySincethereis,aheavyloadweneedhorizontalscalingmanywebserverswillbehandlingtherequests.Indoingthisweneedtohavealoadbalancer,whichwilldistributetherequestamongtheservers.

Thisapproachgivesusaflexibilitythatwhentheloadincreases,wecanaddmorewebserverstohandletheincreasedload.Theseweb servers are responsible forhandlingnewpost addedby theuser.Theyare responsible forgenerating various user homepage and timeline pages. In our diagram, the client is the web browser,whichisrenderingthepagefortheuser.Weneedtostoredataaboutuserprofile,Usersfriendlist,User-generatedposts,Userlikestatuestotheposts.Letusfindouthowmuchstorageweneedtostoreallthisdata.Thetotalnumberofusers10million.Letus suppose each user is usingFacebook for 5 to 6 years, so the total number of posts that a user hadproducedinthiswholetimeisapproximately20,000millionor20billion.Letussupposeeachmessageconsistsof100wordsor500characters.Letusassumeeachcharactertake2bytes.

Page 542:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Totalmemoryrequired=20*500*2billionbytes.

=20,000billionbytes=20,000GB=20TB

1gigabyte(GB)=1billionbytes1000gigabytes(GB)=1TerabytesMost of thememory is taken from the posts and the user profile and friend list will take nominal ascomparedwith the posts.We can use a relational database like SQL to store this data. Facebook andtwitterareusingarelationaldatabasetostoretheirdata.

Responsiveness is key for social networking site. Databases have their own cache to increase theirperformance.Stilldatabaseaccess isslowasdatabasesarestoredonharddrivesand theyareslowerthan RAM. Database performance can be increased by replication of the database. Requests can bedistributedbetweenthevariouscopiesofthedatabases.Also,therewillbemorereadsthenwritesinthedatabasesotherecanbemultipleslaveDBwhichareusedforreadingandtherecanbefewmasterDBforwriting.Stilldatabaseaccessisslowtowewillusesomecachingmechanism likeMemcached inbetweenapplication serveranddatabase.Highlypopularusersandtheirhomepagewillalwaysremaininthecache.Theremaybethecasewhenthereplicationnolongersolvestheperformanceproblem.Inaddition,weneedtodosomeGeo-locationbasedoptimizationinoursolution.Again,lookforacompletediagraminthescalabilitytheorysection.If it were asked in the interview how you would store the data in the database. The schema of thedatabasecanlooklike:TableUsers

·UserId·FirstName

TablePosts·PostId

Page 543:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

·LastName·Email·Password·Gender·Birthday·Relationship

·AuthorId·DateofCreation·Content

TableFriends·RelationId·FirstFriendId·SecondFriendId

TableLikes·Id·PostId·UserId

Page 544:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 545:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DesignFacebookFriendssuggestionfunctionDesignasystemtoimplementafriendsuggestionfunctionalityofFacebook,withmillionsofusers.Thealgorithmshouldsuggestallthefriendsoftheimmediatefriendsasaproposedlisttoaddasfriends.

UseCaseThesystemshouldsuggestfriendsofthefriendsassuggestednewfriends.

ConstraintMillionsofuser’slotofdatawithbillionsofrelations.

BasicDesignForgetaboutmillionsofusers. Justconsider thereareonlya fewpersonsand theyareconnectedwitheach other as friends.Consider that people are represented by vertices of graphs and their friendshiprelationisrepresentedbyedges.Sincethereareonlyafewpeople,thenwecankeepeverythinginmemoryandfindthefriendsuggestionusingBreadthFirstTraversal.Wejustneedtofindthenodes,whicharejust2degreesapartfromthestartingnode.

BottleneckSincetherearemillionsofusers,wecannothaveeverythinginmemory.Sincetherearemillionsofusers,wecannotkeepthedataononemachine.Onefriends’profilesmaylieonmanydifferentmachines.

ScalabilitySincetherearemillionsofusers,theiruserprofileisdistributedamongmanydifferentdatabaseservers.User profiles can be distributed depending uponGeo-Location. The Indian users profilewill lie in aserverlocatedinIndiaandUScitizen'sprofilelieintheserverlocatedintheUS.EachuserwillhavecorrespondingUserIdassociatedwiththem.SomeportionofIDcanbeusedtogetGeolocationoftheuser.Anotherportionofuseridcanfindtheuserprofileonthatserver.Theuserprofileisnotthatfrequentlyupdatedsothereismorereadthanwrite.Sosinglemasterwriter-multipleslavereaderarchitectureismostsuitableforthisapplication.Theapplicationservercanprocessthedata;itcandotheoptimizationtoquerylessfromthedatabasebyaccumulatinguserlisttobeprocessed.classsystem

privatemap<int,int>personIdToMachineIdMap;privatemap<int,Machine>machineIdToMachineMap;

Page 546:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

MachinegetMachine(intmachineId);getPerson(intpersonId)intmachienId=personIdToMachienIdMap[personId];Machinem=machineIdToMachineMap[machienId];returnm.getPersonWithId(personId);

Optimization:Reduced the number of jumpsby first finding the list of friendswhose profile is on thesamemachine.Thensendthefindnextdegreefriendsquerythatwillreturnthelistofnextlevelfriends.Bydoing,thisworkisdistributedamongvariousmachines.Finally,theresultofthevariousquerieswillbemerged,andthenfriendlistissuggested.Betterresult:Youcancalculatethedegreeofthefriendswiththefriendlist.Thepersonwhoisafriendofmanyofmyfriendsismorelikelytobemyfriendthanthepersonwhoisjustafriendofoneofmyfriends.WeneedtokeeptrackofthefriendreferencecountsbykeepingHash-Tableforthefriendlistandmakethecount1wheneverwefindanewpersonotherwiseincreasethecountby1.Ifwewanttotakeadvantageofcaching,thenweneedtoaddsomedatabasecacheinbetween.

Therecanbemultiplewebservers,whichwillbequeryingthedatabases.Alsomultipleuserswhoareaccessing their Facebook profile and each one of them is proposedwith new friends list so the finalarchitecture is again sameas theoneproposed in the completeweb server implemented in scalabilitytheory.

Page 547:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DesignashorteningservicelikeBitly

UseCaseBasicusecase:1.ShorteningtakesaURLandreturnsashortURL.2.RedirectiontakesashortURLandredirectstotheoriginalURL.3.CustomURL.4.Highavailabilityofthesystem.Additionalusecases:1.Analytics2.Automaticlinkexpiration.3.Manuallinkremoval.4.SpecificcompanyURL.5.UIorjustAPIRequirementAnalysis/MathFirst,weneedtofindtheusagepattern.You can directly ask this data from the interviewer or you can derive it using some data that theinterviewerprovides.Letussuppose that the interviewer tells that therewillbe1billion requestspermonth.Inaddition,outofthese10%times,itisanewrequestand90%ofthetime,itisaredirectionofthealreadyshortenedURL.Letuswritedownthedatathatweget.1.1BNrequestspermonth2.10%arefornewURL/shorteningand90%areforredirection.3.NewURLspermonthis100MLN4.Requestspersecond1BN/(30*24*3600)=385.Roughly,youcanassumeit400requestsperseconds.5.TotalnumberofURLsstoredin5years.

5*12*100MLN=6BNURLsin5years.6.LetussupposethespacerequiredbyeachURLis500bytes.7.LetussupposethespacerequiredbyeachHashcodeforcorrespondingURLsis6bytelong.8.Totaldataweneedtostoreinfiveyears.3TBsforalltheURLsand36gbforhashes

6,000,000,000*500bytes=3terabytes6,000,000,000*6bytes=36gigabytes

9.Newdatawriterequestspersecond:40*(500+6):20k

BasicdesignWebserver:providethewebsitefortheBitlyservicewhereuserscangeneratetheshortURL.ApplicationServer:providesthefollowingservices:1.Shorteningservice2.Redirectionservice3.Key=HashFunction(URL)

Page 548:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DatabaseServer:1.KeeptrackofhashtoURLmapping.2.WorkslikeahugeHash-Tablestoresthenewmappingandretrievesoldmappinggivenkey.Bottleneck1.Trafficisnotmuch2.Datastoragecanbeaproblem.

ScalabilityApplicationServer:1.Startwiththesinglemachine.2.Testhowfarittakesup.3.Wedoaverticalscalingforsometime.4.Addloadbalancerandaclusterofmachinestohandlespikesandtoincreaseavailability.DataStorage:1.Billionsofobjects2.Eachobjectissmall3.Thereisnorelationshipbetweenobjects4.Readsaremorethanwrite.5.3TBsofURLsand36GBofhash.MySQL:1.Widelyused2.Amaturetechnology3.Cleanscalingparadigms(master/slave,master/master)4.UsedbyFacebook,google,twitteretc.5.Indexlookupisveryfast.Mappings:<Hash,URL>1.UseonlyMySQLtablewithtwofields.2.Createauniqueindexonthehashwewanttoholditinmemorytospeeduplookups.3.VerticalscalingofMySQLforawhile4.Partitionofdataintomanypartitions5.Master-slave(readfromslaveandwritetomaster.)6.Eventually,partitionthedatabytakingthefirstcharacterofthehashmodthenumberofpartitions.

Page 549:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

StockQueryServerImplement a stockquery service that canprovide an interface toget stockprice information likeopenprice,closeprice,highestprice, lowestpriceetc.Youshouldprovideaninterfacethatwillbeusedtoenterthesedataandinterfacetoreadthisdata.

UseCaseTherewillbetwointerfacestothissystem.1)Firstinterfacetoadddailystockpriceinformationtothesystem.2)Secondinterfacetoreadstockpriceinformationgivingthedateandstockidasinput.

ConstraintsLetussupposethesystemwillbeusedbythousandsofusers.Foreachstock,therewillbeonlyonewriteoperationperday.However,foreverystocktherewillbemultiplereadoperationsperday.Therefore,theapplicationismorereadheavythenwriteheavy.Thesolutionshouldbeflexibleenoughsothatifnewdatafieldsneedtobeaddedtothestocktheycaneasilybeaddedtothesystem.Thesolutionprovidedshouldbesecure.

BasicDesignWecanuseadatabaselikeSQLtostorestockdata.Clientcanaccessthedatabaseusingthewebserverinterface.Belowdiagramwillshowthebasicarchitecture.

Intheabovearchitecture,theusercanaccessthedatabaseusingwebservice.Anynumberofflexibilitycanbeprovidedfortheuse.Forexample,whatisthemaxpriceofsomestockin6monthsetc.?Atthesametime,theuserdoesnothaveaccesstothedatatheyshouldnothave.Wecanprovidedifferentaccessofreadandwritedependingonthenormalusersoradministrator.Well-definedrollingback,backingupdataandsecurityfeaturesareprovidedbytheSQLdatabase.Theabovearchitectureiseasilyextendabletousewithawebsiteorsomemobileapplication.

ScalabilitySincewehave1000’sofusers,thenhavingasinglewebserverandasingledatabaseisnotextendable.We need to distribute data among N number of Databases, which sit behind some load balancer. In

Page 550:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

addition,multipleNnumberofwebserverwhichwillsitbehindsomeloadbalancer.Eachoftheloadbalancersneedstobeprovidedwithsomeredundancy,astheywillbeasinglepointoffailure.Finally,the solutionwill look likebelowdiagram. (Fordetails, see scalability theoryexplainedearlier in thischapter)

Page 551:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DesignabasicsearchengineDatabaseYouaregivenmillionsofURLs;howwouldyoucreateyourdatabase.So thatgivenaquery stringofwords,howtofindtheURLs,whichcontainallthewordsofthequerystring.Thewordscancomeinanyorder.

UseCase1)WearegivenalistofmillionsofURLs.2) The user of the systemwill provide query string. In addition, we need to return the URLs, which

containallthewordsofthequerystring.3)Itissomekindofsearchenginesowecanpre-processthedataandmakeourdatabase.

RequirementAnalysisIntherequirementstep,youneedtofindouthowmanyusersaregoingtousethissearchengine.Inourcase,letussupposetherearenotmanyuserswhoaregoingtouseoursystemsothesourmainconcernisadatabase.MaybewehaveNnumberofmachinesthatcanbeusedtofastourdatapre-processing.

BasicDesignInthisstep,wewillmakethebasicdesignsoletusmakeaworkingsystemwithjustafewURLs.HowwouldyoufindtherequiredURLfromthegivenURLs,whichcontainsallthewordsoftheinputquerystring?WecanmakeaHash-Tableinwhichwordsarethekeysanddocumentidsarevalues.“Hello”->url1,url2,url3“World”->url2,url4,url5Tosearch thedocument,whichcontains“helloworld”,wecanfind the intersectionof the twolists. Inaddition,url2istheresult.

BottleneckIn this step,wewill look back to our original problem inwhich pre-processing ofmillions ofURLs.TheremaybeanumberofdifferentwordssoitmaynotbepossibletokeepthewholeHash-Tableonasinglemachine.Therefore,weneedtodividetheHash-Tableandkeepitonaseparatemachine.WeneedtoretrievetheURLsthatmatchagivenwordefficiently.Sothatwecanfindtheintersection.Pre-processingallthemillions,URLsbysinglemachinewillbeslow.Weneedtofindawaytoparallelprocesspre-processingstep.

ScalabilityLetuslookintotheproblemofkeepingtheHash-Tableindifferentdatabases.Onesolutionistodividethewordsalphabetically.Wecanmaketablescorrespondingtoeachword.Eachdatabasecontainstablesofwordsundersomerange.Forexample,DB1containsallthewords,whichstartwithalphabet“a”,andDB2containsallthewords,whichstartswiththealphabets“b”andsoon.Dataisstoredinthedatabase.

Page 552:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

When a database reaches itsmaximum capacity, the data is stored to nextmachine and a tree kind ofstructurecanbemade.Finding the listofURLscorresponding tosomeword iseasy,wecango to thecorresponding database and find the table and get all the data of that table. Finally, we can take theintersectionoftheresultofvariouswords.Inaddition,theresultwillbegivenasoutput.ProcessingofthemillionsofURLswithasinglemachineisslow.Therefore,wecandivideabunchofURLprocessingamonganNnumberofmachines,eachURLprocessingisindependentofeachotherandthefinalHash-TableoftheURLscanbefinallycombined.ThisapproachofprocessingindependentdataandfinallycombiningtheirresultisusedinMapReduce.MapReduce:AMapReduce divides the input dataset into independent chunks,which are processed inparallel.Thentheiroutputiscombinedtogettheresult.

Page 553:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DesignabasicsearchengineCachingGivenasearchenginedatabaseimplementationwhichsupportsQuerySearch()functionwhichwillreturnthe best list of URLs based on thewords of the query. This time you need to design theweb serverimplementationof this such that thereareNnumberof thewebservers that are responding to theuserqueries.Anywebservercanbepickedat random.QuerySearch() isaheavyoperationsoyouneed todesign,cachingforthissystemsothatdatabaseaccessisreduced.

UseCase1.TheuserofthesystemwillprovidequerystringandsystemwillrespondwiththeproperlistofURLs

correspondingtohisrequest.2.Giventhat,thedatabaseoperationsareveryheavyweneedtominimizethembycachingthequeriesat

thewebserver.3.Weneedtokeepthefrequentqueriesinthecacheandstalequeriesneedtoberemovedfromthecache.4.Weneedtohavesomeproperrefreshmechanismforeachquery.

BasicDesignLetuslustforgetaboutanNnumberofmachinesandassumethatQuerySearch()operationhappensonasinglemachine.Nowwewouldliketocachequeries.Eachquerywillconsistofsomestring.Inaddition,theresultofaqueryisalistofURLs.WeneedtohaveaquickcachelookupsothatwecangettheresultoftheQueryfromthecacheif it ispresentthere.Also,needtohavesomeproperrefreshmechanismforeachquery.TheHash-Tableismosteffectivetokeepthecache.Byusingahash,atablelookupisfast.However,ifthecacheisfilledhowyouwouldremovetheleastuseddatafromthecache.Alinkedlistcanbeusedtoremovetheolddata.Youcankeepadoublelinkedlisttomanagetheolddataremoval.Wheneveradataisaccessed,itcanbemovedtothefrontofthelinkedlistandtheremovalcanhappenfromtheendofthelinkedlist.Takingadvantageofboththesolutions,wecankeepthecacheinalinkedlistandadditsreferencetotheHash-Table.Now the last problem of how to remove the data upon the expiry of it. For example,most frequentlyaccessedqueryresultwillalwaysremaininthelinkedlisteventhoughthatresultischangedandifitisaccessedagainfromthedatabasethenitwillgivesomeupdatedresult.Forthis,weneedtohavesomeTTL(timetolive)associatedwitheachquerydependingupontheresultofURLswegetfromeachquery.Forexample,someweatherorcurrentnewsrelatedqueriesshouldhaveaTTLofdays.Ontheotherhand,somehistoricdatashouldhavealongTTL.TheTTLcanbederivedfromhowfrequentlytheURLsarechanginginthequeryresult.

BottleneckThereareNdifferentwebservers.Inaddition,anyparticularquerycanbeservedbyanyserver.

Page 554:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Dataaccessshouldbefast.

ScalabilityThevarioussolutionsthatwecanthinkaboutare:Approach1:Serverscanhavetheirowncache.IfsomequeryissenttoMachine1,itwillcatchitinitscachewhenthesamequeryissenttoitagainitwillreturnitfromitscache.However,ifsomequeryissenttoMachine1first, itwillcacheitandif thesamequeryissent toMachine2, itwillagaindoadatabaselookupandcache it to its own cache. This implementation is suboptimal as it is doingmore number of databaselookupsthanwhatisactuallyrequired.Approach2:Anotherapproachisthateachmachinestoresidenticalcache.Wheneversomedatabaseaccesshappenedthen thesamecache isupdatedbyall thewebservers.Thisapproachhasadrawback thatwheneveradataisupdatedincachesamecacheupdateisfiredtoalltheNwebservers.Anotherdisadvantageisthatallthecachestoresthesamedatasowearewastingpreciouscachespace.Approach3:Inthisapproach,wewilldivideourcachesuchthateachwebserverholdsadifferentpartofthecache.Whenaqueryreachtosomewebserveritknowswhichwebserveractuallyholdsthecacheforthisqueryoratleastknowsthatwhichserverissupposedtokeepacacheoftheparticularquery.Todothisweneedahash-basedapproach.Wefindtheserver,whichservesthequery,byjustfindingthehash(query)percentageN.Whenaqueryrequestcometosomewebserver,itwillfindthewebservercorrespondingtothisquerybyapplyingtheformula.ItwillasktheQuerySearch()functiontothatparticularserver.Thatserverwillinturnwillquerythedatabaseifrequiredorprovidetheresultfromitsowncache.Now, regarding thecacheexpirationandoldcacheremoval.Wearekeeping theTTLcorresponding toeach query so there can be a thread runningwhich looks for the expired data and remove it from thecache.Inaddition,combinationoflinkedlistandHash-Tableisusedtokeepthecachetogetridoflessaccesseddatawhenthecacheisalmostfull.As a further improvement,we can think of some sort ofGeo location awarewebserver selection andcachepolicysothatqueryrelatedtoIndiaismoresupposedtobedoneinIndiaandqueryrelatedtochinaissupposedtocomemorefromchina.

Page 555:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DuplicateintegerinmillionsofdocumentsGivenmillionsofdocumentswithalldistinctnumbers,findthenumber,whichoccursmultipletimes.

BasicDesignConsidertherearejustafewnumbers,andwewanttofindtheduplicatenumbers.Thefirstapproach is tofindkeepasorted listof thenumbersandsee if thenextreadnumbermatcheswithsomenumberinthelist.Anotherbetter approach is to findahashvaluecorresponding tonumber andadd that thenumber to aHash-Table.

ConstraintMillionsofdocumentsandthereisnorangeofnumbersowecannotkeepeverythinginmemory.

ScalabilityWecanfindthehashvalueforalltheintegersandthenaddthatintegertoitscorrespondinghashvaluefileordatabase.Ifthereissomeduplicate,thentheywillfallinthesamefile.Inthefirstpass,variousfilesarecreatedandintegersaredistributed.In thesecondpassall, thedataof the individual filescanbe loaded intomemoryandsorted to find ifthereissomeduplicatevalue.Wecanusethesametechniqueexplainedabovetoprocessthevariousdocumentsofintegerinparallelbydifferentmachinesandthencombinetheiroutputtogetourresultfaster.

Page 556:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Zomato

UseCase1.Givenalocation,thelistofhotelsinthatlocalityneedstobedisplayed.2.Givenahotelnamethathotel’srating,review,andmenuneedtobedisplayed3.Thereshouldbesomeoptiontofindifadeliveryoptionisthereinthehotel.4.Thereshouldbesomeoptiontoselectahotelonveg/non-vegcategory.5.Thereshouldbesomeoptiontoselecthotels,whichservealcohol.6.Theusershouldbeabletoaddreviews,addpersonalratingstothehotels.7.Theuserhassomeaccountorcanaccessasguest.8.Users/Adminshouldbeabletoaddnewhotelstothesystem.

Constraints1.Anumberofqueriespersecondsuppose100queriespersecond.2.Therearemorereadsthanwrites.3.90%ofthetimethereisreadoperationandonly10%ofthetimethereisawriteoperation.4.100*60*60*24=8,640,000

BasicDesign

ThescalabilitywillbesameasthatoftheexamplesexplainedaboveinthecaseofbasicFacebook.Sameconceptofredundancy,loadbalancing,scalabilityetc.

AbstractDesignEachhotelhassomehotelidassociatedwithit.1.DataofthehotelcanbeName,Address,Rating,ReviewList,Veg-Nonveg,andAlcoholetc.2.Theregionisafieldintheaddress.3.Search:Whenauserdoesaregionbased,queryalltheentriesofthehotelsinthatregionneedtobe

displayedtotheuser.4.Search:Usershouldbeabletosearchspecifichotel.5.AddReview/Rating:Whenusersassessahotel,thenheshouldbeabletoaddreviewsandratingfor

thehotel.6.ObviouslytheimagesarestoredinCDN

Page 557:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ApplicationServicelayer1.Startwithfewermachines2.Allloadbalancer+aclusterofmachinesovertime.3.Trafficspikehandling.4.Highavailability.DataStorageLayer:1.Thousandsofhotels.2.Therearenorelationshipsbetweentheobject.3.Readsaremorethanwriting.4.RelationaldatabaseoptionisMySQL5.Widelyused.6.Clearscalingparadigms.(Master-Masterreplication,Master-Slavereplication)7.Indexlookupsareveryfast.Oneoptimizationthatwecanassignanidtohotelstheidcanbederivedfromthelocalitysothatitwouldbeeasytofindhotelsinthatlocality.

Page 558:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

YouTube

Scenarios1.Usershavesomeprofileaccordingtowhichcontentisshown.2.ContentthumbnailsareshownwhentheuseropenstheYouTubewebpage.3.Whentheuserclicksonsomethumbnail,thenthatvideoisplayedonflashplayer.

Constraints1.Millionsofusersaregoingtousethisservice.2.200millionvideorequestsservedperday.3.Morereadsthanwrites.

Design1.YouTubeissupposedtoservehugenumberofvideosforwhichithasvideoservingclusters.Asingle

videocanbeservedfrommultipleserversinclustersandfrommultipleclusterstherebydistributingthediskreadwhichincreasestheperformanceofthesystem.

2. Themost popular videos are served fromCDN.CDN ismore close to the user,which reduce theresponsetime.Thisalsoreducetheloadtothevideoservingclusters.

3.Therestofthemetadataofthevideoisservedfromotherservers,astheuserisnotmuchinterestedinthemetadata.

4.Therestoftheapplicationwillbesame,asitwillhaveanapplicationserver,databaseservers,loadbalancer,cachingetc.

5.There ismorereadthanwriteso themasterserver topologywillbeused.Therefore, therecanbeasinglemasterforwritingandmultipleslavesforreading.

6.Master data is replicated to slaves. Since slaves are same asmaster then themaster is down, thenslavescanbepromotedtomakeasmaster.

7.Pagetobedisplayedtotheuserdependsonhissubscribedpages,Historyetc.8.InformationcanbecachedintheMemcachedimplementednearthedatabaseloadbalancer.

Page 559:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 560:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DesignIRCTC

Scenario

1.Theusershouldbeabletoquerytrainsbetweentwostations.2.Thequeryshouldbebasedonthedate,quota,fromandtothestation.3.Theusershouldbeabletoseetheavailabilityinthetrainlistretrievedfromtheabovequery.4.Theusershouldbeabletobookticketsfortheavailableseats.

Constraints1. Therewill be a huge number of people requesting the service. Let us suppose 0.01 percent of the

populationusetheservicedailyonce.2.Geo-Redundancyshouldbeprovided.3.Morereadquery/requestthenwritesrequests.

Design1.Thebasicarchitecturefromthescalabilitytheorytopiccanbeusedheretoo.2.Thereshouldbeahugenumberofservers,whichareservingtheusers.3.Thereshouldbemultipleserversatmultiplegeo locations toprovidegeo-redundancy.Thedatabase

shouldbereplicatedatthesemultiplegeolocations.Theremaybemultipleserversinoneparticularzonetoo.

4.Thereisahugenumberofreadquery,theusergenerallydoesalargenumberofquerytofindtheseathewantstobook.Therewillbemorereadsthenwritesomaster-slave.

5.Queriescanbecached;littleolddataisok.6.Allthesearchwillbeservedbyslaveservers.7.Whenwebookaticketthentransactiongoesdirectlytothemasterserver.Locksontrainnumbercanbe

takentopreventraceconditions.Oncealockisacquiredthenonlyyoucanbookaticket.Somecountscanbeusedtoavoidunnecessarylockingandsomecountercanbeusedforthis.

8.Eachstationhasaquotaintrainandseatsareallocatedfromthatquota.9.Eachphysicaltrainwillhavetwotrainidsonewhentransgofromsourcetodestinationstationandone

whenitcomesback.Sointhesystem,therewillbetwotrainids.Keepingthesetwoseparateidswillmakethequeryeasiertoimplement.

10.When final charting is done then each seat is swapped for the empty slots andwe try to find therequestfromsourcestationwhosedestinationisalsointhatslot.Thefirstfitisallottedthatseat.

11.Aloadbalancerisusedtodistributetraffic.12.Theremaybemultiplebookingserverswhichaskforabookingtoken to themasterserver.Master

serverallocateatokenforthatserverandreserveitforsometime.Whenalltheuserinformationisfilledandpaymentisdonethenonlyitallocatesrealseatdependinguponuserpreference.

13.Slaveserverwillhandleuserrequesttilltheend.Finalbookingrequestwiththeuserpaymentandhiscompleteinformationwillgotothemasterserverandthecorrespondingticketwillbebooked.

Page 561:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

AlarmClockHowwouldyoudesignanalarmclock?

UseCaseAlarmclockshouldhaveallthefunctionsofclock.Shouldbeabletoshowtime.TheUsercansetthealarmtimeTheUsercanresetthealarm.TheUsercansetthealarm.

ConstrainsTheGranularityofalarmcanbe15min.

TestCaseSetthealarmatsometime6:00AMandsetit.TheAlarmshouldworkat6:00AMStopthealarm,thenalarmshouldstopringing.

DesignTherecanbeaclockclass,whichmanagestimeandshoetimetothescreen.IthasfunctionsgetTime()andsetTime()Alarm Clock extends Clock, and have some more function like startAlarm(), stopAlarm(),setAlarmTime(),ring()

ImplementationAtimerentrywillrunforgranularityof15min.Alternatively,onemindependsoncustomerrequirement.Itwillcheckifcurrenttimeisequaltoalarmtime.Iftrueandthealarmisonthenring.IfstartAlarmiscalled,itwillsetalarmonIfstopalarmiscalled,itwillsetalarmoff.

Page 562:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 563:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

DesignforElevatorofabuilding

ScenariosAtypicallifthasbuttons(Elevatorbuttons)insidethecabintolettheuserwhogotthelifttoselecthis/herdesired floor.Similarly,each floorhasbuttons (Floorbuttons) tocall the lift togo floorsaboveandafloorbelowrespectively.Thebuttonsilluminateindicatingtherequestisaccepted.Inaddition,thebuttonstopsilluminatingwhentheliftreachestherequestedfloor.Usecases:User•Pressesthefloorbuttontocallthelift•PressestheelevatorbuttontomovetothedesiredfloorFloorButton&ElevatorButton•Illuminateswhenpressedbyuser•PlacesanelevatorrequestwhenpressedElevator•Movesup/downasperinstruction•Opens/closesthedoor

DesignEachbuttonpressresultsinanelevatorrequestwhichhastobeserved.Eachoftheserequestsistrackedatacentralizedplace.ElevatorRequests,theclassthatstores,elevatorrequestscanusedifferentalgotoscheduletheelevatorrequests.Theelevatorismanagedbyacontrollerclass,whichwecallElevatorController.Elevatorcontrollerclassprovideinstructionstotheelevator.Elevatorcontrollerreadsthenextelevatorrequesttobeprocessedandserved.

Page 564:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Thebuttonisanabstractclassdefiningcommonbehaviourlikeilluminate,doNotIlluminate.FloorButton,ElevatorButtonextendsButtontypeanddefineplaceRequest()methodwhichisinvokedwhenabuttonispressed.Whenafloorbuttonorelevatorbuttonispressesarequestsisaddedtoacommonqueue.ElevatorControllerreadsthenextrequestandinstructnextactiontotheelevator.Howcanweextendthistomultipleelevators?Inthesingleelevatorscenario,thereisasingleelevatorandanelevatorcontrollerandacommonserverwhere the floor requests and the elevator button request are stored.Which are processed as per theschedulingalgorithm.Toextend this tomultiple elevator scenarios therewill still be single elevator controller.Floorbasedrequests can be served by any elevator whereas elevator button requests will be served only by theelevatortowhomthebuttonbelongs.FloorButton's placeRequest() adds a request to the common queue,which is accessed by the elevatorcontroller thereby assigning the request to one of the elevators. ElevatorButton's placeRequest adds arequesttotheelevatordirectlyasitissupposedtoserveit.Elevatorcontrollerwillberunningvariousalgorithmslikeshortestseeketc.todecidewhichliftissupposedtohandlewhichrequest.

Page 565:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ValetparkingsystemDesignavaletparkingsystem.

UseCaseTherequirementsofthevaletparkingsystemshouldbe:1.GivenaParkinglothavingafixednumberofslots2.Whereacarcanentertheslotifthereisafreeslotandthenitwillbegiventhedirectionofthefreeslot.3.Whenexitingthecarhastopaythefeesforthedurationofthetimeitusesparking.

Constraints1.Parkingslotscomeinmultiplesizes-small,midandlarge2.Threetypesofvehicles,small,mid,large3.Asmallvehiclecanparkinasmall,medium,orlargespot4.Amediumvehiclecanparkinamediumorlargespot5.Alargevehiclecanparkonlyinalargespot

Design&ImplementationTheparkinglotwillhavethefollowinginterfaceparkingLot

Map<int,Space>unreservedMap;Map<int,Space>reservedMap;

reserveSpace(Space)//Itwillfindifthereisspaceintheunreservedmap//Ifyes,thenwewillpickthatelementand//putintothereservedmapwiththecurrenttimevalue.

unreserveSpace(Space)//Itwillfindtheentryinreservemap.Ifvaluefoundthen//wewillpickthatElementandputintotheunreservedmap.//Andreturnthechargeunitswiththecurrenttimevalue.

Page 566:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

OOdesignforaMcDonaldsshopLetusstartwiththedescriptionofhowtheMcDonaldsshopworks.1.InaMcDonaldsshop,theCustomerselectstheburgeranddirectlyplacestheorderwiththecashier.2. In a McDonalds shop, the Customer waits for the order ready notification. Customer upon being

notifiedthattheorderisreadycollectstheburgerhimself.Therearethreedifferentactorsinourscenarioandbelowisthelistofactionstheydo.Customer1.Paysthecashtothecashierandplaceshisorder,getatokennumberandreceipt2.Waitsfortheintimationthatorderforhistokenisready3.Uponintimation/notification,hecollectstheburgerandenjoyshisdrinkCashier1.Takesanorderandpaymentfromthecustomer2.Uponpayment,createsanorderandplacesitintotheorderqueue3.ProvidetokenandreceipttothecustomerCook1.Getsthenextorderfromthequeue2.Preparestheburger3.Placestheburgerinthecompletedorderqueue4.Placesanotificationthatorderfortokenisready

Page 567:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ObjectorienteddesignforaRestaurantLetusdescribehowtherestaurantworks.1.Inarestaurant,thewaitertakesorderfromthecustomer.2.Thewaiterwaitsfortheordertobereadyandoncereadyservesthedishestothecustomer.ThesearethedifferentactorsinthemodelandIhavelistedthedifferentactionsagainsteachactorCustomer1.Selectsthedishfromthemenuandcalluponawaiter2.Placestheorder3.Enjoyshismealoncethedishisservedonhisplate4.Askforthebill5.PaysfortheservicesWaiter1.Respondstothecustomerscallonthetablesheiswaiting2.Takesthecustomer'sorder3.Placestheorderinthependingorderqueue4.Waitsfortheorderreadynotifications5.Oncenotificationisreceived,collectsthedishandservesthedishtothecorrespondingcustomer6.Receivesthebillrequestfromcustomer7.AskstheCashiertopreparethebill8.GivesthebilltothecustomerandacceptsthepaymentCashier1.Acceptsthepreparedbillrequestfromthewaiterforthegivenorderdetails2.Preparesthebillsandhandsitovertothewaiter3.AcceptsthecashfromthewaitertowardstheorderCook1.Getsthenextorderfromthependingorderqueue2.Preparesthedishandpushtheordertofinishedorderqueue3.Sendsanotificationthattheorderisready

Page 568:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ClassdiagramfortheRestaurant.

Page 569:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

ObjectorienteddesignforaLibrarysystemA library has a set of books,which the users can borrow for a certain period and return.Usersmaychoosetorenewthereturndateiftheyfeeltheyneedmoretimetoreadthebook.

Thetypicaluseractionswiththisonlinelibrarywouldbe·Signin/register·Searchbooks·Borrowbooks·Renewbooks·Returnbooks·Viewhisprofile

Theonline librarymustkeep trackof thedifferentbooks in the librarycurrentlyavailable forusers toborrowandthebooksalreadyborrowedbyusers.Putitsimplytheinventoryshouldbemanaged.Thevariouscomponentsofthesystem:1.User2.Librarian3.Library4.Book5.Transection6.EventManagerThebelowclassdiagram,whichdepictshowthesecomponentsinter-operates.

TheUsereitherinteractswiththeLibrarian,theuserrequest,returnorrenewsabook.TheLibrarianwill

Page 570:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

searchforthebookifthebookisavailableintheLibrarythenissueittotheuser.ATransectionwillbecreated and added to theEventManager.EventManagerwill support add transaction and send returnrequestinterface.Oncethebookisoverduethentheeventmanagerwillsendanindicationtothestudentthatthebookneedstobereturned.WhenthebookisrenewedthenthelibrarystateisnotchangedbuttheTransectiondetailisrenewedattheEventManager.

Page 571:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Suggestashortestpath

UseCaseTheuserhadsomecoordinatebysearchingthecoordinatefromthename.Showthewholemapconsideringthecoordinateasitscentre.Suggesttheshortestpathbetweentwopoints.

ConstraintsAllpathsarepositiveincost.For simplicity, I am considering all paths are for vehicle only, no pedestrian (pedestrian canwalk ineitherdirectioneveninone-wayroad.)

DesignThewholecitymapisstoredasagraphingoogle.Weneedtofindthemapbylookingintotheobjects,whichareinthedistanceshownbythebrowser.Thesamepathisstoredasdirectedgraph.Inaddition,thegraphthatneedstoberendereddependsonthezoomlevel.Thepreferredalgorithmisa*forthisapplicationtogettheshortestpath.Weight=h(x,y)+g(x,y)

Page 572:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

Exercise1.DesignasystemtoimplementsocialnetworkinglikeFacebook,withmillionsofusers.Howwouldyou

findtheconnectionbetweentwopeople?2.Autocompleteinwww.booking.com.Designautocompletefeatureforwww.booking.com.3. Instagram, Instagram is anonlinemobile-basedphoto sharing,video sharing service,whichenables

userstotakepictures,andvideouploadthemtotheserverandsharethemonsocialnetworkingsiteslikeFacebookorTwitter.Note:-CDNisusedtostoreactiveimages.

4.MonolithicWebsite,assumeyouhaveamonolithicwebsiteandyouareaskedtoarchitectthewebsite

Hint:-Discusswholescalabilitytheorysectionhere.5. TripAdvisor: URL's are parsed; content is collected from various services, and then applied to a

template.6.Cinchcast:Liveaudiostreamingforbusinesstodoconferences.7.BlogTalkRadio:Audiosocialnetwork8.Clientbasedrecommendationfeature:Howwouldyoudesignaclientbasedrecommendationfeature

(basedoncustomerhistory)on theproductdetailpage?DesignCustomerswhovieweditemAalsoviewitemBanditemCinanonlineshoppingportal.

9.Car rentingsystem:Designacar rentingsystem, includingreservingacar,checking inandchecking

out.Considerallthecases:reserveacar,thencheckoutsuccessfully;reserveacar,butthecarissoldoutbeforeyoucheckout.TestCases:a)Trytoreserveacarformorethanonepersonb)Trytoreserveacarthatissoldoutc)Verify thecheckoutprocess.After checkingout aparticular, you shouldbeable to reserve it for

anothercustomer.d)Trytoreservethesamecarfordifferentcustomersindifferentdates

10.Onlinecabbookingsystem(likeUber)

AdminModulea)Adminshouldbeabletoaddnewdriver/taxidetails.b) Should be able to calculate the amount that needs to be paid to the drivers.Monthly,weekly or

daily.

UserModulea)Shouldbeabletochoosefromandtolocation.b)AvailableTaxiestype,alongwithfaredetails.

Page 573:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

c)SelectaTaxityped)Bookthetaxi.e)Aconfirmationmessageforthebooking.

DriverModulea)AdrivershouldbeabletoregisterasadrivertoUber.b)Whenajobisdisplayedtothedriver,heshouldbeabletoacceptthejob.c)Whenthedriverreachestothecustomerthenheshouldbeabletostartatrip.d)Whenthedriverhadtakenthecustomertothedesiredlocationthenheshouldstopthetrip.e)Thedrivershouldcollectthefarebasedontheamountdisplayedintheapp.f)Thedrivershouldbeabletogivecustomerfeedback.

Note:Justassume2minutesisequalto1KM.

11.Onlineteachingsystem

a)Inanonlineteachingsystem,therearennumberofteachersandeachoneteachesonlyonesubjecttoanynumberofstudents.

b)Astudentcanjointoanynumberofteacherstolearnthosesubjects.c)Eachstudentcangiveonepreferencethroughwhichhecangetupdatesaboutthesubjectorclass

timingsetc.d)ThosepreferencescanbethroughSMSorTwitter/FacebookorEmailetc.e)Designabovesystemanddrawthediagramforabove.

12.CustomerOrderBookingSystem

AdminModulea)Shouldbeabletoadd/edit/deleteitem,alongwithquantity,price,andunit.b)Shouldbeabletoseeallorders.

CustomerModulea)Shouldbeabletoenterhis/herdetailsforshipping,alongwillbasicinformationlikename,email,

contactetc.b)Canchooseitem,quantityc)Automaticallypayablepriceshouldbegeneratedasperselecteditemandquantity.d)Shouldbeabletoconfirmtheorder.e) After confirmation can see order confirmation report along with order number, which will be,

systemgenerated.13.OnlineMovieBookingSystem

AdminModulea)Shouldbeable toenterallmovies,whichhavebeenreleased,andabout torelease innextweek

withallpossibledetailsliketheatrelocation,price,showtimingsandseats.b)Shouldbeabletodeletemovies,whicharenolongerinthetheatre.c)Canseeanumberofbookedticketsandremainingticketsforsingletheatreorforalltheatre.

UserModule

Page 574:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

a)User should be able to check all ongoingmovies in theatre alongwith locations, availability ofseats,price,andshowtimings

b)Theusershouldbeabletocheckallupcomingmoviesfornextweektoo.c)Allmoviesthosearerunningontheatreshouldbeavailableforbooking(oneticketormorethanone

ticketcanbebooked).d)Afterbookingusershouldseetheconfirmationmessageofbooking. 

14.Design an onlineAuction system (similar to e-bay). Functionalities include enlisting a product for

auctionbybidowner,placingthebidforaproductbybidders,Bidwinnerselection,Notificationofbidwinneretc.).

Page 575:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would
Page 576:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

APPENDIX

Page 577:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would

AppendixAAlgorithms TimeComplexityBinarySearchinasortedarrayofNelements O(logN)ReversingastringofNelements O(N)LinearsearchinanunsortedarrayofNelements O(N)ComparetwostringswithlengthsL1andL2 O(min(L1,L2))ComputingtheNthFibonaccinumberusingdynamicprogramming O(N)CheckingifastringofNcharactersisapalindrome O(N)FindingastringinanotherstringusingtheAho-Corasickalgorithm O(N)SortinganarrayofNelementsusingMerge-Sort/Quick-Sort/Heap-Sort O(N∗logN)SortinganarrayofNelementsusingBubble-Sort O(N!)Twonestedloopsfrom1toN O(N!)TheKnapsackproblemofNelementswithcapacityM O(N∗N)Findingastringinanotherstring–thenaiveapproach O(L1∗L2)Threenestedloopsfrom1toN O(N3)Twenty-eightnestedloops…yougettheidea O(N28)Stack Addingavaluetothetopofastack O(1)Removingthevalueatthetopofastack O(1)Reversingastack O(N)Queue Addingavaluetoendofthequeue O(1)Removingthevalueatthefrontofthequeue O(1)Reversingaqueue O()Heap Addingavaluetotheheap O(logN)Removingthevalueatthetopoftheheap O(logN)Hash Addingavaluetoahash O(1)Checkingifavalueisinahash O(1)

Page 578:  · ACKNOWLEDGEMENT The author is very grateful to GOD ALMIGHTY for his grace and blessing. Deepest gratitude for the help and support of my brother Dr. Sumant Jain. This book would