You are on page 1of 6

HackingaGoogleInterviewHandout1

CourseDescription Instructors:BillJacobsandCurtisFonger Time:January1215,5:006:30PMin32124 Website:http://courses.csail.mit.edu/iap/interview ClassicQuestion#1:CoinPuzzle Youhave8coinswhichareallthesameweight,exceptforonewhichisslightly heavierthantheothers(youdon'tknowwhichcoinisheavier).Youalsohavean oldstylebalance,whichallowsyoutoweightwopilesofcoinstoseewhichoneis heavier(oriftheyareofequalweight).Whatisthefewestnumberofweighings thatyoucanmakewhichwilltellyouwhichcoinistheheavierone? Goodanswer:Weigh3coinsagainst3coins.Ifoneofthegroupsisheavier,weigh oneofitscoinsagainstanotheroneofitscoins;thisallowsyoutoidentifytheheavy coin.Ifthetwogroupsbalance,weighthetwoleftovercoins. Notsogoodanswer:Weigh4coinsagainst4coins.Discardthelightercoins,and weigh2coinsagainst2coins.Discardthelightercoinsandweightheremaining twocoins. Interviewtips Whenaskedaquestion,openadialogwiththeinterviewer.Letthemknowwhat youarethinking.Youmight,forexample,suggestasloworpartialsolution(let themknowthatthesolutionisnotideal),mentionsomeobservationsaboutthe problem,orsayanyideasyouhavethatmightleadtoasolution.Often,interviewers willgivehintsifyouappeartobestuck. Often,youwillbeaskedtowriteaprogramduringaninterview.Forsomereason, interviewersusuallyhavepeoplewriteprogramsonablackboardoronasheetof paperratherthanonacomputer.Itisgoodtogetpracticewithwritingcodeonthe boardinordertobepreparedforthis. Hereisalistof"do's"and"don't's"whendoingaprogramminginterview: Do's Askforclarificationonaproblemifyoudidn'tunderstandsomethingorif thereisanyambiguity

Lettheinterviewerknowwhatyouarethinking Suggestmultipleapproachestotheproblem Bounceideasofftheinterviewer(suchasideasfordatastructuresor algorithms) Ifyougetstuck,don'tbeafraidtoletthemknowandpolitelyaskforahint

Don't's Nevergiveup!Thissaysnothinggoodaboutyourproblemsolvingskills. Don'tjustsitinsilencewhilethinking.Theinterviewerhaslimitedtimeto findoutasmuchaspossibleaboutyou,andnottalkingwiththemtellsthem nothing,exceptthatyoucansittheresilently. Ifyoualreadyknowtheanswer,don'tjustblurtitout!Theywillsuspectthat youalreadyknewtheansweranddidn'ttellthemyou'veseenthequestion before.Atleastpretendtobethinkingthoughtheproblembeforeyougive theanswer! BigONotation BigOnotationisawaythatprogrammersusetodeterminehowtherunningspeed ofanalgorithmisaffectedastheinputsizeisincreased.Wesaythatanalgorithmis O(n)ifincreasingtheinputsizeresultsinalinearincreaseinrunningtime.For example,ifwehaveanalgorithmthattakesanarrayofintegersandincrements eachintegerby1,thatalgorithmwilltaketwiceaslongtorunonanarrayofsize 200thanonanarrayofsize100. Nowlet'slookatanalgorithmofrunningtimeO(n^2).ConsiderthefollowingJava code: boolean hasDuplicate(int[] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { if (array[i] == array[j] && i != j) { return true; } } } return false; } Thisalgorithmtakesinanarrayofintegersandcompareseachintegertoevery otherinteger,returningtrueiftwointegersareequal,otherwisereturningfalse. ThisarraytakesO(n^2)runningtimebecauseeachelementhastobecompared withnelements(wherenisthelengthofthearray).Therefore,ifwedoublethe inputsize,wequadrupletherunningtime.

ThereisalsoamoreformaldefinitionofbigOnotation,butweprefertheintuitive approachforthepurposesofprogramminginterviews. Question:Searchingthroughanarray Givenasortedarrayofintegers,howcanyoufindthelocationofaparticularinteger x? Goodanswer:Usebinarysearch.Comparethenumberinthemiddleofthearray withx.Ifitisequal,wearedone.Ifthenumberisgreater,weknowtolookinthe secondhalfofthearray.Ifitissmaller,weknowtolookinthefirsthalf.Wecan repeatthesearchontheappropriatehalfofthearraybycomparingthemiddle elementofthatarraywithx,onceagainnarrowingoursearchbyafactorof2.We repeatthisprocessuntilwefindx.ThisalgorithmtakesO(logn)time. Notsogoodanswer:Gothrougheachnumberinorderandcompareittox.This algorithmtakesO(n)time. Parallelism Threadsandprocesses: Acomputerwilloftenappeartobedoingmanythingssimultaneously,suchas checkingfornewemailmessages,savingaWorddocument,andloadingawebsite. Eachprogramisaseparate"process".Eachprocesshasoneormore"threads."Ifa processhasseveralthreads,theyappeartorunsimultaneously.Forexample,ane mailclientmayhaveonethreadthatchecksfornewemailmessagesandone threadfortheGUIsothatitcanshowabuttonbeingpressed.Infact,onlyone threadisbeingrunatanygiventime.Theprocessorswitchesbetweenthreadsso quicklythattheyappeartoberunningsimultaneously. Multiplethreadsinasingleprocesshaveaccesstothesamememory.Bycontrast, multipleprocesseshaveseparateregionsofmemoryandcanonlycommunicateby specialmechanisms.Theprocessorloadsandsavesaseparatesetofregistersfor eachthread. Remember,eachprocesshasoneormorethreads,andtheprocessorswitches betweenthreads. Mutexesandsemaphores: Amutexislikealock.Mutexesareusedinparallelprogrammingtoensurethatonly onethreadcanaccessasharedresourceatatime.Forexample,sayonethreadis modifyinganarray.Whenithasgottenhalfwaythroughthearray,theprocessor switchestoanotherthread.Ifwewerenotusingmutexes,thethreadmighttryto modifythearrayaswell,whichisprobablynotwhatwewant.

Topreventthis,wecoulduseamutex.Conceptually,amutexisanintegerthat startsat1.Wheneverathreadneedstoalterthearray,it"locks"themutex.This causesthethreadtowaituntilthenumberispositiveandthendecreasesitbyone. Whenthethreadisdonemodifyingthearray,it"unlocks"themutex,causingthe numbertoincreaseby1.Ifwearesuretolockthemutexbeforemodifyingthe arrayandtounlockitwhenwearedone,thenweknowthatnotwothreadswill modifythearrayatthesametime. Semaphoresaremoregeneralthanmutexes.Theydifferonlyinthatasemaphore's integermaystartatanumbergreaterthan1.Thenumberatwhichasemaphore startsisthenumberofthreadsthatmayaccesstheresourceatonce.Semaphores support"wait"and"signal"operations,whichareanalogoustothe"lock"and "unlock"operationsofmutexes. Synchronizedmethods(inJava): Anotherfavoritequestionofinterviewersis,"Whatisasynchronizedmethodin Java?"EachobjectinJavahasitsownmutex.Wheneverasynchronizedmethodis called,themutexislocked.Whenthemethodisfinished,themutexisunlocked. Thisensuresthatonlyonesynchronizedmethodiscalledatatimeonagivenobject. Deadlock: Deadlockisaproblemthatsometimesarisesinparallelprogramming.Itistypified bythefollowing,whichissupposedlyalawthatcamebeforetheKansaslegislature: "Whentwotrainsapproacheachotheratacrossing,bothshallcometoafullstop andneithershallstartupagainuntiltheotherhasgone." Strangeasthissounds,asimilarsituationcanoccurwhenusingmutexes.Saywe havetwothreadsrunningthefollowingcode: Thread1: acquire(lock1); acquire(lock2); [dostuff] release(lock1); release(lock2); Thread2: acquire(lock2); acquire(lock1); [dostuff]

release(lock2); release(lock1); Supposethatthread1isexecutedtojustafterthefirststatement.Then,the processorswitchestothread2andexecutesbothstatements.Then,theprocessor switchesbacktothread1andexecutesthesecondstatement.Inthissituation, thread1willbewaitingforthread2toreleaselock1,andthread2willbewaiting forthread1toreleaselock2.Boththreadswillbestuckindefinitely.Thisiscalled deadlock. ClassicQuestion#2:PreventingDeadlock Howcanweensurethatdeadlockdoesnotoccur? Answer:Therearemanypossibleanswerstothisproblem,buttheanswerthe interviewerwillbelookingforisthis:wecanpreventdeadlockifweassignanorder toourlocksandrequirethatlocksalwaysbeacquiredinorder.Forexample,ifa threadneedstoacquirelocks1,5,and2,itmustacquirelock1,followedbylock2, followedbylock5.Thatwaywepreventonethreadtryingtoacquirelock1then lock2,andanotherthreadtryingtoacquirelock2thenlock1,whichcouldcause deadlock.(Notethatthisapproachisnotusedveryofteninpractice.) SomeOtherTopics Whatispolymorphism? Interviewerslovetoaskpeoplethisquestionpointblank,andthereareseveral possibleanswers.Forafulldiscussionofallthetypesofpolymorphism,we recommendlookingatitsWikipediapage.However,webelievethatagoodanswer tothisquestionisthatpolymorphismistheabilityofonemethodtohavedifferent behaviordependingonthetypeofobjectitisbeingcalledonorthetypeofobject beingpassedasaparameter.Forexample,ifwedefinedourown"MyInteger"class andwantedtodefinean"add"methodforit(toaddthatintegerwithanother number),wewouldwantthefollowingcodetowork: MyInteger int1 = new MyInteger(5); MyInteger int2 = new MyInteger(7); MyFloat float1 = new MyFloat(3.14); MyDouble doub1 = new MyDouble(2.71); print(int1.add(int2)); print(int1.add(float1)); print(int1.add(doub1)); Inthisexample,calling"add"willresultindifferentbehaviordependingonthetype oftheinput.

Whatisavirtualfunction/method?(inC++) OutofallthepossiblequestionsinterviewerscouldaskaboutC++,thisoneseemsto beastrangefavorite.Amethod'sbeing"virtual"simplydescribesitsbehaviorwhen workingwithsuperclassesandsubclasses.AssumeclassBisasubclassofclassA. AlsoassumebothclassesAandBhaveamethod"bar()".Let'ssaywehavethe followingcodeinC++: A *foo = new B(); foo->bar(); Ifthemethod"bar()"isdeclaredtobevirtual,thenwhenwecallfoo>bar(),the methodfoundinclassBwillberun.ThisishowJavaalwayshandlesmethodsand it'susuallywhatwewanttohappen.However,ifthemethodbar()isnotdeclaredto bevirtual,thenthiscodewillrunthemethodfoundinclassAwhenwecall foo>bar(). ClassicQuestion#3:AtoI Writeafunctiontoconvertastringintoaninteger.(ThisfunctioniscalledAtoI(or atoi())becauseweareconvertinganASCIIstringintoaninteger.) Goodanswer:Gothroughthestringfrombeginningtoend.Ifthefirstcharacterisa negativesign,rememberthisfact.Keeparunningtotal,whichstartsat0.Eachtime youreachanewdigit,multiplythetotalby10andaddthenewdigit.Whenyou reachtheend,returnthecurrenttotal,or,iftherewasanegativesign,theinverseof thenumber. Okayanswer:Anotherapproachistogothroughthestringfromendtobeginning, againkeepingarunningtotal.Also,rememberanumberxrepresentingwhichdigit youarecurrentlyon;xisinitially1.Foreachcharacter,addthecurrentdigittimesx totherunningtotal,andmultiplyxby10.Whenyoureachthebeginning,returnthe currenttotal,or,iftherewasanegativesign,theinverseofthenumber. Note:Theinterviewerislikelytoaskyouaboutthelimitationsofyourapproach. Youshouldmentionthatitonlyworksifthestringconsistsofanoptionalnegative signfollowedbydigits.Also,mentionthatifthenumberistoobig,theresultwillbe incorrectduetooverflow.

You might also like