Professional Documents
Culture Documents
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.