Professional Documents
Culture Documents
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:
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:
Inthisexample,calling"add"willresultindifferentbehaviordependingonthetype
oftheinput.
Whatisavirtualfunction/method?(inC++)
OutofallthepossiblequestionsinterviewerscouldaskaboutC++,thisoneseemsto
beastrangefavorite.Amethod'sbeing"virtual"simplydescribesitsbehaviorwhen
workingwithsuperclassesandsubclasses.AssumeclassBisasubclassofclassA.
AlsoassumebothclassesAandBhaveamethod"bar()".Let'ssaywehavethe
followingcodeinC++:
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.
HackingaGoogleInterviewHandout2
CourseDescription
Instructors:BillJacobsandCurtisFonger
Time:January1215,5:006:30PMin32124
Website:http://courses.csail.mit.edu/iap/interview
ClassicQuestion#4:Reversingthewordsinastring
Writeafunctiontoreversetheorderofwordsinastringinplace.
Answer:Reversethestringbyswappingthefirstcharacterwiththelastcharacter,
thesecondcharacterwiththesecondtolastcharacter,andsoon.Then,gothrough
thestringlookingforspaces,sothatyoufindwhereeachofthewordsis.Reverse
eachofthewordsyouencounterbyagainswappingthefirstcharacterwiththelast
character,thesecondcharacterwiththesecondtolastcharacter,andsoon.
Sorting
Often,aspartofasolutiontoaquestion,youwillneedtosortacollectionof
elements.ThemostimportantthingtorememberaboutsortingisthatittakesO(n
logn)time.(Thatis,thefastestsortingalgorithmforarbitrarydatatakesO(nlogn)
time.)
MergeSort:
Mergesortisarecursivewaytosortanarray.First,youdividethearrayinhalfand
recursivelysorteachhalfofthearray.Then,youcombinethetwohalvesintoa
sortedarray.Soamergesortfunctionwouldlooksomethinglikethis:
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:
Quicksortistypicallyveryfastinpractice,butrememberthatithasO(n^2)worst
caserunningtime,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.
Notethatthisquestionistechnicallyillposed.Anordinarylinkedlistwillhaveno
cycles.Whattheyactuallymeanisforyoutodeterminewhetheryoucanreacha
cyclefromanodeinagraphconsistingofnodesthathaveatmostoneoutgoing
edge.
StacksandQueues
Aninterviewerwillprobablyexpectyoutoknowwhatqueuesandstacksare.
Queuesareabstractdatatypes.Aqueueisjustlikealineofpeopleatanamusement
park.Aqueuetypicallyhastwooperations:enqueueanddequeue.Enqueueingan
elementaddsittothequeue.Dequeueinganelementremovesandreturnsthe
elementthatwasaddedleastrecently.AqueueissaidtobeFIFO(firstin,firstout).
Astackisanotherabstractdatatypewithtwocommonoperations:pushandpop.
Pushinganelementaddsittothestack.Poppinganelementremovesandreturns
theelementthatwasaddedmostrecently.AstackissaidtobeLIFO(lastin,first
out).Astackoperateslikeastackofcafeteriatrays.
HashTables
Ahashtableisusedtoassociatekeyswithvalues,sothateachkeyisassociatedwith
oneorzerovalues.Eachkeyshouldbeabletocomputea"hash"function,which
takessomeorallofitsinformationanddigestsitintoasingleinteger.Thehash
tableconsistsofanarrayofhashbuckets.Toaddakeyvaluepairtoahashtable,
onecomputesthekey'shashcodeandusesittodecidethehashbucketinwhichthe
mappingbelongs.Forexample,ifthehashvalueis53andthereare8hashbuckets,
onemightusethemodfunctiontodecidetoputthemappinginbucket53mod8,
whichisbucket5.Tolookupthevalueforagivenkey,onecomputesthebucketin
whichthekeywouldresideandcheckswhetherthekeyisthere;ifso,onecan
returnthevaluestoredinthatbucket.Toremovethemappingforagivenkey,one
likewiselocatesthekey'smappingandremovesitfromtheappropriatebucket.
Notethatthehashfunctionisgenerallydecidedoninadvance.
Aproblemariseswhentwokeyshashtothesamebucket.Thiseventiscalleda
"collision".Thereareseveralwaystodealwiththis.Onewayistostorealinkedlist
ofkeyvaluepairsforeachbucket.
Insertion,removal,andlookuptakeexpectedO(1)time,providedthatthehash
functionissufficiently"random".Intheworstcase,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,butthatwouldhavebadworstcaseperformance."The
interviewermightthenindicatethathe'llallowyoutouseahashtable.
ClassicQuestion#6:Datastructureforanagrams
GivenanEnglishwordintheformofastring,howcanyouquicklyfindallvalid
anagramsforthatstring(allvalidrearrangementsofthelettersthatformvalid
Englishwords)?Youareallowedtoprecomputewhateveryouwanttoandstore
whateveryouoptionallyprecomputeondisk.
Answer:Wewanttouseahashtable!Ifyourinterviewerreallyhateshashtables
(whichtheysometimesdoforsomereason),youcanuseatreeinstead.Butlet's
assumeyoucanuseahashtable.Thenfortheprecomputingstep,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!.
HackingaGoogleInterviewHandout3
CourseDescription
Instructors:BillJacobsandCurtisFonger
Time:January1215,5:006:30PMin32124
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
goodlookinganswersthatareincorrect.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,weidentifythenext
smallerornextlargerelementinthetree(itdoesn'tmatterwhich),usingan
algorithmwhichwedonotdescribehereforthesakeofbrevity.Wesettheelement
storedinthenodetothisvalue.Then,wesplicethenodethatcontainedthevalue
fromthetree.Thiswillberelativelyeasy,sincethenodewillhaveatmostonechild.
Forexample,toremove6fromthetree,wefirstchangethenodetohavethevalue
3.Then,weremovethenodethatusedtohavethevalue3,andwemake1theleft
childofthenodethatusedtohavethevalue6.
Asmallmodificationtoabinarysearchtreeallowsittobeusedtoassociatekeys
withvalues,asinahashtable.Insteadofstoringasinglevalueineachnode,one
couldstoreakeyvaluepairineachnode.Thetreewouldbeorderedbasedonthe
nodes'keys.
Interviewerssometimesaskaboutbinarysearchtrees.Inaddition,binarysearch
treesareoftenusefulasacomponentofananswertointerviewquestions.The
importantthingtorememberisthatinsertion,removal,andlookuptakeO(logn)
time(wherenisthenumberofelementsinthetree),sincetheheightofawell
balancedbinarysearchtreeisO(logn).Althoughintheworstcase,abinarysearch
treemighthaveaheightofO(n),thereare"selfbalancing"binarysearchtreesthat
periodicallyreorganizeaBSTtoensureaheightofO(logn).Manyselfbalancing
BST'sguaranteethatoperationstakeO(logn)time.Ifyouwanttolearnmoreabout
particulartypesbinarysearchtrees,suchasredblacktrees,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:
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(1leftshiftedbyx)
Question:IsPowerof2
Howcanyouquicklydeterminewhetheranumberisapowerof2?
Goodanswer:Checkwhetherx&(x1)is0.Ifxisnotanevenpowerof2,the
highestpositionofxwitha1willalsohavea1inx1;otherwise,xwillbe100...0
andx1willbe011...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,ifyouweredesigningafivecarddrawpokergameprogram,youcould
haveaGameModeinterfaceorsuperclassandhaveaFiveCardDrawsubclassto
encapsulatetheparticularrulesforthatversionofthegame.Thereforeifthe
interviewerthenasksyouhowyoucouldextendthesystemtoallowaTexashold
'emgame,youcouldsimplyagainmakeaTexasHoldEmsubclassofGameMode.
DesignPatterns
Adesignpatternisausefuldesigntechniquethatprogrammershavediscoveredto
besousefulovertheyearsthattheygiveaspecificnametoit.Interviewers
sometimesaskyoutolistsomedesignpattersyouknow,andmayevenaskyouto
describehowaparticularoneworks.Butbesidesquestionsthatdirectlytestyour
knowledgeofthem,designpattersareveryusefulasbuildingblocksforsolving
otherquestions,especiallytheonesthatfocusonprogramdesign.Thereareseveral
designpatternsthatexist,andwerecommendthatyoutakealookatthe"Design
Pattern"pageonWikipediatogetanideaofseveralofthebestknowones,butthere
areafewthattrulystandoutintheirpopularityandusefulness.
Listener/ObserverPattern:
Thismaybethemostpopulardesignpatternoutthere.Theideaisthis:suppose
therewereanemaillistforHackingaGoogleInterview(unfortunatelythereisn't
one,butifwehadbeenabitmoreforwardthinking,perhapswewouldhavemade
one).Thislistwouldallowforimportantannouncementstobesenttoanyonewho
caredabouttheclass.Everystudentwhoputthemselvesonthelistwouldbea
"listener"(or"observer").Theteacherwouldbethe"announcer"(or"subject"in
sometexts).Everytimetheteacherwantedtoletthestudentsknowsomething,
theywouldgothoughtheemaillistandsendanannouncementemailtoeach
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.
ModelViewController:
Modelviewcontroller(MVC)isadesignpatterncommonlyusedinuserinterfaces.
Itsgoalistokeepthe"data"separatefromtheuserinterface.Forexample,when
designingaprogramthatdisplaysstockinformation,thecodethatdownloadsthe
stockinformationshouldnotdependonthecodethatdisplaystheinformation.
Theexactmeaningofmodelviewcontrollerisabitambiguous.Essentially,a
programthatusesmodelviewcontrollerusesseparateprogrammingentitiesto
storethedata(the"model"),todisplaythedata(the"view"),andtomodifythedata
(the"controller").Inmodelviewcontroller,theviewusuallymakesheavyuseof
listenerstolistentochangesandeventsinthemodelorthecontroller.
Modelviewcontrollerisagoodbuzzwordtowhipoutwhenyou'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.
Prettygoodanswer: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.