HackingaGoogleInterview Handout2 CourseDescription Instructors:BillJacobsandCurtisFonger Time:January12 15,5:00 6:30PMin32 124 Website:http://courses.csail.mit.edu/iap/interview ClassicQuestion#4:Reversingthewordsinastring Writeafunctiontoreversetheorderofwordsinastringinplace. Answer:Reversethestringbyswappingthefirstcharacterwiththelastcharacter, thesecondcharacterwiththesecond to lastcharacter,andsoon.then,gothrough thestringlookingforspaces,sothatyoufindwhereeachofthewordsis.reverse eachofthewordsyouencounterbyagainswappingthefirstcharacterwiththelast character,thesecondcharacterwiththesecond to lastcharacter,andsoon. Sorting Often,aspartofasolutiontoaquestion,youwillneedtosortacollectionof elements.themostimportantthingtorememberaboutsortingisthatittakeso(n logn)time.(thatis,thefastestsortingalgorithmforarbitrarydatatakeso(nlogn) time.) MergeSort: Mergesortisarecursivewaytosortanarray.First,youdividethearrayinhalfand recursivelysorteachhalfofthearray.then,youcombinethetwohalvesintoa sortedarray.soamergesortfunctionwouldlooksomethinglikethis: int[] mergesort(int[] array) { if (array.length <= 1) return array; int middle = array.length / 2; int firsthalf = mergesort(array[0..middle - 1]); int secondhalf = mergesort( array[middle..array.length - 1]); return merge(firsthalf, secondhalf); Thealgorithmreliesonthefactthatonecanquicklycombinetwosortedarraysinto asinglesortedarray.onecandosobykeepingtwopointersintothetwosorted
arrays.onerepeatedlyaddsthesmallerofthetwonumberspointedtotothenew arrayandadvancesthepointer. Quicksort: Quicksortisanothersortingalgorithm.IttakesO(n^2)timeintheworstcaseand O(nlogn)expectedtime. Tosortanarrayusingquicksort,onefirstselectsarandomelementofthearrayto bethe"pivot".onethendividesthearrayintotwogroups:agroupofelementsthat arelessthanthepivotandagroupofelementsthataregreaterthanthepivot.after this,therewillbeanarrayconsistingofelementslessthanthepivot,followedbythe pivot,followedbyelementsgreaterthanthepivot.then,onerecursivelysortsthe portionofthearraybeforethepivotandtheportionofthearrayafterthepivot.a quicksortfunctionwouldlooklikethis: void quicksort(int[] array, int startindex, int endindex) { if (startindex >= endindex) { // Base case (array segment has 1 or 0 elements else { int pivotindex = partition(array, startindex, endindex); quicksort(array, startindex, pivotindex - 1); quicksort(array, pivotindex + 1, endindex); Quicksortistypicallyveryfastinpractice,butrememberthatithasO(n^2)worstcaserunningtime,sobesuretomentionanothersortingalgorithm,suchasmerge sort,ifyouneedguaranteedo(nlogn)runningtime. OrderStatistics: Sometimes,aninterviewerwillaskyoutodescribeanalgorithmtoidentifythekth smallestelementinanarrayofnelements.todothis,youselectarandompivot andpartitionthearrayasyouwouldinthequicksortalgorithm.then,basedonthe indexofthepivotelement,youknowwhichhalfofthearraythedesiredelementlies in.forexample,sayk=15andn=30,andafteryouselectyourpivotandpartition thearray,thefirsthalfhas10elements(thehalfbeforethepivot).youknowthat thedesiredelementisthe4thsmallestelementinthelargerhalf.toidentifythe element,youpartitionthesecondhalfofthearrayandcontinuerecursively.the reasonthatthisisnoto(nlogn)isthattherecursivepartitioncallisonlyonone halfofthearray,sotheexpectedrunningtimeisn+(n/2)+(n/4)+(n/8)+...= O(n).
Notethatfindingthemedianofanarrayisaspecialcaseofthiswherek=n/2. Thisisaveryimportantpoint,asaninterviewerwilloftenaskyoutofindawayto getthemedianofanarrayofnumbers. Question:NearestNeighbor Sayyouhaveanarraycontaininginformationregardingnpeople.Eachpersonis describedusingastring(theirname)andanumber(theirpositionalonganumber line).eachpersonhasthreefriends,whicharethethreepeoplewhosenumberis nearesttheirown.describeanalgorithmtoidentifyeachperson'sthreefriends. Goodanswer:Sortthearrayinascendingorderofthepeople'snumber.Foreach person,checkthethreepeopleimmediatelybeforeandafterthem.theirthree friendswillbeamongthesesixpeople.thisalgorithmtakeso(nlogn)time,since sortingthepeopletakesthatmuchtime. LinkedLists Alinkedlistisabasicdatastructure.Eachnodeinalinkedlistcontainsanelement andapointertothenextnodeinthelinkedlist.thelastnodehasa"null"pointerto indicatethatthereisnonextnode.alistmayalsobedoublylinked,inwhichcase eachnodealsohasapointertothepreviousnode.ittakesconstant(o(1))timeto addanodetoorremoveanodefromalinkedlist(ifyoualreadyhaveapointerto thatnode).ittakeso(n)timetolookupanelementinalinkedlistifyoudon't alreadyhaveapointertothatnode. ClassicQuestion#5:CycleinaLinkedList Howcanonedeterminewhetherasinglylinkedlisthasacycle? Goodanswer:Keeptrackoftwopointersinthelinkedlist,andstartthematthe beginningofthelinkedlist.ateachiterationofthealgorithm,advancethefirst pointerbyonenodeandthesecondpointerbytwonodes.ifthetwopointersare everthesame(otherthanatthebeginningofthealgorithm),thenthereisacycle.if apointereverreachestheendofthelinkedlistbeforethepointersarethesame, thenthereisnocycle.actually,thepointersneednotmoveoneandtwonodesata time;itisonlynecessarythatthepointersmoveatdifferentrates.thistakeso(n) time.thisisatrickyanswerthatinterviewersreallylikeforsomereason. Okayanswer:Foreverynodeyouencounterwhilegoingthroughthelistonebyone, putapointertothatnodeintoao(1) lookuptimedatastructure,suchasahashset. Then,whenyouencounteranewnode,seeifapointertothatnodealreadyexistsin yourhashset.thisshouldtakeo(n)time,butalsotakeso(n)space.
Okayanswer:Gothroughtheelementsofthelist."Mark"eachnodethatyoureach. Ifyoureachamarkednodebeforereachingtheend,thelisthasacycle;otherwise,it doesnot.thisalsotakeso(n)time. Notethatthisquestionistechnicallyill posed.anordinarylinkedlistwillhaveno cycles.whattheyactuallymeanisforyoutodeterminewhetheryoucanreacha cyclefromanodeinagraphconsistingofnodesthathaveatmostoneoutgoing edge. StacksandQueues Aninterviewerwillprobablyexpectyoutoknowwhatqueuesandstacksare. Queuesareabstractdatatypes.Aqueueisjustlikealineofpeopleatanamusement park.aqueuetypicallyhastwooperations:enqueueanddequeue.enqueueingan elementaddsittothequeue.dequeueinganelementremovesandreturnsthe elementthatwasaddedleastrecently.aqueueissaidtobefifo(first in,first out). Astackisanotherabstractdatatypewithtwocommonoperations:pushandpop. Pushinganelementaddsittothestack.Poppinganelementremovesandreturns theelementthatwasaddedmostrecently.astackissaidtobelifo(last in,firstout).astackoperateslikeastackofcafeteriatrays. HashTables Ahashtableisusedtoassociatekeyswithvalues,sothateachkeyisassociatedwith oneorzerovalues.eachkeyshouldbeabletocomputea"hash"function,which takessomeorallofitsinformationanddigestsitintoasingleinteger.thehash tableconsistsofanarrayofhashbuckets.toaddakey valuepairtoahashtable, onecomputesthekey'shashcodeandusesittodecidethehashbucketinwhichthe mappingbelongs.forexample,ifthehashvalueis53andthereare8hashbuckets, onemightusethemodfunctiontodecidetoputthemappinginbucket53mod8, whichisbucket5.tolookupthevalueforagivenkey,onecomputesthebucketin whichthekeywouldresideandcheckswhetherthekeyisthere;ifso,onecan returnthevaluestoredinthatbucket.toremovethemappingforagivenkey,one likewiselocatesthekey'smappingandremovesitfromtheappropriatebucket. Notethatthehashfunctionisgenerallydecidedoninadvance. Aproblemariseswhentwokeyshashtothesamebucket.Thiseventiscalleda "collision".thereareseveralwaystodealwiththis.onewayistostorealinkedlist ofkey valuepairsforeachbucket. Insertion,removal,andlookuptakeexpectedO(1)time,providedthatthehash functionissufficiently"random".intheworst case,eachkeyhashestothesame bucket,soeachoperationtakeso(n)time.inpractice,itiscommontoassume constanttime.
Hashtablescanoftenbeusedassmallercomponentsofanswerstoquestions.In ourexperience,someinterviewerslikehashtablesandsomedon't.thatis,some interviewerswillallowyoutoassumeconstanttime,whileotherswillnot.ifyou wanttouseahashtable,werecommendsubtlytryingtofigureoutwhichcategory yourinterviewerbelongsto.youmight,forexample,saysomethinglike,"well,i couldusedahashtable,butthatwouldhavebadworst caseperformance."the interviewermightthenindicatethathe'llallowyoutouseahashtable. ClassicQuestion#6:Datastructureforanagrams GivenanEnglishwordintheformofastring,howcanyouquicklyfindallvalid anagramsforthatstring(allvalidrearrangementsofthelettersthatformvalid Englishwords)?Youareallowedtopre computewhateveryouwanttoandstore whateveryouoptionallypre computeondisk. Answer:Wewanttouseahashtable!Ifyourinterviewerreallyhateshashtables (whichtheysometimesdoforsomereason),youcanuseatreeinstead.butlet's assumeyoucanuseahashtable.thenforthepre computingstep,gothrougheach wordinthedictionary,sortthelettersofthewordinalphabeticalorder(so "hacking"wouldbecome"acghikn")andaddthesortedlettersasakeyinthetable andtheoriginalwordasoneofthevaluesinalistofvaluesforthatkey.for example,theentryfor"opst"wouldbethelist["opts","post","stop","pots","tops", "spot"].then,wheneveryougetastring,yousimplysortthelettersofthestring andlookupthevalueinthehashtable.therunningtimeiso(nlogn)forsorting thestring(whichisrelativelysmall)andapproximatelyo(1)forthelookupinthe hashtable. Thereareseveralotherpossibleanswerstothisquestion,butwefeelthatthe answeraboveisconsideredanoptimalsolution. Question:FactorialZeros Withoutusingacalculator,howmanyzerosareattheendof"100!"?(that's 100*99*98*...*3*2*1) Answer:Whatyoudon'twanttodoisstartmultiplyingitallout!Thetrickis rememberingthatthenumberofzerosattheendofanumberisequaltothe numberoftimes"10"(or"2*5")appearswhenyoufactorthenumber.therefore thinkabouttheprimefactorizationof100!andhowmany2sand5sthereare. Thereareabunchmore2sthan5s,sothenumberof5sisalsothenumberof10sin thefactorization.thereisone5foreveryfactorof5inourfactorialmultiplication (1*2*...*5*...*10*...*15*...)andanextra5for25,50,75,and100.Thereforewehave 20+4=24zerosattheendof100!.