Professional Documents
Culture Documents
Hacking A Google Interview Practice Questions - Person B: Question: Binary Search Tree Validity
Hacking A Google Interview Practice Questions - Person B: Question: Binary Search Tree Validity
PersonB
Question:BinarySearchTreeValidity
Writeafunctiontodeterminewhetheragivenbinarytreeofdistinctintegersisa
validbinarysearchtree.Assumethateachnodecontainsapointertoitsleftchild,a
pointertoitsrightchild,andaninteger,butnotapointertoitsparent.Youmayuse
anylanguageyoulike.
GoodAnswer:Notethatit'snotenoughtowritearecursivefunctionthatjustchecks
iftheleftandrightnodesofeachnodearelessthanandgreaterthanthecurrent
node(andcallsthatrecursively).Youneedtomakesurethatallthenodesofthe
subtreestartingatyourcurrentnodearewithinthevalidrangeofvaluesallowedby
thecurrentnode'sancestors.Thereforeyoucansolvethisrecursivelybywritinga
helperfunctionthatacceptsacurrentnode,thesmallestallowedvalue,andthe
largestallowedvalueforthatsubtree.Anexampleofthisisthefollowing(inJava):
TherunningtimeofthisalgorithmisO(n).
Question:OddManOut
You'regivenanunsortedarrayofintegerswhereeveryintegerappearsexactly
twice,exceptforoneintegerwhichappearsonlyonce.Writeanalgorithm(ina
languageofyourchoice)thatfindstheintegerthatappearsonlyonce.
GoodAnswer:Setupahashsetthatwewillputtheintegersfromthearrayinto.
Haveasecondvariablethatwillkeepasum.Startgoingthroughthearrayandfor
eachinteger,checktoseeifit'salreadyinthehashset.Ifitisnot,addthatintegerto
thesumandstorethatintegerinthehashset.Ifitisinthehashset,subtractthat
integerfromthesum.Whenthealgorithmfinishesgoingthroughthearray,thesum
variableshouldbeequaltotheintegerwewerelookingfor,sinceitistheonly
numberweneversubtractedfromthesum.ThistakesO(n)timeandO(n)space.
ReallyAwesomeAnswer:XORallthevaluesofthearraytogether!SinceXORis
commutativeandisitsowninverse,eachintegerinthearraythatappearstwicewill
cancelitselfout,andwe'llbeleftwiththeintegerwe'relookingfor.ThistakesO(n)
timeandO(1)space.Wetoldyoubitwisestuffwashandy!
Question:DesignaPokerGame
(Don'taskallthesequestionsatthesametime;askoneafteranother,sincethey
builduponeachother.)Withoutwritinganyactualcode,describeasmuchas
possiblehowyouwoulddesignapokergameprogram.Whatclasseswouldyou
have?Whatrelationshipswouldtheyhavewitheachother?Whatwouldbethe
basicflowoftheprogramandhowwouldthoseclassesplayapart?Ifyouthen
wantedtoaddanewtypeofpokergame(suchasTexasHold'em),howwouldthat
fitintoyourdesign?
Answer:Therearesomanypossibleanswerstothisproblemthatitwouldbe
difficulttosaythatoneansweristhebest.Looktomakesurethattheymake
classestosimulatethebasicpartsofapokergame(perhapsahand,thepot,agame
typeorrules,around,thedeck,etc.).Usinginheritance(subclassinginobject
orientedprogramming)whereitmakessenseisalsogoodforreusabilityand
extendibility.Usingdesignpatters(suchasModelViewController,
Listener/Observer,ortheSingletonpattern)isalsoagoodthing.Themainpointis
forthemtogetusedtothinkingabouthowtheywoulddesignasystem.Most
importantly,theyneedtothinkaboutsimplicity,reusability,andextendibilityin
theirdesign.
Question:LeaderElection
Describeatechniquetoidentifya"leader"amongagroupof10identicalservers
thatareallconnectedtoeveryotherserver.Therearenopriordistinguishing
characteristicsofanyofthemandthesameprogramtoidentifytheleaderstarts
runningonallofthematthesametime.Afterananswerisgiven,askhowmuch
networktrafficitrequiresand,if"ties"arepossible,askhowyoucanbreakties.
GoodAnswer:Haveeachserverwaitarandomamountoftimeandthensay"I'mit."
The"I'mit"announcementistimestamped,andthecomputerthattimestampedits
announcementfirstiselectedtheleader.Thisapproachrequiressendingout9
messages.Ifthereisatie,thecomputerscanrepeattheprocedure.
Notethatotheranswersarepossible,buteverycorrectanswerwilluserandomness
insomeway.
Question:QueueUsingStacks
Describeaqueuedatastructurethatisimplementedusingoneormorestacks.
Don'tworryaboutrunningtime.Writetheenqueueanddequeueoperationsforthe
queue.Youmayuseanylanguageyoulike.
Goodanswer:Youcanusetwostacks:an"incoming"stackandan"outgoing"stack.
Theenqueueanddequeueoperationswouldlooklikethis(inJava):
Stack in;
Stack out;
void enqueue(int value) {
while (!out.isEmpty())
in.push(out.pop());
in.push(value);
}
int dequeue() {
while (!in.isEmpty())
out.push(in.pop());
return out.pop();
}
Question:InstantMessaging
Describeadesignforaninstantmessagingprogramwherethereareseveral
servers,clientsareconnectedtoeachserver,andtheserverscommunicatewith
eachother.Describetheclasses,interfaces,andsoonthatyouwoulduseandhow
youwouldorganizethem.
Answer:Asinthepreviousdesignquestions,thereisnobestanswer.Goodtopicsto
discussarehoweachclientcommunicateswithaserver,howtheserversmaintain
statewiththeotherservers,howstateinformationiscommunicatedbetween
serversandclients,andthespeed/reliabilityoftheirdesign.
Question:MaximalSubarray
Givenanarray,describeanalgorithmtoidentifythesubarraywiththemaximum
sum.Forexample,iftheinputis[1,3,5,2,9,8,6,4],theoutputwouldbe[5,2,
9].
GoodAnswer:Observethatthesumofasubarrayfromelementitoelementjis
equaltothesumofthesubarrayfromelement1toelementjminusthesubarray
fromelement1toelementi1.Ouralgorithmwilliteratethroughthearray.The
algorithmkeepstrackofthesumxoftheelementsnolaterthantheelement.Itwill
alsokeeptrackoftheminimumsumyofthesubarrayfromthefirstelementtoan
elementnolaterthanthecurrentelement.Finally,Itwillalsokeeptrackofthe
subarrayzwiththemaximumsumsofar.Ateachstep,weupdatexbyaddingthe
currentelementtoit.Weupdateybycheckingwhetherx<y;ifso,wesetytobex.
Weupdatezbycheckingwhetheryxisgreaterthanz;ifso,wesetztobeyx.
Forexample,withthesampleinput,ouralgorithmwoulddothefollowing:
Current element | x | y | z
---------------------------------1
| 1 | 0 | 1
-3
| -2 | -2 | 0
5
| 3 | -2 | 5
-2
| 1 | -2 | 5
9
| 10 | -2 | 12
-8
| 2 | -2 | 12
-6
| -4 | -4 | 12
4
| 0 | -4 | 12
Surprisingly,thisproblemisequivalenttothestockmarketproblemdescribedin
handout3.Givenanarraya1,youcan"convert"ittoanarraya2forthestock
marketproblembysettingeachelementa2[i]tobea1[0]+a1[1]+...+a1[i].
Question:ObstacleAvoidance
Givenannxngridwithapersonandobstacles,howwouldyoufindapathforthe
persontoaparticulardestination?Thepersonispermittedtomoveleft,right,up,
anddown.
GoodAnswer:UsetheA*algorithmoranotherfastpathfindingalgorithm.(Itis
describedonWikipedia.)