Академический Документы
Профессиональный Документы
Культура Документы
intro
[::FORUM::]
easy
med
hard
m$
cs
putnam
cigs
FAQ
pros
cons
laff
credits
bookmarkthispage
visittheriddlesforum
PagelastmodifiedFriday,18Feb200519:30:38PST
SYMBOLS
RIDDLEINDEX
M
C
Needsmathpastarithmeticandbasicprobability.
P
>=P
CPU
Physicsknowledgeishelpful.
Requiresknowinghowtoplaychess.
Idon'tknowthesolutiontothisproblemmyself.
relativelyeasy
easy
relativelymedium
med
relativelyhard
hard
microsoft
m$
computerscience
cs
putnam
putnam
Requirescalculator/computerpower.
FORUM
Stuck?Havecomplimentsorcriticisms?
Wanttotest driveanewriddleofyourown?
Whoarewe,andwhatdowedo?
Visitthefantabulousriddleforum!
Thousandsofpostsbyreallycleverpeople.
RECENTADDITIONS
Checkoutlatestpuzzlesbyperusingthe forumandthe 10mostrecentposts.
Latestadditionstocoversitecanbeseenbyclickinghere.
computerscience
ROTATEDSORTED
LISTSEARCH
AnelementinasortedarraycanbefoundinO(logn)timeviabinarysearch.ButsupposeIrotatethesortedarray
atsomepivotunknowntoyoubeforehand.Soforinstance,12345mightbecome34512.Nowdeviseaway
tofindanelementintherotatedarrayinO(logn)time.
intatoi(char*pStr)
ASCIITOINT
Writethedefinitionfortheatoi(ASCIItointeger)functionwithoutusinganybuiltinfunctions.IfpStrisnull,return
0.IfpStrcontainsnonnumericcharacters,eitherreturn0(ok)orreturnthenumberderivedsofar(better)(e.g.if
its"123A",thenreturn123).Assumeallnumbersarepositive.Plusorminussignscanbeconsiderednonnumeric
characters.
LINKEDLISTLOOP
Usingaconstantamountofmemory,findaloopinasinglylinkedlistinO(n)time.Youcannotmodifythelistinany
way.
Note:"Constantmemory"=thememoryrequiredforthesolutioncannotbeafunctionofn.
PALINDROMETEST
REPEATEDNUMBER
Writealittleprogramthatacceptsasinputastring,andoutputsabooleanvaluetellingwhetherornottheinput
isapalindrome.(Asalways,therearebothsmartandstupidwaystodothis...)
YouaregivenasequenceSofnumberswhosevaluesrangefrom1ton 1.Oneofthesenumbersrepeatsitself
onceinthesequence.(Examples:{1234563},{4212365}).Writeaprogramthatfindsthisrepeating
numberusingaconstantamountofmemory.Nowwhatiftherearetworepeatingnumbers(andthesame
memoryconstraint)?
Note:"Constantmemory"=thememoryrequiredforthesolutioncannotbeafunctionofn.
REPEATEDNUMBER
YouaregivenasequenceSofnumberswhosevaluesrangefrom1ton 1.Oneofthesenumbersrepeatsitself
onceinthesequence.(Examples:{1234563},{4212365}).Writeaprogramthatfindsthisrepeating
numberusingaconstantamountofmemory.Nowwhatiftherearetworepeatingnumbers(andthesame
memoryconstraint)?
Note:"Constantmemory"=thememoryrequiredforthesolutioncannotbeafunctionofn.
XORFROMNAND
QUICKSORT
MALLOC
STRING
PERMUTATIONS
MakeanXORgateusingonlyNANDgates.
Writequicksort.
Implementmalloc.
Writeafunctiontoprintallofthepermutationsofastring.
I/Ocompletionportsarecommunicationsportswhichtakehandlestofiles,sockets,oranyotherI/O.Whena
I/OCOMPLETION
PORTS
>=P
ReadorWriteissubmittedtothem,theycachethedata(ifnecessary),andattempttotaketherequestto
completion.Uponerrororcompletion,theycallausersuppliedfunctiontolettheusersapplicationknowthatthat
particularrequesthascompleted.Theyworkasynchronously,andcanprocessanunlimitednumberof
simultaneousrequests.DesigntheimplementationandthreadmodelsforI/Ocompletionports.Remembertotake
intoaccountmultiprocessormachines.
Note:Argh,IshouldknowhowtodothisaftertakingCS162.
BINARYTREEPRINT
Howwouldyouprintoutthedatainabinarytree,levelbylevel,startingatthetop?
BASEN
Demonstrateadditioninsomebasen,wherenisnot2,8,10,or16.Nowtryn=2.
STRINGREVERSAL
Reversethewordsinasentence,i.e."MynameisChris"becomes"ChrisisnameMy."Optimizeforspeed.
Optimizeforspace.
Giventhatyouarereceivingsamplesfromaninstrumentataconstantrate,andyouhaveconstantstorage
STORAGE
ALGORITHM
space,howwouldyoudesignastoragealgorithmthatwouldallowyoutogetarepresentativereadoutofdata,
nomatterwhenyoulookedatit?Inotherwords,representativeofthebehaviorofthesystemtodate.
Update:Gotseveraldozensofanswersforthisone,thanks/.
SORTINGALGO
COMPARISON
MULTIPLYWITHOUT
MULTIPLYING
Describethevariousstandardsortingalgorithms(theonesyoulearnedinschool),anddiscussadvantagesand
disadvantages.Whenwouldyouuseoneoveranotherwhy?
Multiplyby8withoutusingmultiplicationoraddition.Nowdothesamewith7.
STRING
COMPARISON
ComparetwostringsusingO(n)timewithconstantspace.
LINKEDLISTVS.
ARRAY
What'sthedifferencebetweenalinkedlistandanarray?
Aburglarbreaksintoanelectronicsstore.HehasabagofvolumeV,andheseesNdifferentgadgets,eachwith
DYNAMIC
PROGRAMMING
itsownpricevalue.Hewantstochoosegadgetsthatmaximizethevalueofhissteal,whilemaintaininghis
volumeconstraint.Writeadynamicprogrammingalgorithmthatcalculateswhichobjectsshouldbechosen,and
thevalueoftheoptimalsteal.
SUBSTRINGSEARCH
STRING
INTERSECTION
GiventwostringsAandB,writeaprogramthatdeterminesifAisasubstringofB.Optimizeforspeed.Optimize
forspace.
GiventwostringsAandB,writeaprogramthatreturnstheintersectionofAandB(couldbenull).Nowspeedit
up.Nowtestit.
Writeaprogramthatwilldisplaya"spiral"ofNxNnumbers,usingconstantspace(noarraysallowed).For
example,here'swhatthespirallookslikeforN=10:
99989796959493929190
INTERSECTION
up.Nowtestit.
Writeaprogramthatwilldisplaya"spiral"ofNxNnumbers,usingconstantspace(noarraysallowed).For
example,here'swhatthespirallookslikeforN=10:
NUMBERSPIRAL
99989796959493929190
64636261605958575689
65363534333231305588
66371615141312295487
67381743211285386
68391850110275285
6940196789265184
70412021222324255083
71424344454647484982
72737475767778798081
Note:manythankstohordesof/.'ersforpointingoutanerrorinthereadout
ONESINA
REGISTER
Howcanyoudeterminethenumberofonesinann bitregisteronlyusingiiterations,whereiisthenumberof
onesintheregister?
Update7/24/20022:58AM:Receivedmanysolutionsforthisproblemnowthanksto/.Ipromisetoeventually
creditallthepeoplewhosentmestuff.
REGISTERVALUE
SWAP
VARIABLERENAMER
Inconstanttime,withoutusinganyextramemory,exchangethevaluesoftwoequallysizedvariables(e.g.32Bit
Ints,butinfinitelylongalsoworks,givingitamoretheoreticaltouch).
YouarewritingaparserthatreadsaCprogramandtranslatesallthevariablenamesintonewnamesoftheform
"VAR######",where######isanintegerincrementedforeachuniquevariablename.Discusswhatis
neededforthecasewheretheCprogramalreadycontainsavariableoftheform"VAR######".
Tworobotsaretobeparachutedontorandomlocationsonaninfiniteline.Whentheyland,theirparachutes
detachandremainwheretheyare.Therobotsmaybeprogrammedfromthefollowinginstructionset:
l
ROBOTCOLLISION
PROGRAMMING
l
l
l
Goleftoneunit
Gorightoneunit
Skipnextinstructionunlessthereisaparachutehere
Gotolabel
Eachinstructiontakesonecycletoexecute.Programtherobotstocollide.
Note:FromMicrosoft.Howcool!
WriteaC/C++programthattakesanunsignedintegerandadds1toitwithoutusingtheplusorminussigns.
ADDONEWITHOUT
USING+OR
Don'tworryaboutoverflowissues.Itischeatingtouseassemblycommands,ortowriteapreprocessorthatuses
ASCIIcodestoinserttheplusorminussign.Therearemanysolutions,somemoreelegantthanothers.
Note:FromAtariGames!
ARRAYROTATION
UsingconstantspaceandO(n)time,rotatethearraysuchthatitcontains{x k ,x k+1 ...x n ,x 1 ,x 2 ...x k 1 }.
Eisasetofboysandgirls.Pisasetofunorderedpairs(x,y)ofthoseboysandgirls.Iftwopeopleareinapair,
thentheywouldbewillingtogoonaromanticdate.Listoutallthepossibledatingcombinationsthatcouldoccur
inonenight,suchthatnopersondatesmorethanoneotherpersonthatnight.(Technically:Generateallsubsets
ofPsuchthatnopersonisusedmorethanoncepersubset.)
Example:
E={Alice,Bob,Cole,Doris}
P={(Alice,Bob)(Alice,Cole)(Bob,Doris)(Cole,Doris)}
DATING
POSSIBILITIES
Amaximalnumberofdatingscenariosthatcouldoccurinonenight,suchthatnoonedatesmorethanoneperson
inthesamenight:
{(Alice,Bob)}
{(Alice,Cole)}
{(Bob,Doris)}
{(Cole,Doris)}
{(Alice,Bob),(Cole,Doris)}
{(Alice,Cole),(Bob,Doris)}
{(Alice,Cole)}
{(Bob,Doris)}
{(Cole,Doris)}
{(Alice,Bob),(Cole,Doris)}
{(Alice,Cole),(Bob,Doris)}
HowwelldoyouknowC"for"loops?
Findthreewaystomaketheprogrambelowtoprint20copiesofthedashcharacter' 'bychanging/addingonly
FORLOOPTWEAKS
onecharacter:
inti,n=20
for(i=0i<ni){printf("")}
Findthenthelementfromtheendofalinkedlist(wheren<sizeoflist).
NTHFROMEND
Note:askedatm$interviews.
IgiveyouthreepointsonaCartesianplanewhichdefinetheverticesofatriangle.NowIgiveyouafourthpoint.
Writeupanalgorithmthatcandetermineifthefourthpointiswithintheinteriorofthegiventriangle.
TRIANGLEINTERIOR
Note:Fromtopcoder.comviaYosenLin.Topcoderisanonlinecompetitionarenawherepeopletrytocodecorrect
solutionstoproblemsasquicklyaspossible,forprizemoney.Speedisabigdeal.Ifyou'rewritinganastysolution
forthisproblemthatinvolvessolvingseveralsimultaneousequations,you'retakingthestandardroute.Thereisa
morecleverwaythatisverysnappyandelegant.
Explainexactlyhowthiscodeworks.Particularly,everycharacterinthefirstthreelines.
# d e f i n e _ F > 0 0 | | F OO
longF=00,OO=00
m a i n { F _ O O p r i n t f " % 1 . 3 f \ n " , 4 . * F/OO/OO}F_OO
{
_ _ _ _
_ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _
OBFUSCATEDPI
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _
_ _ _ _
}
Note:FromtheObfuscatedCcodecontest.Clickhereformorewacky1337code.
YouhaveaboxandNcards.Eachcardisblueononeside,whiteontheother.Becauseoftheasymmetricshapes
ofthecards,whichexactlymatchtheshapeoftheholeinthebox,eachcardwillfitintheboxinonlytwopossible
ways(gray side uporwhite side up).Eachcardcontains2RcircleslinedupintwocolumnsandRrows,eachof
whichmaybepunchedout(soitisahole)ornot.Yourpuzzleistoseeifyoucanplaceallthecardsinthebox
(eachoneeithergray side uporwhite side up)soastocompletelycoverthebottomofthebox,i.e.eachofthe
2Rcirclepositionsiscoveredbyatleastonecardthathasnoholepunchedoutthere.
Example:InthecardsforPuzzle1(leftexamplebelow),with2cardseachwith2rows,itisnotpossibletoput
themintheboxtocovereachcircle,butwithPuzzle2(rightexamplebelow),with2cardseachwith3rows,itis
possible.(Punched outcirclesareshowninblack).
PUNCHOUTCARDS
Example:InthecardsforPuzzle1(leftexamplebelow),with2cardseachwith2rows,itisnotpossibletoput
themintheboxtocovereachcircle,butwithPuzzle2(rightexamplebelow),with2cardseachwith3rows,itis
possible.(Punched outcirclesareshowninblack).
PUNCHOUTCARDS
Showthatthisproblem(decidingifthecardscanbeputintheboxtocovereachcircleposition)isNPcomplete.
INSTANCE:G=(V,E)isanundirectedgraph.RisasubsetofverticesV.kisapositiveinteger.
QUESTION:DoesthereexistasubtreeofGthatincludesallverticesofRandcontainsatmostkedges?
Example:ThegraphGbelow,withR={1,2,3,4,5,6,10}andk=8,isa"yes"instance.
STEINERTREE
ProvethatthisproblemisNP complete.
a.
SupposenextweeksomeoneannouncedandprovidesaconclusiveproofthatP!=NP.Inaparagraph,
explainwhatimpactyoubelievesucharesultwouldhaveonthefieldofcomputerscienceandonsocietyat
large.
P?=NP
b.
(alternatively)SupposenextweeksomeoneannouncedandprovidesaconclusiveproofthatP=NP.Ina
paragraph,explainwhatimpactyoubelievesucharesultwouldhaveonthefieldofcomputerscienceand
onsocietyatlarge.
Note:Parta.wasanextracreditproblemontheCS172Spring2001FinalExamatUCBerkeley.
NONCONSTRUCTIVE
P=NP
You'vemadethebreakthrougheverytheoristdreamsof:you'vesolvedPvsNP.Surprisinglyenough,you've
shownthatP=NP,butsadlyyourproofwasnon constructive.DesignapolytimeprogramtosolveSAT.
a.
Forachessboardofstandard8X8size,writeaprogramdeviseapathforaKnightusingstandardKnight
movestovisitallsquaresonceandonlyonce.ThesquaretheKnightstartsoniscountedasvisited.
(FYI,aknightcanmovefollowingthisrule:2squaresacrossand1squaredownor2squaresdownand1
squareacross.)
KNIGHTTOURS
b.
NOBRUTEFORCEapproaches.Optimizecodeforspeed.
Donothardcodethestartingsquare.Makeitaparameter.
Ifthatistooeasy,hereisanotherrestriction:TheproblemdescribedaboveisknownasaKnightsTour.You
canmodifyyourcodetodoaCompleteKnightsTour,wherethefinalsquarevisitedbytheKnightisdirectly
adjacent(notdiagonal)tothesquaretheKnightstartedon.
c.
Ifyouthinkallofthatistooeasy,userecursion.
You'reasuper villainandyouwanttoprepareatransparency(thekindthatgoesonanoverheadprojector)with
adjacent(notdiagonal)tothesquaretheKnightstartedon.
c.
Ifyouthinkallofthatistooeasy,userecursion.
You'reasuper villainandyouwanttoprepareatransparency(thekindthatgoesonanoverheadprojector)with
thekeypointsofyourplanforworlddominationsoyoucanpresentthemtothehero/superagentbeforeyou
attempttokillhiminsomeridiculouslynovelway.Youdon'twantthisinformationtofallintothewronghands
SUPERVILLAIN
TRANSPARENCIES
beforeyou'reready.Smartvillainthatyouare,youknowyoucansharetheinformationacrossseveralslidesso
thatiftheenemyagentscaptureany2ofyourslides,theywon'tlearneventhetiniestbitofinformationabout
yourplan.How?
Note:Awfullycoolriddle,isn'tit:)ThankstoAlexHarris.
Youaregivenabinarysearchtreewithnodesofthefollowingform:
structnode{
structnode*left
structnode*right
BSTTOLL
Writeasimplefunctionthatconvertsthetreetoanordereddoublylinkedlistbychangingthelinksintheexisting
tree.Yourfunctionshouldhavethefollowingform:
voidbst2llstructnode*root,structnode*first,structnode*last
where firstandlastarereturnvalues.
a.
Constructacircuitwhichtakesthreebinaryinputs,a,b,c,andcreatesasoutputstheircomplements,a',b',
c',(NOTa,NOTb,NOTc)withtherestrictionthatyoumayonlyusetwoinverters(NOTgates),andallthe
ANDgatesandORgatesthatyouwish.
THREEINVERTERS
FROMTWO
b.
Nowgeneralize.HowmanyinvertersdoyouneedtocomputethecomplementsofNinputs?
Givenacomputerwith8kbytesofmemory(RAM),andanexecutionspeedof1billion(10**9)instructionsper
second,whatisthelongestterminatingprogram(intermsofexecutiontime)whichcanrunonthemachine?
LONGEST
TERMINATING
PROGRAM
"Terminating"meansthattheprogramisguaranteedtoexecutesomeHALTinstruction.
Thedesiredsolutionissimplya"backoftheenvelope"estimate.Theexactanswer,ofcourse,dependsondetails
suchasexactlywhattheinstructionsetlookslike,andsoforth.Feelfreetomakereasonableassumptions,where
necessary.
2SATTO2COL
Reduce2SATto2COLORABILITY.
ConsidertheSingleInstructionComputer(SIC).Ithasonlyoneoperation,andnoregisters,takingeverything
frommemory.Theonlyoperationiscalledsbn,forSubtractandBranchifNegative.Ittakesthreeoperands,allof
whicharememoryaddresses.Itworkslikethis:
l
Taketheinstructionsbna,b,c.
Letthevalueataddressaequalthevalueataddressaminusthevalueataddressb.
(InClanguage,thatwouldbe*a=*a*b)
Ifnewvalueataislessthan0,jumptomemoryaddresscanddoinstructionsfromthere.Elsegotonext
instruction.
(cisusuallyinterpretedasalabel.)
Despiteitstininess,thisinstructionsetisstillcapableofdoingmanythings,perhapsmorethanyouwouldexpect.
EASY
1.
Implementleftshift.Givenanaddressa,shiftthevalueinaonebittotheleft.Bringin
zeroesontheright.(Hint:Rememberthatleftshiftisthesameasmultiplyby
two...now...howcanwedothat...?)
2.
Implementunconditionaljump.Makeanunconditionaljump,thatwillalwaysjumptoto
thelabelatc.Useatemporaryvariable.(BigHint:Thistakesmetwoinstructions.Here's
myanswer:sbntemp,tempsbntemp,one,LABEL.)
3.
Implementmultiplication.Giventwoaddresses,aandb,setanotheraddresscequalto
atimesb.Assumethatthevaluesofaandbarenonnegative,andyoucanchange
them.Workonfiguringouthowtodoaloop,too.(Then,doitsothatyoucan'tassume
2.
Implementunconditionaljump.Makeanunconditionaljump,thatwillalwaysjumptoto
thelabelatc.Useatemporaryvariable.(BigHint:Thistakesmetwoinstructions.Here's
myanswer:sbntemp,tempsbntemp,one,LABEL.)
3.
Implementmultiplication.Giventwoaddresses,aandb,setanotheraddresscequalto
atimesb.Assumethatthevaluesofaandbarenonnegative,andyoucanchange
them.Workonfiguringouthowtodoaloop,too.(Then,doitsothatyoucan'tassume
they'renonnegative,anddoitwithoutchangingthem.That'sabitharder.)
4.
Implementsignchecking.Givenanaddressa,setanotheraddressbtoequaltrueifthe
valueinaisnegative,orsetbtofalseifitisnonnegative.Youmightwanttotakethis
opportunitytofindgoodvaluestorepresenttrueandfalsewith.(Hint:Thiswillcomein
handyinsomeoftherotateandshiftcommands...doyouknowwhy?)
MEDIUM
SINGLE
INSTRUCTION
COMPUTER
1.
Implementcomparetozero.Givenanaddressa,setanotheraddressbtoequaltrueif
thevalueataisequalto0,andfalseifthevalueataisnotequalto0.Donotchange
thevalueina.
2.
Implementleftrotate.Givenanaddressa,rotateitonebittotheleft,bringinginthebit
fromtheleftontherightside.
HARD
1.
Implementrightrotate.Givenanaddressa,rotatethevalueintheaddressaonebitto
theright,bringinginthebitfromtherightontheleftside.
Note1:Assumethatvaluesattheaddressesarestandard8 bitsignedintegersintwo'scomplementform.You
canalsoassumethereisanaddresscalled ONEthatalwaysstartsoutwiththevalueone.UseONEtomake
incrementationanddecrementationeasier,andformakingbooleanvalues.Alsoyoucanusethenotation . + 1 to
showthatcequalsthenextinstruction'saddress,sothatevenifa<0,theprogramgoestothenextinstruction
anyway,asin s b n a , b , . + 1
Note2:Tohelpyougetstarted,here'showyouwouldimplementaddition:
sbntemp,temp
sbntemp,b
sbna,temp
//Linebylineexplanation:
l
Line1:Sincewedon'tknowwhatwasintempbefore,it'suninitialized.Butdoingthiswillinitializeitandset
ittozero,sincetemptemp=0.cisblank,soprogramflowwillalwaysgotothenextinstruction.
Line2:temp=tempbsincetempiszero,tempisnowequalto b.Sincecisempty,evenifbislessthan
0,programflowstillgoestothenextinstruction
Line3:a=atempsincetemp=b,thisisa(b),whichisa+b
Note3:Fromthetextbook"ComputerOrganizationandDesign:TheHardware/SoftwareInterface"2ndedition,by
DavidA.PattersonandJohnL.Henessey,MorganKaufmannPublishers,SanFrancisco,California.
Note4:Whatotheroperationscanyouthinkofthatwouldmakegoodpuzzles?E mailwwu atocf.berkeley.edu.
MISSINGINTEGER
INARRAY
Youhavea99cellarray.Ineachcellyouputanintegerbelongingtotheset{1,2,...,100}.Notwocellscontain
thesameinteger.Thuswhenthearrayfillingiscomplete,oneoftheintegersfrom1to100isnotpresentinthe
array.Determinewhichintegerismissingfromthearray.(Thelowertherunningtimeofyouralgorithm,the
better.)
AboardthespaceshipDiscovery,theHAL9000hasgonerogueandneedstobeshutdownasquicklyaspossible!
ThecomputerhasMmicroprocessorsworkinginparallel,eachofwhichislocatedinadifferentareaoftheship.If
anyNoftheseprocessorsisdestroyed,theHAL9000willbecomeinoperational.Usingyourtrustyhammer,you
plantodoexactlythat.Youhaveamapofthespaceship,whichlookslikeaKbyKmazegridwithwallshereand
there.Coordinates(1,1)correspondtothecornersquareonthebottom leftofthemap.Themapshowsthe
locationsofallMprocessors.Youarecurrentlystandingatcoordinates(X,Y).
AboardthespaceshipDiscovery,theHAL9000hasgonerogueandneedstobeshutdownasquicklyaspossible!
ThecomputerhasMmicroprocessorsworkinginparallel,eachofwhichislocatedinadifferentareaoftheship.If
anyNoftheseprocessorsisdestroyed,theHAL9000willbecomeinoperational.Usingyourtrustyhammer,you
plantodoexactlythat.Youhaveamapofthespaceship,whichlookslikeaKbyKmazegridwithwallshereand
there.Coordinates(1,1)correspondtothecornersquareonthebottom leftofthemap.Themapshowsthe
locationsofallMprocessors.Youarecurrentlystandingatcoordinates(X,Y).
HAL9000
SHUTDOWN
HavingtakenCScoursesbefore,yourealizethatacomputerprogramcouldhelpyououthere.Althoughtheon
boardcomputerscan'tbetrusted,youhaveanuncorruptedPDAthatcoulddothejob.Writeanalgorithmfor
findingtheshortestroutefromwhereyouarestandingrightnowthatallowyoutobashNprocessorsalongthe
way.Assumethatyoucanonlymoveup,down,left,andright.
Note1:Allaforementionedvariablesarepositiveintegers.M>=N.K>=X.K>=Y.
Note2:Problemadaptedfromtopcoder.com.Storylinebyme=)
WriteafunctionwhichconvertsanumberintoanExcelspreadsheetcolumnname.
EXCELSIMULATOR
0=A
...
25=Z
26=AA
...
701=ZZ
702=AAA
Note:[fromMishaKruk]Thisoneiseasy,butalittlebittricky(inthe"Iguaranteethatyourfirstsolutionwillfail"
way).
Writeafastprogramthatprintsperfectpowers(integersoftheformm n ,withm,n>1)inincreasingnumerical
order.Sothefirstfewoutputsshouldbe4,8,9,16,25,27,32,...
"Fast"isintentionallyfuzzy.Theoriginalcontestruleswerethattheprogramshadtobeinastandarddialectof
Basicandfitononepage,andthecontestorganizerswouldtypetheminandtimethemontheirsystem,withthe
PERFECTPOWERS
winnerbeingthefastestonetoprintallperfectpowerslessthanN=10,000,000.Adifferentrulemightbethat
youralgorithmhastoworkforunlimitedN,andthealgorithmthathastheleasttimecomplexity(intheO(f(N))
sense)wins.Canyouthinkofanalgorithmthatwouldwinundertheoriginalrulesbutwouldbedisqualifiedunder
thelaterrules?
Note:Froma1977highschoolprogrammingcontest(TimMann).
SELFPRINTING
PROGRAM
Writeaprogramthatprintsitself!
(Usingtopcoder.comproblemstatementformat.Youhavean8secondprogramexecutionlimitona700MHz
PentiumIII.)
PROBLEMSTATEMENT
InthegameofPegSolitaire,youaregivenaarrangementofpegsthatfitintoalineofequallyspacedholes.In
ordertowinthegame,youmustreducethenumberofpegstoone,byusingaseriesofjumps.Eachjumpoccurs
accordingtothefollowingrules:
l
l
l
Apegmayonlyjumpoverthoseimmediatelyadjacenttoitontheleftorright.
Ajumpingpegmustjumpexactlyoneotherpeg,nomore,noless.
Oncethejumpiscompleted,thepegthatwasjumpedoverisremoved.
Forexample,giventheconfigurationofpegsandholes
...1234.5....
whereaperiodrepresentsanemptyhole,andwhereadigitrepresentsapeg,theonlytwolegalmovesareas
follows:
...12..35....[peg3jumpedoverpeg4,whichwasthenremoved]
..2..34.5....[peg2jumpedoverpeg1,whichwasthenremoved]
Apositionisdefinedas"winnable"if,throughaseriesofjumps,itcanbereducedtoonepeg.Forexample,the
abovepositioniswinnable,sinceitcanbereducedtoonepegbythefollowingsetofjumps:
...1234.5....[initial]
...12..35....[peg3jumpedoverpeg4]
.....1.35....[peg1jumpedoverpeg2]
.....15......[peg5jumpedoverpeg3]
PEGSOLITAIRE
...1234.5....[initial]
...12..35....[peg3jumpedoverpeg4]
.....1.35....[peg1jumpedoverpeg2]
.....15......[peg5jumpedoverpeg3]
....5........[peg5jumpedoverpeg1]
GivenanumberNofpegs,writeamethodthatreturnsthenumberofwinnablepositionsthatconsistofNpegs.
NOTES
l
l
l
Whenconsideringwhethertwopositionsareidentical,disregardexcessemptyholesontheleftandright
side.
Notethatthereisno"edge"oftheplayingfieldthereareessentiallyinfinitelymanyemptyholes.
Aninputisvalidifthefollowingcriterionismet:sizewillbeanintegerbetween2and35,inclusive
TESTCASES
Input:2
Output:1
Thereisonlyonewinnablecasewith2pegswhentheyareadjacent.
Input:4
Output:3
Thepatternscontaining4pegsare:
..12.3.4..
..12..34..
..1.2.34..
Input:8
Output:23
Note:Aproblemsetfromtopcoder.com,writtenbyMattLahut.
Consideranarrayofintegersa[1]...a[n].DesignanO(n)algorithmthatfindsthepairI,J(withI<=J)suchthat
thesum
MAXIMALSUMIN
INTEGERARRAY
ismaximized.(Notethatintegerscanbebothpositiveandnegative.)
Note:SourceUCBCS170(Algorithms)Spring2002,Homework1.
Findthesecondsmallestintegerinanarrayofnintegers.Runtimerestraint:n+O(logn)comparisons.Tricky!
SECONDSMALLEST
Note:SourceUCBCS170(Algorithms)Spring2003,Homework1.
1/31/20031:38AM
Imagineaworldwheremultiplicationoverthesymbolsa,b,andcisdefinedasfollows:
abc
a|aac
b|cab
c|bca
abc
a|aac
b|cab
c|bca
(interpretthistableassayinga*a=a,b*c=b,andsoon)
DFADESIGNI
Thisessentiallysaysmultiplythefirsttwodigits,thentakethatproductandmultiplyitbythethirddigit,thentake
[i]that[/i]productandmultiplyitbythefourthdigit,andsoon,processingthestringinthisfashionfromleftto
right.Similarly,definetheRLProductofSasfollows
Note1:FromRanjitJhala,GSIforCS172(ComputabilityandComplexity)atUCB,andmyformerCS170GSI.Taken
fromdiscussion1/29/2003.
Note2:Notethatthedesiredlanguageisnotquitealanguageofpalindromes.ThereisnoDFAwhichcanaccept
palindromes.
Note3:Ifyouareunfamiliarwiththeterminology,feelfreetoask.Oryoucangooglesearchforlecturenotes.
1/31/20031:38AM
Theeuclideantraveling salesmanproblemistheproblemofdeterminingtheshortestclosedtourthatconnectsa
givensetofnpointsintheplane.Figure(a)showsthesolutiontoa7pointproblem.
Inthisproblem,weconsideravariation,thebitoniceuclideantraveling salesmanproblem.Weconsideronly
bitonictours,thatis,toursthatstartattheleftmostpoint,gostrictlylefttorighttotherightmostpoint,andthen
gostrictlyrighttoleftbacktothestartingpoint.
BITONICTOURS
DescribeanO(n 2 )timedynamicprogrammingalgorithmfordetermininganoptimalbitonictour.Youmayassume
thatnotwopointshavethesamex coordinate.Afullsolutionshouldincludethefollowing:
1.
2.
3.
SpecifythedimensionsofthedatastructureusedinyourDPalgorithm,andexplainhowtoretrievethe
answerafterthestructureisfilled.
Specifywhichentriescanbefilledfromthestart(basecase),andgivearecursiveformulaforacquiringthe
otherentries.
Estimatethetimeneededtofilloneentry,andgivethetotaltimeneededtofillthewholematrixandfind
theanswertotheproblem.
Hint:Whatyouneedtodoisdivideeachpointintotwogroups.Wetraversethefirstgroupinlefttorightorder,
followedbythesecondgroupinright toleftorder.There'sanobviousalgorithmwhichjusttrieseverypossibility,
butitisexponential.We'dlikeadynamicprogrammingsolutionthatsolvessubproblemsfromlefttoright,dealing
withjustthefirstipointsineachcase.)
Note:SourceUCBerkeleyCS170(algorithms),Spring2002.ClassmatesandIstaredatitforeverinofficehours.
Writearegularexpression(orequivalently,constructadeterministicfiniteautomaton)thatacceptsstringsover
thealphabet{a,b}inwhichthenumberofoccurrencesof'ab'=numberofoccurrencesof'ba'.
Note1:What'saregularexpression?Basically,itmatchescharacterstringsthatfitacertainpattern.Youare
Writearegularexpression(orequivalently,constructadeterministicfiniteautomaton)thatacceptsstringsover
thealphabet{a,b}inwhichthenumberofoccurrencesof'ab'=numberofoccurrencesof'ba'.
RegEx:ab,ba
Note1:What'saregularexpression?Basically,itmatchescharacterstringsthatfitacertainpattern.Youare
restrictedtotheoperatorsOR,CONCATENATE,andKleeneStar.Andyoucanusealltheparenthesesyouwant.
google(regular+expressions)
Note2:Thisproblemoftentripspeopleupbecauseregularexpressionsarenotsupposedtohaveunbounded
countingability.There'saone toonecorrespondencebetweenaregularexpressionandfinitestatemachines,
andtheabilitytocountarbitrarilyhighrequiresanunboundedamountofstatespace.Itfollowsthatyoucannot
makearegularexpressionthatmatchesall0 1stringsoftheform0 n 1 n ,wherenisaninteger,andthenotation
0 n referstothestringofnconsecutivezeroes.However,inthiscasethere'ssomethingslightlycunningyoucan
observewhichwillallowyoutorealizeaRegularExpression.
Averyhardproblem.LetLbearegularlanguage.Showthatthefollowinglanguageisregular.
half(L)={x:thereexistsaysuchthatxyisinL,and|x|=|y|}
RegEx:half(L)
Hint1:ItwillbeprobablybetoodifficulttoconstructaRegExforthis.Trymakinganondeterministicfinite
automaton.Ifyou'renotawareofit,there'saonetoonecorrespondencebetweendeterministicfiniteautomata
(DFA),andnondeterministicfiniteautomata(NFA).Thisissurprisingbecauseonewouldexpectnondeterminismto
giveusmuchaddedpower,butitendsupbeingnobetterthanaDFA.
Hint2:Thinkaboutcrossproducts.Ifyou'veeverseentheproductconstructionbasedproofthatregular
languagesareclosedunderintersection,thatstyleofapproachshouldbehelpfulforthisproblem.
Constructafinitestatemachine(orequivalently,writearegularexpression)whichacceptsallstringsoverthe
alphabet{0,1}whicharedivisibleby3wheninterpretedinbinary.
RegEx:divisibleby3
Note1:Thereisaone toonecorrespondencebetweenRegularExpressionsandFiniteStateMachines.Ifyou
thinkyoucansolvetheproblemmoreeasilybywritingaregularexpression,goahead.However,astatemachine
approachwillprobablybemoreintuitive,andthesolutionwillbemoreunderstandable.
Note2:Whenscannedfromlefttoright,thestringisinterpretedasmovingfrommostsignificantbittoleast
significant,asexpected.
YouaregivenacomputerthatcancompileandexecuteCprograms.WriteaprograminCtodetermineiftheheap
growsdownandthestackgrowsuponthismachine,orviceversa.
STACKINDEXING
Note:FromanAmazon.cominterview.
4/7/200312:17AM
Willywutangisorganizingamixtapeforhisoverseassweetheart,AprilUnderwood.ThetapewillhavehertopN
songsofalltime.Willywasgoingtodeterminetheorderofthesesongsonhisown,butthenAprilfoundout
abouthislittleproject.Beinganobnoxiouslydemandingwoman,shehasnowgivenWillyapricefunctionfwhich
takesapairofsongs[s i,sj ]asinput,andreturnsarealnumberthatquantifiesexactlyhowgoodsongs j sounds
aftersongs i,inheropinion.(Notethatf([s i,sj ])maynotbeequaltof([sj ,s i]).)
SWEETHEARTMIX
TAPE
WriteanO(n 2 2 n )algorithmforWillywutangthatwilldetermineasongorderwhichmaximizesthetotaltransition
goodnessofthemixtape.(Ifthemaximumisnotachieved,Willywillbedumped.)
Note1:AdaptedfromUCBerkeley,Spring2001FinalExamforCS170(EfficientAlgorithmsandIntractable
Problems).Approximatetimeyouwouldgetforthisproblem:30mins.Storylinebyme:)
Note2:Thisproblemisprettyhard.
4/7/200312:17AM
YouaregivencoordinatesforasetofNpointsona2Dplane.Afterpreprocessingthosepointsinsomemannerof
yourowndiscretion,youaregivenanewpointv=(x,y).NowyourtaskistodeterminewhichoftheoriginalN
pointsisclosestinEuclideandistancetov.Devisethebestalgorithm(lowestbig Ohruntime)youcanto
accomplishthistask.
CLOSESTPOINT
Note1:FromaMojaveNetworkstech interview.
Note2:Exactlyhowmuchtimeyoucanspendpreprocessingisnotspecified,butIthinkit'sreasonabletosayit
accomplishthistask.
CLOSESTPOINT
Note1:FromaMojaveNetworkstech interview.
Note2:Exactlyhowmuchtimeyoucanspendpreprocessingisnotspecified,butIthinkit'sreasonabletosayit
shouldn'tbeexponential.Afterpreprocessing,theinterviewerdidgivearuntimethatyouralgorithmshouldmeet
fordeterminingthepointclosesttov.However,Iwon'tgivethataway,becauseitcouldbetoomuchofahint
furthermore,Iamuncertainifanevenbetterruntimedoesnotexist.
4/10/20032:29PM
Youaregivenapointertothemiddlenodeofasinglylinkedlist.Deletethatnode.
LINKEDLISTDELETE
Note:FromaMojaveNetworkstechinterview.
5/27/20033:21PM
Youaregivennprogramsp 1 ...p n ,eachofwhichtakeanASCIIstringasinput.Eachprogramwilleitheroutputan
ORACLEQUERIES
5/27/20033:15PM
Considerthefollowingproblem,calledQuizTeamScheduling(QTS).YouaregivenasetofNcollegestudents,
eachofwhichhasexpertiseincertainacademicsubjects(e.g.,Entomology,Cinematography,Biology,etc.).There
areatotalofSpossiblesubjects.Knowingwhateachstudentisgoodat,youwanttopartitionthesetof
studentsintotwoteams(notnecessarilythesamesize)suchthateachteamspansallNsubjects.Inother
words,foranygivensubject,thereexistsatleastoneguyineachteamwhichknowsthatsubject.
Soforexample,thefollowingisaYESinstanceofQTSXmarksmeanthestudentinthatrowknowsthesubjectin
thatcolumn:
Entomology
QUIZTEAM
SCHEDULING
Alice
Bob
Carol
Furballogy
Geology
Histology
X
X
Dick
SimplychooseAliceandDickforoneteam,andBobandCarolfortheotherteam.
It'seasytoshowthattheQTSproblemisinNP.Byreductionfrom3SAT(yes3SATspecifically),showthatthe
QTSproblemisalsoNP hard,andthusNPcomplete.
Source:UCBerkeleyCS172(ComputabilityandComplexityTheory)FinalExam,Spring2003.ProfessorAllistair
Sinclair.
5/27/20033:21PM
ConsiderthefollowinglanguageL:
L={|foreveryinputstringw,Mwillhaltwithin1000|w| 2 steps}
Showthatthislanguageisnotrecognizable.(Reducefrom~A[sub]TM[/sub].)
Note1.denotesanencodingofaTuringmachineM.SoLconsistsofallTuringmachinesthatsatisfytheproperty
describedabove.
UNRECOGNIZABLE
LANGUAGE
Note2.|w|denotesthelengthofthestringw.
Note3.~A[sub]TM[/sub]={|MisaTuringMachinethatdoesNOTacceptthestringw}.Soitcouldrejectorloop
forever.
Note4.AlanguageLis[i]recognizable[/i]ifthereexistsaTuringMachineMsuchthatforallstringswinL,running
MonwwillACCEPT.WhenMisrunonastringnotinL,itwilleitherREJECTorloopforever.Contrastthistoa
decidablelanguageL',inwhichthereexistsaTuringMachinethatwillACCEPTforstringsinL',andREJECTfor
LANGUAGE
Note3.~A[sub]TM[/sub]={|MisaTuringMachinethatdoesNOTacceptthestringw}.Soitcouldrejectorloop
forever.
Note4.AlanguageLis[i]recognizable[/i]ifthereexistsaTuringMachineMsuchthatforallstringswinL,running
MonwwillACCEPT.WhenMisrunonastringnotinL,itwilleitherREJECTorloopforever.Contrastthistoa
decidablelanguageL',inwhichthereexistsaTuringMachinethatwillACCEPTforstringsinL',andREJECTfor
stringsnotinL'.Insummary,decidersmusthalt,andrecognizersonlyneedtohaltforstringsinthelanguage.
Source:UCBerkeleyCS172(ComputablityandComplexity)FinalExam,Spring2003
5/27/20033:21PM
CORC++
Writeaprogramthatwillprint"C"ifcompiledasan(ANSI)Cprogram,and"C++"ifcompiledasaC++program.
ThankstoContributors
DavidLau,SiddharthaDoshi,JiongShen,CarlWang,PhoebusChen,AlanLiu,HansenBow,ErnestZhu,ElaineLo,YosenLin,DonBarkauskas,Katherine
Chan,JasvirNagra,TauBetaPi(TBP),EtaKappaNu(HKN),DannyDulai,HisGraceTheDukeOfAnkh MorporkCommanderSirSamuelVimes,Michael
Snyder,DipanK.Ghosh,EricCole,LouisWainwright,BenBardill,PatrickDreker,AutumnLooijen,StephenChampailler,ChristopherKingsLynne,BartSamwel,
KannanRamchandran,NickYee,StevePlimpton,LevsenHendrik,RemcoHartog,[I.M._Smarter_Enyu],PhilipMock,MichaelChang,JonMeilstrup,Ryan
Russell,MattYoung,JonathanHaas,GeoffCanyon,PeterSurda,CoryOndrejka,SatishRao,[gcooper],TedPowell,BraveSirRobin,EricCole,J.A.H.Hunter,
SeanR.Owen,AndrewGlenn,BrucePreston,PeterRatiu,MichaelMendelsohn,RobMahurin,JamesFingas,BryanOrgan,JeroenRutten,Stephen
Montgomery Smith,MarkoLukat,EricYeh,NickHobson,MikeLawther,[anshil],RichardFeynman,DouglasHofstaeder,DacherKeltner,DavidMace,[SAS],
MatthewSchultheis,JohnLeen,AndrewOoi,FolkertHindriks,SteveRagle,DanielFilner,KarlBarrus,MishaKruk,KeithLloyd,DaveMinott,JetteRandlov,Eric
Winger,NathanHellweg,TomVanCourt,ChrisSeaton,MitchellMorris,MichaelStyer,ZameerAndani,JonathanBlow,JeffThompson,JonathonDuerig,Dan
Hanson,GabrielSechan,TomSaxton,[HunterWare],[alsee],JamesAntill,TomBarringer,BartMassey,DavidKrikorian,EricSharkey,[tudorb],KevinDay,Milan
Ramaiya,RobertMerkel,JamesJones,HaimBitner,AdamBarth,OscarLazzarino,DamienFisher,[DrkShadow],ErikBlankendaal,EricSmith,JamesDemmel,
JonathanShewchuk,AlexHarris,MichaelKelley,[Mr._Martingale],KaisenLin,HakanYilmaz,FreddyMercury,JustinRising,MarkoLukat,WilliamKahan,
JeremyRandolph,MichaelSinatra,DavidMesserschmitt,PatrickMasterson,FrederikBonte,RandyWilliams,PietroK.C.,BrettDanaher,DerekAbbott,Ralph
Boleslavsky,Ruidel Negro,[collegemathjournal],[amer.mathmonthly],SpyrosPotamianos,GaryHsieh,[rec.puzzles],StevenRudich,MattLahut,Richard
Reti,PaulSinclair,TimMann,[ucbengineeringnews],LukePercival,AnwisDas,MikeWhite,LouisePoon,JeffreyWilhelm,AnthonyCammon,[BNC],A.Frieze
&D.Sleator,[SWF],TedStevens,FrankWang,DannyP,PatrickSesulka,[towr],ChiSumCheung,RanjitJhala,JacobScott,DavidMcKay,EamonWarnock
(THUDandBLUNDER),KozoMorimoto,AbhijitJoshi,DeveshParekh,AmnonMelzer,MaryLou,LeonidBrouhkis,AllistairSinclair,MarkNewheiser,JocKoelman,
PaulJung,Aryabhatta,ThomasCover,Barukh,Nootch,Eigenray
WilliamWu200204:home|intro|easy|medium|hard|microsoft|cs|putnam|cigs|faq|pros|cons|laff|forum|credits