HackingaGoogleInterview Handout3 CourseDescription Instructors:BillJacobsandCurtisFonger Time:January12 15,5:00 6:30PMin32 124 Website:http://courses.csail.mit.edu/iap/interview Question:DeckShuffling Givenanarrayofdistinctintegers,giveanalgorithmtorandomlyreorderthe integerssothateachpossiblereorderingisequallylikely.inotherwords,givena deckofcards,howcanyoushufflethemsuchthatanypermutationofcardsis equallylikely? Goodanswer:Gothroughtheelementsinorder,swappingeachelementwitha randomelementinthearraythatdoesnotappearearlierthantheelement.this takeso(n)time. Notethatthereareseveralpossiblesolutionstothisproblem,aswellasseveral good lookinganswersthatareincorrect.forexample,aslightmodificationtothe abovealgorithmwherebyoneswitcheseachelementwithanyelementinthearray doesnotgiveeachreorderingwithequallyprobability.theanswergivenhereis,in ouropinion,thebestsolution.ifyouwanttoseeothersolutions,checkthe "Shuffling"pageonWikipedia. BinarySearchTrees Abinarysearchtreeisadatastructurethatkeepsitemsinsortedorder.Itconsists ofabinarytree.eachnodehasapointertotwochildren(oneorbothofwhichmay benull),anoptionalpointertoitsparent(whichmaybenull),andoneelementthat isbeingstoredinthetree(perhapsastringoraninteger).forabinarysearchtree tobevalid,eachnode'selementmustbegreaterthaneveryelementinitsleft subtreeandlessthaneveryelementinitsrightsubtree.forexample,abinarytree mightlooklikethis: 17 / \ 6 46 / \ \ 3 12 56 / / \ / 1 9 15 48
Tocheckwhetheranelementappearsinabinarysearchtree,oneneedonlyfollow theappropriatelinksfromparenttochild.forexample,ifwewanttosearchfor15 intheabovetree,westartattheroot,17.since15<17,wemovetotheleftchild,6. Since15>6,wemovetotherightchild,12.Since15>12,wemovetotheright childagain,15.nowwehavefoundthenumberwewerelookingfor,sowe'redone. Toaddanelementtoabinarysearchtree,webeginasifweweresearchingforthe element,followingtheappropriatelinksfromparenttochild.whenthedesired childisnull,weaddtheelementasanewchildnode.forexample,ifweweretoadd 14totheabovetree,wewouldgodownthetree.Oncewereached15,wewouldsee thatthenodehasnoleftchild,sowewouldadd14asaleftchild. Toremoveanelementfromabinarysearchtree,wefirstfindthenodecontaining thatelement.ifthenodehaszerochildren,wesimplyremoveit.ifithasonechild, wereplacethenodewithitschild.ifithastwochildren,weidentifythenextsmallerornext largerelementinthetree(itdoesn'tmatterwhich),usingan algorithmwhichwedonotdescribehereforthesakeofbrevity.wesettheelement storedinthenodetothisvalue.then,wesplicethenodethatcontainedthevalue fromthetree.thiswillberelativelyeasy,sincethenodewillhaveatmostonechild. Forexample,toremove6fromthetree,wefirstchangethenodetohavethevalue 3.Then,weremovethenodethatusedtohavethevalue3,andwemake1theleft childofthenodethatusedtohavethevalue6. Asmallmodificationtoabinarysearchtreeallowsittobeusedtoassociatekeys withvalues,asinahashtable.insteadofstoringasinglevalueineachnode,one couldstoreakey valuepairineachnode.thetreewouldbeorderedbasedonthe nodes'keys. Interviewerssometimesaskaboutbinarysearchtrees.Inaddition,binarysearch treesareoftenusefulasacomponentofananswertointerviewquestions.the importantthingtorememberisthatinsertion,removal,andlookuptakeo(logn) time(wherenisthenumberofelementsinthetree),sincetheheightofawellbalancedbinarysearchtreeiso(logn).althoughintheworstcase,abinarysearch treemighthaveaheightofo(n),thereare"self balancing"binarysearchtreesthat periodicallyreorganizeabsttoensureaheightofo(logn).manyself balancing BST'sguaranteethatoperationstakeO(logn)time.Ifyouwanttolearnmoreabout particulartypesbinarysearchtrees,suchasred blacktrees,werecommendlooking themup. Question:PathBetweenNodesinaBinaryTree Designanalgorithmtofindapathfromonenodeinabinarytreetoanother.
GoodAnswer:Therewillalwaysbeexactlyonepath:fromthestartingnodetothe lowestcommonancestorofthenodestothesecondnode.thegoalistoidentifythe lowestcommonancestor. Foreachnode,keeptrackofasetofnodesinthebinarytree(usingahashtableora BST)aswellasacurrentnode.Ateachiteration,foreachofthetwocurrentnodes, changethecurrentnodetobeitsparentandaddittotheappropriateset.thefirst elementthatisaddedtoonesetwhenitisalreadypresentintheothersetisthe lowestcommonancestor.thisalgorithmtakeso(n)time,wherenisthelengthof thepath.forexample,ifwewerefindingthelowestcommonancestorof3and15 intheabovetree,ouralgorithmwoulddothefollowing: Current node 1 Current node 2 Set 1 Set 2 -------------------------------------------------------- 3 15 3 15 6 12 3, 6 15, 12 17 6 3, 6, 17 15, 12, 6 Toimprovethesolution,weactuallyonlyneedtouseonesetinsteadoftwo. BitwiseOperations Integersarerepresentedinacomputerusingbasetwo,usingonly0'sand1's.Each placeinabinarynumberrepresentsapoweroftwo.therightmostbitcorresponds to2^0,theseconddigitfromtherightcorrespondsto2^1,andsoon.forexample, thenumber11000101inbinaryisequalto2^0+2^2+2^6+2^7=197.negative integerscanalsoberepresentedinbinary;lookup"two'scomplement"on Wikipediaformoredetails. Thereareafewoperationsthatacomputercanperformquicklyononeortwo integers.thefirstis"bitwiseand",whichtakestwointegersandreturnsaninteger thathasa1onlyinplaceswherebothoftheinputshada1.forexample: 00101011 & 10110010 ---------- 00100010 Anotheroperationis"bitwiseor",whichtakestwointegersandreturnsaninteger thathasa0onlyinplaceswherebothoftheinputshada0.forexample: 00101011 10110010 ---------- 10111011
"Bitwisexor"hasa1ineachplacewherethebitsinthetwointegersisdifferent. Forexample: 00101011 ^ 10110010 ---------- 10011001 "Bitwisenegation"takesanumberandinvertseachofthebits.Forexample: ~ 00101011 ---------- 11010100 "Leftshifting"takesabinarynumber,addsacertainnumberofzerostotheend,and removesthesamenumberofbitsfromthebeginning.forexample,00101011<<4 isequalto10110000.likewise,rightshiftingtakesabinarynumber,addsacertain numberofzerostothebeginning,andremovesthesamenumberofbitsfromthe end.forinstance,00101011>>>4=00000010.actually,thereisamorecommon formofrightshifting(the"arithmeticrightshift")thatreplacesthefirstfewbits withacopyofthefirstbitinsteadofwithzeros.forexample,10110010>>4= 11111011. Interviewersliketoaskquestionsrelatedtobitwiselogic.Often,thereisatricky waytosolvetheseproblems.bitwisexorcanoftenbeusedinatrickywaybecause twoidenticalnumbersinanexpressioninvolvingxorwill"cancelout".forexample, 15^12^15=12. Question:Compute2^x Howcanyouquicklycompute2^x? Goodanswer:1<<x(1left shiftedbyx) Question:IsPowerof2 Howcanyouquicklydeterminewhetheranumberisapowerof2? Goodanswer:Checkwhetherx&(x 1)is0.Ifxisnotanevenpowerof2,the highestpositionofxwitha1willalsohavea1inx 1;otherwise,xwillbe100...0 andx 1willbe011...1;and'ingthemtogetherwillreturn0.
Question:BeatingtheStockMarket Sayyouhaveanarrayforwhichtheithelementisthepriceofagivenstockondayi. Ifyouwereonlypermittedtobuyoneshareofthestockandselloneshareofthe stock,designanalgorithmtofindthebesttimestobuyandsell. Goodanswer:Gothroughthearrayinorder,keepingtrackoftheloweststockprice andthebestdealyou'veseensofar.wheneverthecurrentstockpriceminusthe currentloweststockpriceisbetterthanthecurrentbestdeal,updatethebestdeal tothisnewvalue. ProgramDesign Althoughitsometimesmayseemlikeit,interviewersaren'talwaysinterestedin littleprogrammingtricksandpuzzles.sometimestheymayaskyoutodesigna programorasystem.forexample,it'snotuncommontobeaskedtosketchout whatclassesyouwouldneedifyouweretowriteapokergameprogramora simulationofcartrafficatanintersection.therearemanydifferentquestionsthe interviewercouldaskaboutdesign,sojustkeepinmindthatifyouneedtodesign theclassesforaprogram,trytokeepyourdesignsimpleandatthesametimeallow forfutureextensionsonyourdesign. Forexample,ifyouweredesigningafive carddrawpokergameprogram,youcould haveagamemodeinterfaceorsuperclassandhaveafivecarddrawsubclassto encapsulatetheparticularrulesforthatversionofthegame.thereforeifthe interviewerthenasksyouhowyoucouldextendthesystemtoallowatexashold 'emgame,youcouldsimplyagainmakeatexasholdemsubclassofgamemode. DesignPatterns Adesignpatternisausefuldesigntechniquethatprogrammershavediscoveredto besousefulovertheyearsthattheygiveaspecificnametoit.interviewers sometimesaskyoutolistsomedesignpattersyouknow,andmayevenaskyouto describehowaparticularoneworks.butbesidesquestionsthatdirectlytestyour knowledgeofthem,designpattersareveryusefulasbuildingblocksforsolving otherquestions,especiallytheonesthatfocusonprogramdesign.thereareseveral designpatternsthatexist,andwerecommendthatyoutakealookatthe"design Pattern"pageonWikipediatogetanideaofseveralofthebest knowones,butthere areafewthattrulystandoutintheirpopularityandusefulness. Listener/ObserverPattern: Thismaybethemostpopulardesignpatternoutthere.Theideaisthis:suppose therewereane maillistforhackingagoogleinterview(unfortunatelythereisn't one,butifwehadbeenabitmoreforward thinking,perhapswewouldhavemade one).thislistwouldallowforimportantannouncementstobesenttoanyonewho
caredabouttheclass.everystudentwhoputthemselvesonthelistwouldbea "listener"(or"observer").theteacherwouldbethe"announcer"(or"subject"in sometexts).everytimetheteacherwantedtoletthestudentsknowsomething, theywouldgothoughthee maillistandsendanannouncemente mailtoeach listener. Inaprogram,wewouldhaveaListenerinterfacethatanyclasscouldimplement. ThatListenerinterfacewouldhavesomesortof"update()"methodthatwouldbe calledwhenevertheannouncerwantedtotellthelistenerssomething.the announcerwouldstorealistofallthelisteners.ifwewantedtoaddanobject"foo" asalistener,wewouldcall"announcer.addlistener(foo)",whichwouldcausethe announcertoaddfootoitslistoflisteners.whenevertheannouncerdidsomething importantthatitwantedtotellthelistenersabout,itwouldgothoughitslistof listenersandcall"update()"oneachofthoseobjects. Goingbacktothepokergameprogram,youmightmentiontotheinterviewerthat youcouldusethelistenerdesignpatternforseveralthings.forexample,youcould havetheguibealistenertoseveralobjectsinthegame(suchasplayerhands,the pot,etc.)foranychangesingamestateforwhichitwouldneedtoupdatethe display. SingletonPattern: Thesingletonpatternisusedwhenyouwanttomakesurethereisexactlyone instanceofsomethinginyourprogram.ifyouweremakingalordoftherings game,youwouldwanttomakesurethattheoneringwasonlyinstantiatedonce! WehavetogiveFrodoachance! InJava,forinstance,tomakesurethereisonlyoneofsomething,youcando somethinglikethis: public class OnlyOneOfMe { private static OnlyOneOfMe theoneinstance = null; private OnlyOneOfMe() { // do stuff to make the object } } public static OnlyOneOfMe getinstance() { if (theoneinstance == null) { theoneinstance = new OnlyOneOfMe(); } return theoneinstance; }
Noticethatthereisnopublicconstructor.Ifyouwantaninstanceofthisclass,you havetocall"getinstance()",whichensuresthatonlyoneinstanceoftheclassisever made. Model View Controller: Model view controller(mvc)isadesignpatterncommonlyusedinuserinterfaces. Itsgoalistokeepthe"data"separatefromtheuserinterface.Forexample,when designingaprogramthatdisplaysstockinformation,thecodethatdownloadsthe stockinformationshouldnotdependonthecodethatdisplaystheinformation. Theexactmeaningofmodel view controllerisabitambiguous.essentially,a programthatusesmodel view controllerusesseparateprogrammingentitiesto storethedata(the"model"),todisplaythedata(the"view"),andtomodifythedata (the"controller").inmodel view controller,theviewusuallymakesheavyuseof listenerstolistentochangesandeventsinthemodelorthecontroller. Model view controllerisagoodbuzzwordtowhipoutwhenyou'reaskedadesign questionrelatingtoauserinterface. ClassicQuestion#7:RansomNote Let'ssayyou'vejustkidnappedAlyssaHackeryouwanttoleavearansomnotefor BenBitdiddle,sayingthatifheeverwantstoseeheragain,heneedstoswearto neveruseschemeagain.youdon'twanttowritethenotebyhand,sincetheywould beabletotraceyourhandwriting.you'restandinginalyssa'sapartmentandyou seeamillioncomputermagazines.youneedtowriteyournotebycuttingletters outofthemagazinesandpastingthemtogethertoformaletter.here'sthe question:givenanarbitraryransomnotestringandanotherstringcontainingallthe contentsofallthemagazines,writeafunctionthatwillreturntrueiftheransom notecanbemadefromthemagazines;otherwise,itwillreturnfalse.remember, everyletterfoundinthemagazinestringcanonlybeusedonceinyourransomnote. Forexample,iftheransomnotestringwas"noscheme"andthemagazinestring was"programminginterviewsareweird",youwouldreturnfalsesinceyoucan't formthefirststringbygrabbingandrearranginglettersfromthesecondstring. Pretty goodanswer:makeadatastructuretostoreacountofeachletterinthe magazinestring.ifyou'reprogramminginc,youcanmakeanarrayoflength256 andsimplyusetheasciivalueforeachcharacterasitsspotinthearray,since charactersare1byte.ifyou'reprogramminginjava,youcanjustuseahashtable instead(sincecharactersare2bytesinjava).thengothroughthemagazinestring andforeachcharacter,incrementthevalueforthatletterinyourdatastructure. Afteryougothoughthewholemagazinestring,youshouldhaveanexactcountof howmanytimeseachcharacterappearsinthemagazinestring.thengothrough eachcharacterintheransomnotestringandforeverycharacteryouencounter,
decrementthevalueforthatletterinyourdatastructure.ifyoueverfindthatafter youdecrementacounttosomethinglessthan0,youknowyoucan'tmakethe ransomnote,soyouimmediatelyreturnfalse.ifhoweveryougetthoughtheentire ransomnotewithoutrunningoutofavailableletters,youreturntrue. Evenbetteranswer:Becausethemagazinestringmaybeverylarge,wewantto reducethetimewespendgoingthroughthemagazinestring.weusethesameidea asabove,exceptwegothroughtheransomnoteandthemagazinestringatthe sametime.keeponepointerforourcurrentcharacterintheransomnoteand anotherpointerforourcurrentcharacterinourmagazinestring.first,checktosee ifthecountinourdatastructureforourcurrentransomnotecharacterisgreater than0.ifitis,decrementitandadvancethepointerinourransomnote.ifitisn't, startgoingthroughthecharactersinthemagazinestring,updatingthecountsinthe datastructureforeachcharacterencountered,untilwereachthecharacterweneed forourransomnote.thenstopadvancingthemagazinestringpointerandstart advancingtheransomnotepointeragain.ifwegettotheendoftheransomnote, wereturntrue.ifwegettotheendofthemagazinestring(meaningwedidn'tfind enoughlettersforourransomnote),wereturnfalse.