Algorithm - Amazon - Water Collected Between Towers - Stack Overflow
Algorithm - Amazon - Water Collected Between Towers - Stack Overflow
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Amazon:Watercollectedbetweentowers
IrecentlycameacrossaninterviewquestionaskedbyAmazonandIamnotabletofindanoptimizedalgorithmtosolvethisquestion:
Youaregivenaninputarraywhoseeachelementrepresentstheheightofthetower.Thewidthofeverytoweris1.Itstartsraining.Howmuchwater
iscollectedbetweenthetowers?
Example
Input:[1,5,3,7,2],Output:2units
Explanation:2unitsofwatercollectedbetweentowersofheight5and7
AnotherExample
Input:[5,3,7,2,6,4,5,9,1,2],Output:14units
upvote6down Explanation=2unitsofwatercollectedbetweentowersofheight5and7+
votefavorite 4unitsofwatercollectedbetweentowersofheight7and6+
4 1unitsofwatercollectedbetweentowersofheight6and5+
2unitsofwatercollectedbetweentowersofheight6and9+
4unitsofwatercollectedbetweentowersofheight7and9+
1unitsofwatercollectedbetweentowersofheight9and2.
AtfirstIthoughtthiscouldbesolvedbyStockSpanProblem(http://www.geeksforgeeks.org/thestockspanproblem/)butIwaswrongsoitwould
begreatifanyonecanthinkofatimeoptimizedalgorithmforthisquestion.
algorithm
editedJun25'14at17:51 askedJun25'14at17:09
share|improvethisquestion
Charles Jerky
36.6k105792 973624
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 1/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
7Answers
activeoldestvotes
Oncethewater'sdonefalling,eachpositionwillfilltoalevelequaltothesmallerofthehighesttowertotheleftandthehighesttowertotheright.
Find,byarightwardscan,thehighesttowertotheleftofeachposition.Thenfind,byaleftwardscan,thehighesttowertotherightofeachposition.
Thentaketheminimumateachpositionandaddthemallup.
Somethinglikethisoughttowork:
inttow[N];//nonnegativetowerheights
upvote8down inthl[N]={0},hr[N]={0};//highestleftandhighestright
voteaccepted for(inti=0;i<n;i++)hl[i]=max(tow[i],(i!=0)?hl[i1]:0);
for(inti=n1;i>=0;i)hr[i]=max(tow[i],i<(n1)?hr[i+1]:0);
intans=0;
for(inti=0;i<n;i++)ans+=min(hl[i],hr[i])tow[i];
editedJun25'14at19:26 answeredJun25'14at17:16
share|improvethisanswer
Jerky tmyklebu
973624 9,60931141
Youuseanexcessloop.Thetotalamountofwaterthatcanbeheldovereachtowerisknownassoonasyouhaveprocessedthatrow.Itisnot
2
necessarytofinishthesecondpasstobeginthethirdsinceyouhavealreadylookedahead.AJHendersonJun25'14at17:21
addacomment|
Youcandothisbyscanningthearraytwice.
Thefirsttimeyouscanfromtoptobottomandstorethevalueofthetallesttoweryouhaveyettoencounterwhenreachingeachrow.
Youthenrepeattheprocess,butinreverse.Youstartfromthebottomandworktowardsthetopofthearray.Youkeeptrackofthetallesttoweryouhave
seensofarandcomparetheheightofittothevalueforthattowerintheotherresultset.
Takethedifferencebetweenthelesserofthesetwovalues(theshortestofthetallesttwotowerssurroundingthecurrenttower,subtracttheheightofthe
towerandaddthatamounttothetotalamountofwater.
intmaxValue=0;
inttotal=0;
int[n]lookAhead
for(i=0;i<n;i++)
{
if(input[i]>maxValue)maxValue=input[i];
lookahead[i]=maxValue;
}
maxValue=0;
for(i=n1;i>=0;i)
{
upvote2 //Iftheinputisgreaterthanorequaltothemax,allwaterescapes.
if(input[i]>=maxValue)
downvote
{
maxValue=input[i];
}
else
{
if(maxValue>lookAhead[i])
{
//Makesurewedon'trunofftheotherside.
if(lookAhead[i]>input[i])
{
total+=lookAhead[i]input[i];
}
}
else
{
total+=maxValueinput[i];
}
}
}
answeredJun25'14at17:19
editedJun25'14at17:30
share|improvethisanswer
AJHenderson
575519
addacomment|
Anothersolutionis:
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 2/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Youcantraversefirstfromlefttoright,andcalculatethewateraccumulatedforthecaseswherethereisasmallerbuildingontheleftandalargeroneonthe
right.Youwouldhavetosubtracttheareaofthebuildingsthatareinbetweenthesetwobuildingsandaresmallerthantheleftone.
Similarwouldbethecaseforrighttoleft.
Hereisthecodeforlefttoright.Ihaveuploadedthisproblemonleetcodeonlinejudgeusingthisapproach.
Ifindthisapproachmuchmoreintuitivethanthestandardsolutionwhichispresenteverywhere(calculatingthelargestbuildingontherightandtheleftfor
eachi).
intsum=0,finalAns=0;
idx=0;
while(a[idx]==0&&idx<n)
idx++;
for(inti=idx+1;i<n;i++){
upvote1 while(a[i]<a[idx]&&i<n){
downvote sum+=a[i];
i++;
}
if(i==n)
break;
jdx=i;
intarea=a[idx]*(jdxidx1);
area=sum;
finalAns+=area;
idx=jdx;
sum=0;
}
ThetimecomplexityofthisapproachisO(n),asyouaretraversingthearraytwotimelinearly.SpacecomplexitywouldbeO(1).
answeredNov1'14at9:48
share|improvethisanswer
Yashasvi
397520
addacomment|
Here'sanelegant,efficientsolutioninHaskell
rainfall::[Int]>Int
rainfallxs=sum.filter(>0)$zipWith()deltasxs
deltas=zipWithmin(init$scanlmax0xs)(tail$scanrmax0xs)
upvote0downvote itusesthesametwopassscanalgorithmmentionedintheotheranswers.
answeredJun25'14at18:04
share|improvethisanswer
cdk
4,060538
addacomment|
Ihaveasolutionthatonlyrequiresasingletraversalfromlefttoright.
defstanding_water(heights):
iflen(heights)<3:
return0
i=0#indexusedtoiteratefromlefttoright
w=0#accumulatorforthetotalamountofwater
whilei<len(heights)1:
target=i+1
forjinrange(i+1,len(heights)):
ifheights[j]>=heights[i]:
target=j
break
upvote0
down ifheights[j]>heights[target]:
target=j
vote
iftarget==i:
returnw
surface=min(heights[i],heights[target])
i+=1
whilei<target:
w+=surfaceheights[i]
i+=1
returnw
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 3/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
answeredMar16at1:58
share|improvethisanswer
paranoidandroid
3,31211438
ThiscouldbeO(n^2)intheworstcasethoughgctApr21at18:23
Whatistheworstcaseinthiscase?paranoidandroidMay8at4:51
InthiscaseIbelieveit'sbeaseriesofdescendingheighttowers.Youlookforthenextonethat's>=thecurrent.Soiftherewereinsortedorderfrom
largesttosmallest,thenyou'llseektotheendoftheinputforeachtower,whichwilltaken*(n1)traversalswhichisO(n^2)gctMay8at12:55
addacomment|
Myuglysingletraversalsoln
defwater_collection(buildings):
valleyFlag=False
water=0
pool=[]
fori,buildinginenumerate(buildings):
if(i==0):
lastHill=building
else:
iflastHill<=buildingori==len(buildings)1:
minHill=min(building,lastHill)
print("Hill{}toHill{}".format(lastHill,building))
summ=0
fordropinpool:
summ+=minHilldrop
water+=minHilldrop
upvote0downvote
print("Collectedsum{}".format(summ))
pool=[]
valleyFlag=False
lastHill=building
eliflastHill>buildingandvalleyFlag==False:
pool.append(building)
valleyFlag=True
eliflastHill>buildingandvalleyFlag==True:
pool.append(building)
print(water)
answeredApr10at21:28
share|improvethisanswer
cozos
597
addacomment|
Here'smyattemptinjQuery.Itonlyscanstotheright.
Workingfiddle(withhelpfullogging)
vara=[1,5,3,7,2];
varwater=0;
$.each(a,function(key,i){
if(i>a[key+1]){//ifnexttowertorightisbigger
for(j=1;j<=a.lengthkey;j++){//numberofremainingtowerstotheright
if(a[key+1+j]>=i){//ifanytowertotherightisbigger
for(k=1;k<1+j;k++){
//addtowater:thedifferenceofthefirsttowerandeachtowerbetweenthefirsttoweranditsbiggertower
upvote0downvote water+=a[key]a[key+k];
}
}
}
}
});
console.log("Water:"+water);
answeredMay20at22:32
share|improvethisanswer
Matt
858
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 4/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmoraskyourownquestion.
asked 1yearago
viewed 2568times
active 1monthago
Lookingforajob?
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Geek(s)
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 5/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
myglamm.com
Mumbai,India/relocation
javaios
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
152PeopleChatting
JavaScript
6hoursagoCapricaSix
afonsomatos:
ivarni:
rlemon:
Awal
Caprica
Sterling
ssube:
6 6 6 Garg: Six:Archer:
6
PHP
6hoursagordlowrey
Fabor:
bwoebi:
Enerdlowrey:
ircmaxell:
Jimbo:
Ronald
6 6 Mihai: 6 6 6 Ulysses
Related
6
Tryingtobuildalgorithmforoptimaltowerplacementinagame
1
towerofboxes(stackingcubes)
529
Findanintegernotamongfourbilliongivenones
3
howmanydifferentsequencesthatthedifferencebetweeneveryadjacentpairofnumbersislargerthan1
2
Minimizethemaximumdistancebetweenanyadjacentstations
1
SPOJWATER:DevelopingaBFSalgorithm
3
AlgorithmforHumanTowering
8
TheMaximumVolumeofTrappedRainWaterin3D
2
Countingnumberofdays,givenacollectionofdayranges?
4
Algorithmtosolveforwateraccumulationgivenbuildingheights
HotNetworkQuestions
Drawarrowinamindmap
Needhelprecreatingcrazycolors/materialfromexample
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Whyshouldakeybemadeexplicit?
Whydosocksstink?
ImageOpensasLayer0ratherthanBackground
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Troublewithterminatinga<apex:pageBlockSection>
Jumpingcarwithtoomanyamps?
howcanItaketotalminutesfromtime?
Whatisatemporarysolutionforadamagedcarbody?
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Ciertasconjugacionesverbalesnoconvencionales
Whyadding"incolour"whenreferringto"WizardofOz"?
Howtodrawsequenceofshapeswitharrowsandtext
zero,zerosorzeroes?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Whatistheoriginofthisphotoofanunexplodedbomb?
WhoinventedStarTreksideburnsandwhy?
Packagetodonotes:HowcanIchangethetextcolor?
HowdoIupgradefromGPLv2toGPLv3?
Alarmclockprinting
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. Photography 1. English
1. Stack 1. Programmers
2. ScienceFiction Language&
Overflow 2. Unix&Linux 1. Database
&Fantasy Usage
2. ServerFault 3. AskDifferent Administrators 1. Mathematics
3. GraphicDesign 2. Skeptics 1. StackApps
(Apple) 2. Drupal 2. CrossValidated
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 6/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
3. SuperUser 4. WordPress Answers 4. SeasonedAdvice 3. MiYodeya (stats) 2. MetaStack
4. Web Development 3. SharePoint (cooking) (Judaism) 3. Theoretical Exchange
Applications 5. Geographic 4. User 5. Home 4. Travel ComputerScience 3. Area51
5. AskUbuntu InformationSystems Experience Improvement 5. Christianity 4. Physics 4. Stack
6. Webmasters 6. Electrical 5. Mathematica 6. PersonalFinance 6. Arqade(gaming) 5. MathOverflow Overflow
7. Game Engineering 6. Salesforce &Money 7. Bicycles 6. more(7) Careers
Development 7. AndroidEnthusiasts 7. more(14) 7. Academia 8. Roleplaying
8. TeX 8. InformationSecurity 8. more(10) Games
LaTeX 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Amazoninterview:Timestampsorting:Findthethreepagesubsetsequence
repeatedmaximumnumberoftimes[closed]
TheAmazoninterviewquestionis:
Givenalogfilecontaining(User_Id,URL,Timestamp)usercannavigatepagefromonetotheother.Findthethreepagesubsetsequence
repeatedmaximumnumberoftimes.RecordsaresortedbyTimestamp.
Ifoundthisquestionfromthisredditthread.
Theposterwrote:
"Givenalogfilecontaining(User_Id,URL,Timestamp)usercannavigatepagefromonetotheother.Findthethreepagesubsetsequence
repeatedmaximumnumberoftimes.RecordsaresortedbyTimestamp."
upvote1down
(Although,Iwasn'ttolduntillateintheinterviewthefileissortedbytimestamp.OneofthefirstthingsIhadaskedwasifthelogwas
votefavorite
sorted,andmyinterviewersaidno.)
2
IdothinkIgaveitmyallIseemedtohavebeenontherighttrackusingahashmap.IalwaysletmyinterviewknowwhatIwasthinking
andgavepossibleoutcomes,timecomplexities,etc.
Iamnotsurehowtoapproachthisproblem.Whatdoes"Findthethreepagesubsetsequencerepeatedmaximumnumberoftimes"mean?Andifthe
questiondidn'tsay"RecordsaresortedbyTimestamp"(ashappenedtotheposter),thenhowwouldthataffecttheproblem?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 7/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
algorithmdesignamazon
askedJan16'14at7:36
share|improvethisquestion
user3184017
3014
closedasprimarilyopinionbasedbyKenWhite,Jeroen,Benjamin,jww,devnullJan17'14at12:51
Manygoodquestionsgeneratesomedegreeofopinionbasedonexpertexperience,butanswerstothisquestionwilltendtobealmostentirelybasedonopinions,rather
thanfacts,references,orspecificexpertise.Ifthisquestioncanberewordedtofittherulesinthehelpcenter,pleaseeditthequestion.
Simplethought:Groupbyuserid,thensortbytimestamp.Findwhichisthemostrepeatedpatternof3pages.PhamTrungJan16'14at8:03
addacomment|
1Answer
activeoldestvotes
With"threepagesubsetsequence"Iamguessingtheymeanthethreepagesmustbenexttoeachother,buttheirinternalorderdoesnotmatter.(ABC=CAB)
publicTuple<string,string,string>GetMostFrequentTriplet(
IEnumerable<LogEntry>entries,
TimeSpan?maxSeparation=null)
{
//Assuming'entries'isalreadyorderedbytimestamp
//StorethelasttwoURLsforeachuser
varlastTwoUrls=newDictionary<int,Tuple<string,string,DateTime>>();
//CountthenumberofoccurencesofeachtripletofURLs
varcounters=newDictionary<Tuple<string,string,string>,int>();
foreach(varentryinentries)
{
Tuple<string,string,DateTime>lastTwo;
if(!lastTwoUrls.TryGetValue(entry.UserId,outlastTwo))
{
//NopreviousURLs
lastTwoUrls[entry.UserId]=Tuple.Create((string)null,entry.Url,entry.Timestamp);
}
//(comparisonwithnull=>false)
elseif(entry.TimestamplastTwo.Item3>maxSeparation){
//TreatalongerseparationthanmaxSeparationastwodifferentsessions.
lastTwoUrls[entry.UserId]=Tuple.Create((string)null,entry.Url,entry.Timestamp);
}
else
{
//OneortwopreviousURLs
if(lastTwo.Item1!=null)
{
//TwopreviousURLs;Threewiththisone.
//SortthethreeURLs,sothattheirinternalorderwon'tmatter
varurls=newList<string>{lastTwo.Item1,lastTwo.Item2,entry.Url};
urls.Sort();
varkey=Tuple.Create(urls[0],urls[1],urls[2]);
//Incrementcount
upvote intcount;
1down counters.TryGetValue(key,outcount);//setsto0ifnotfound
vote counters[key]=count+1;
accepted }
//Shiftinthenewvalue,discardingtheoldestone.
lastTwoUrls[entry.UserId]=Tuple.Create(lastTwo.Item2,entry.Url,entry.Timestamp);
}
}
Tuple<string,string,string>maxKey=null;
intmaxCount=0;
//Findthekeywiththemaximumcount
foreach(varpairincounters)
{
if(maxKey==null||pair.Value>maxCount)
{
maxKey=pair.Key;
maxCount=pair.Value;
}
}
returnmaxKey;
}
Thecodegoesoverthelogentriesandseparatesthestreamforeachuser.ForeachthreeconsecutiveURLsforanyuser,weincrementthecountforthattriplet.
Sincetheorderofthethreepagesarenotimportant,wereordertheminaconsistentway,bysorting.Intheend,wereturnthetripletthathasthehighestcount.
SinceweonlyneedthelastthreeURLsforeachuser,weonlystoretheprevioustwo.CombinedwiththecurrentURL,thatmakesthetripletweneed.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 8/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
FornURLs,muniqueURLs,uusers,andssinglevisitusers,themethodwilldo2n2u+s(=O(n))dictionarylookups,andstoreuptoC(m,3)+u(=O(m3
+u))tuples.
Edit:Infersessionsbythedurationbetweenrequests.IftheydifferbymorethanmaxSeparation,thenewrequestistreatedasthefirstfromthatuser.
answeredJan16'14at23:43
editedMar14'14at11:05
share|improvethisanswer
MarkusJarderot
41.7k77599
Thankyoufortheexplanationandcode!Yourcodeiscommentedprettywell,butwouldyoualsoexplaininwordsthegeneralideaofyouralgorithmand
discussitsefficiency?Thiswouldmakeyouranswerevenmorehelpful.Thanks!user3184017Jan17'14at3:06
ThisdoesnothandleacommoncasewheretheURLSmayberepeated.AssumeascenariowhereauseropenstheHomepageandthengoestotheProduct
page.HethenclosesthesessionandopensthewebsiteagainonaseparatedayonwhichhegoesfromHomepagetotheCartpage.Nowbasedonyour
solution,thelastTwotuplewouldcontainhomepageandproductpage.Nowonthesecondday(whentheseconddayentriesareread),thetuplefortriplet
wouldcontain(Homepage,productpage,Homepage),whichmightleadtofallaciesPawanMar14'14at10:40
Intheabovescenario,Ibelievetheentriesshouldbeignored.PawanMar14'14at10:43
@Pawan,SincetherearenosessionIDsinthelogfile,youwouldhavetorelyonthetimestamps.Seemyedit.MarkusJarderotMar14'14at11:05
Thanks,Iguessthatworks.IfwedonthaveavalueformaxSeparation,thenwecanalsoaccomplishthesamebyjustcheckingthecurrentpagevalue
againstthevaluesinthelastTwoUrlstuple.Say,ifthelasttwourlswere{Homepage,ProductPage}andthelatestentryisagainhomepage,thenwecan
justcreateanewlastTwoUrlsentrywith{Homepage}PawanMar14'14at11:20
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdesignamazonoraskyour
ownquestion.
asked 1yearago
viewed 575times
active 1yearago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Related
28
Findexistenceofnumberinasortedlistinconstanttime?(Interviewquestion)
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
11
InterviewquestionFindingnumbers
3
Findthelargestsubsetofitwhichformasequence
5
findnumberthatdoesnotrepeatinO(n)timeO(1)space
4
Givenasortedarray,findthemaximumsubarrayofrepeatedvalues
2450
Pairsocksfromapileefficiently?
1
AmazonInterviewMaximumNumberofPeoplepresentatanEventatanytime
2
Findthetimeperiodwiththemaximumnumberofoverlappingintervals
0
findingasetofsubsetshavingmaximumweights
HotNetworkQuestions
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Ciertasconjugacionesverbalesnoconvencionales
BenefitsofSETTRANSACTIONISOLATIONLEVELREADUNCOMMITTED
Alarmclockprinting
Patchingabinarywithdd
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 9/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Shouldmy(sequential)collectionstartatindex0orindex1?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Whatistheoriginofthisphotoofanunexplodedbomb?
CanIflywithagoldbar?
What'sthebestwaytoinvestformakingregulardonations?
PythonLabelExpression?ArcGIS10.3.1
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
WhoinventedStarTreksideburnsandwhy?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Clientwantsfontaslogo
Whycan'tanonabeliangroupbe75%abelian?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
HowcanIcheckifmyfunctionprint/echo'ssomething?
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
Needhelprecreatingcrazycolors/materialfromexample
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
AmazonInterviewDesignMeetingScheduler
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 10/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Lately,Itookaninterview.Iwasaskedtodesignameetingscheduler,justlikeintheMicrosoftoutlookcalendarorthegmailcalendar.Iproposed
thatIwillcreateanarrayof48foreachday.Every30minrepresentingthearrayentry.
Ihavetomakesurethatthenextappointmentdoesnotcollidewithapreviousmeeting.
Mysolutionworksfinebutitwastestoomuchmemory.
CananyonepleasetellmehowdoIfindabettersolutiontodetectcollisionformeetings.
upvote6down
votefavorite Idon'tknowallthemeetingsatthebeginning.Theywillbeaddedrandomlylater.
3
Thanks,
algorithmdesign
askedMar1'13at3:49
editedMar1'13at4:04
share|improvethisquestion
user1540945
2441214
Itdidn'tincluderecurringschedules?LikeEveryweekdaymorning09:0015minutesscrum.EveryFriday16:00teamgatheringforateaat
canteen?SparKotMar1'13at11:48
Theyaskedmetodesigncompletelybymyself.Noinputwasprovided.user1540945Mar1'13at22:51
addacomment|
5Answers
activeoldestvotes
Startwithanemptylistofmeetings,eachwithastart_timeandduration.Wewillmaintainasortedlistofmeetingsbystart_time.
Toaddameetingtothelist,findwhereitbelongsinthelistbyperformingabinarysearch.Onceyoufindtheindex,performtwocheckstoavoida
collisionconsiderthemeetingsimmediatelybeforeandafterthetobeinsertedmeeting(iftheyexist).
1. Assertthebeforemeeting'sstart_time+durationdoesnotexceedthenewmeeting'sstart_time.
2. Assertthenewmeeting'sstart_time+durationdoesnotexceedtheaftermeeting'sstart_time.
Iftheassertionsaresatisfied,addthemeetingtothelist.
upvote6
downvote ThisaddoperationtakesO(log(list_size))time.
Note:Thisapproachassumesthataddingameetingwithanoverlapisaninvalidoperation.Ifoverlapsareallowedtoexist,youwouldhavetocheck
beyondthemeetingsimmediatelypreceding/subsequentthenewmeeting.
answeredMar1'13at3:53
editedMar1'13at4:15
share|improvethisanswer
cheeken
10.4k21626
Iguessthatiforgottomentionit.Idonthaveaccesstoallthemeetingsatfirst.user1540945Mar1'13at3:54
I'veamendedmyanswerbasedonyouredit.cheekenMar1'13at4:15
Thanks...Prettycoolapproach.SomethingsimilartoB+tree.:):)user1540945Mar1'13at22:52
AddinginasortedlistwouldtakeO(list_size)time.AmImissingsomething?damnedMar5'14at14:55
@damnedUsingabinarysearch,addoperationscanbeperformedinO(log(list_size))time.See:
en.wikipedia.org/wiki/Binary_search_tree#InsertioncheekenMar5'14at15:29
|show2morecomments
WecanhaveaTreestructure(BST)forstoringtherequests(Requestobject:starttime/endtime/date/priorityetc.).Bydoingso,add/delete/search/update
operationscanbeachievedbyO(height_of_tree).Ifweuseabalancedtree,wecangettheoptimizedrunningtime.i.e.O(logn)foreachoftheabove
mentionedoperations.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 11/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ThisapproachisbetterthanthesortedlistapproachasthelistisbackedbyanfixedsizedarrayincaseofArrayListwhichtakesO(n)forcopyingtheelements
upvote1 fromoldarraytonewarray.Ifweusealinkedlist,binarysearchisnotpossible.
down
vote Commentswelcome!
answeredFeb21at23:07
share|improvethisanswer
Vin
457
addacomment|
whiletheuseofasortedarrayandbinarysearchisefficient,pleasenotethatinsertwilltakeo(n)assumingnocollisionisfoundsincethearrayneedsto
slidethemeetingsover.Notsureifthisisthemostoptimalsolution.
upvote0 answeredJan9'14at8:32
downvote
share|improvethisanswer
Kelvin
5828
addacomment|
Ifthesortedlistisanarray,IbelievetheaddoperationwilltakeO(n)sinceyouhavetoshiftthemeetingthatstartafterthetobeinsertmeeting.
answeredJan13'14at23:03
upvote0downvote
share|improvethisanswer
Kelvin
5828
addacomment|
Hereismysolutionwhichinsertsusingbinarysearch
publicclassMeetingScheduler{
staticclassMeetingimplementsComparable<Meeting>{
DatestartTime;
DateendTime;
intduration;
publicstaticfinalintMINUTE=60000;
//durationinminutes
Meeting(DatestartTime,intduration){
this.startTime=startTime;
this.duration=duration;
this.endTime=newDate(startTime.getTime()+(MINUTE*duration));
@Override
publicintcompareTo(Meetingo){
if(this.endTime.compareTo(o.startTime)<0){
return1;
}//endtimeisbeforetheother'sstarttime
if(this.startTime.compareTo(o.endTime)>0){
return1;
}////starttimeisaftertheother'sendtime
return0;
}
@Override
publicStringtoString(){
return"meeting{"+
"from"+startTime+
",minutes="+duration+
'}';
}
}
privateList<Meeting>meetings=newArrayList<Meeting>();
publicMeetingbookRoom(Meetingmeeting){
if(meetings.isEmpty()){
meetings.add(meeting);
returnnull;
}else{
upvote0downvote intpos=Collections.binarySearch(meetings,meeting);
if(pos>0){
meetings.add(pos1,meeting);
returnnull;
}else{
returnmeetings.get(pos);
}
}
}
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 12/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
publicList<Meeting>getMeetings(){
returnmeetings;
}
publicstaticvoidmain(String[]args){
MeetingSchedulermeetingScheduler=newMeetingScheduler();
Meeting[]meetingsToBook=newMeeting[]{
//October3rd2014
newMeeting(newDate(20141900,101,3,15,00),15),
newMeeting(newDate(20141900,101,3,16,00),15),
newMeeting(newDate(20141900,101,3,17,00),60),
newMeeting(newDate(20141900,101,3,18,00),15),
newMeeting(newDate(20141900,101,3,14,50),10),
newMeeting(newDate(20141900,101,3,14,55),10)
};
for(Meetingm:meetingsToBook){
MeetingoldMeeting=meetingScheduler.bookRoom(m);
if(oldMeeting!=null){
System.out.println("Couldnotbookroomfor"+m+"becauseitcollideswith"+oldMeeting);
}
}
System.out.println("meetingsbooked:"+meetingScheduler.getMeetings().size());
for(Meetingm:meetingScheduler.getMeetings()){
System.out.println(m.startTime+">"+m.duration+"mins");
}
}
}
answeredDec18'14at4:36
share|improvethisanswer
CarlosP
5911823
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 13/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdesignoraskyourown
question.
asked 2yearsago
viewed 1717times
active 4monthsago
Lookingforajob?
SeniorTechnicalConsultant/DeveloperInnovation
iSpace(aConnollyiHea
Hyderabad,India/remote
scalaakka
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Related
12
Whatistheoptimalalgorithmdesignforawatersavingurinal?
0
GeneralDesignQuestion
2
4programdesigninterviewquestions
1
Interviewquestion:Developanapplicationthatcandisplaytrialperiodexpiresafter30dayswithoutexternalstorage
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
1
AmazonInterviewMaximumNumberofPeoplepresentatanEventatanytime
4
LottoTicketCoverageFromAlgorithmDesignManual?
1
Amazoninterview:Timestampsorting:Findthethreepagesubsetsequencerepeatedmaximumnumberoftimes
0
Designapproachforfeeds
1
Designasystemtokeeptopkfrequentwordsrealtime
HotNetworkQuestions
Multiplypurefunctionwithscalar
WhycanfunctionallanguagesbedefinedasTuringcomplete?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 14/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
zero,zerosorzeroes?
Clientwantsfontaslogo
ALN*NTicTacToeGame
Passfilenamefrombashtopython
Justifyingsuboptimalresearchqualitybylackofsupervision
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Whatwereshoesolesmadefrominpreviousages?
Nicelytypesettingverbatimtext
Whatisatemporarysolutionforadamagedcarbody?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Isturninggraphitecarbonintodiamondindustriallydoable?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Howtoprotectaspaceelevatoragainstterrorism
Whyweren'ttheWeasleysapartoftheOriginalOrder?
Drawarrowinamindmap
FindingoutifawordisanAnagramofanother
Howtodecidewhetherastoryisworthwriting?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Jumpingcarwithtoomanyamps?
Packagetodonotes:HowcanIchangethetextcolor?
HowdoIupgradefromGPLv2toGPLv3?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 15/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
AmazonInterviewMaximumNumberofPeoplepresentatanEventatany
time
AssumeIhavealistofpeoplewiththeirarrivalanddeparturetimeataneventthathappenedinthepast.
Mytaskistofindoutthemaximumnumberofpeoplepresentintheeventatanytime?Iamnotgivenquerytime.
ai=Arrivaltimeofpersoni
di=Departuretimeofpersoni
Ihavealistofpairslike(a1,d1),(a2,d2),(a3,d3)....(an,dn)...It'snotinadatabase.
enterimagedescriptionhere
Inthisproblemwecanseethatthemaximumnumberofpeopleattheeventis3.
Sointhiseg.wehavetwosolutionstotheproblemwithsize3.{b,d,e},{j,h,i}.Ijustwanttoknowthenumber3.
MyApproaches:
i.Createanarrayofsize=LastDepartureTimeFirstarrivaltime.Andkeepincrementingthecountofthatarray.
ii.Itriedtosortthepeoplebytheirstarttimes.Andkeepjumpingtothestarttimeofthenextperson.AfterthatIamlost.HowshouldIproceed.
Thanks
upvote1down @ypnos://Sortedthedatabothontimestamps.
votefavorite
1 intcount=0;
intmax=0
char[]arr={a1,a2,d1,a3,a4,d3,d2,}likethis..
for(inti=0;i<arr.length;i++)
{
if(arr[i].startswith('a'))
{
count++;
if(count>max)
{
max=count;
}
}
else
{
count;
}
}
algorithmdesign
askedMar1'13at23:48
editedMar2'13at10:07
share|improvethisquestion
user1540945
2441214
Asegmenttree(en.wikipedia.org/wiki/Segment_tree)cansolvethisproblem,butyoumaynotbeinterestedinimplementingone...Omri
BarelMar1'13at23:54
Bytheway,thetitlesays"Maximum"butthequestiondoesn'tmentionthatareyouinterestedinageneralqueryoronlyinthemaximum?
2
OmriBarelMar1'13at23:55
Evenwithyourclarification,theanswerwouldn'tbedifficultifyousortyourdatabyarrivaltime.Ofcourse,itdependsonhowyourcodeis
called.DigCamaraMar1'13at23:56
IamjustinterestedintheMaximumpeopleattheeventatanytime.user1540945Mar1'13at23:56
Speakingofcode,isthereany?Thelanguagethatyouchoosetowritethisinisgoingtodrasticallyimpacttheanswer(suchaswhat
1
libraries/objecttypesareavailableNumPy,etc.)DaveLasleyMar1'13at23:57
|show3morecomments
4Answers
activeoldestvotes
Firstyoucreateasortedlistwitharrivalanddeparturetimes.Itisasinglelistforbothevents,andeacheventconsistsofatimestamp(whatisthesorting
key)andaboolean(arrivalordeparture).
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 16/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Newsolution(findthemaximum):
Thenyoucaniteratethroughyourlist,rememberthecurrentnumberateachentryandincrement/decrementitaccordingly,whilealsoupdatingyour
maximumnumberifappropriate.
Sorting:O(NlogN),findingthemax.number:O(N)
Oldsolutionduetobadwordinginthequestion(queryattimeX):
upvote4
downvote Afteryouhavethatlist,youcreateamapthathastimestampsaskeysandthenumberofpeopleatthatcurrenttimestampasdata.Tocreatethat,yougo
accepted throughyoursortedlist,rememberthecurrentnumberateachentryandincrement/decrementitaccordingly,whilealsoaddingtheelementtoyourmap.
Nowthatyouhavethemap,youcantriviallyfindtherightnumberbysearchingfortheelementinthemapleftofyourquerytimestamp.
WithamapImeanabinarytree,orwhatisthebaseofstd::map.Btw.std::mapprovidesyouwiththelower_bound()functiontodothat(ref).
However,itisnothardtoimplementabinarytreeyourself.Nowforthecostsoftheoperation:O(logN)perentry,O(logN)perquery.
answeredMar1'13at23:58
share|improvethisanswer
ypnos
24.8k55289
HowdoIkeepincrement/decrementit.Ineedtoscanthroughtheentirelisttofindoutifitisstillcollidingornot.user1540945Mar2'13at0:13
No,theideaisthatyouhavealistofincrementeventsanddecrementevents.Youdon'tcarewhichpersonisdeparting,onlythatanybodyisdeparting.
1 That'swhyyougofrom(a1,d1),(a2,d2),(a3,d3)....(an,dn)to(a1,d1,a2,d2,a3,d3,..,an,dn).Thenyousortthatarrayaccordingtotimestamps,so
youwillgetsthlikea1,a2,d1,a3,a4,d3,d2,...andsoon.ypnosMar2'13at0:25
SupercoolIdea.Thankssomuch.Finallysomebodywasabletounderstandmyquestionandnailthesolution:):)Justtoclarify,youaresayingthe
following:intcount=0intmax=0char[]arr={a1,a2,d1,a3,a4,d3,d2,}likethis..for(inti=0i<arr.lengthi++){if(arr[i].startswith('a')){
count++if(count>max){max=count}}{count}}user1540945Mar2'13at0:27
Ihavewrittenthecodeaboveinthequestion.Itwouldbegreatifyoucouldpleasehavealookintoit.user1540945Mar2'13at0:33
1 looksalright,withamissing"else".ypnosMar2'13at9:08
addacomment|
Iterateoverthelist,testifthegiventimetisbetweenarrivalanddepartureofthecurrentpairandincrementacounterifthatisthecase.Afterwardsyou
shouldhavethecorrectnumberinyourcounter.Pseudocode:
giventimeT
givenlistof(arrival,departure)pairsL
c=0
foreachpair(A,D)inL
upvote0 ifA<TandT<D
downvote c+=1
Notethatthisisnotthemostoptimalsolution...storingyourdatainastructuremoresuitableforqueryingwillenablemoreefficientsolutions.
answeredMar1'13at23:55
share|improvethisanswer
Korijn
716313
Overhere,IassumethatyouareclaimingthatyouknowthetimeT.Butwedon'tknowthat.user1540945Mar2'13at0:01
addacomment|
InSQL?
SELECTcount(id)FROMattendeeWHEREa_time<'2013030112:12'AND(d_time>'2013030112:12'ORd_timeISNULL)
upvote0downvote answeredMar1'13at23:55
share|improvethisanswer
edoceo
16615
ItsnotinSQL:(user1540945Mar2'13at0:22
addacomment|
Isthisinadatabase?Ifso,youjustselecttherowswitharrivaltime<now<departuretime.
Thisisasimplethingtodo,butweneedtoknowwhatdatastructureyouareusingtoholdthedatatogiveaspecificsolution.
Theapproachissimple:Anarrayofdictionarieswhereeachdictionaryconsistsofarrival:valueanddeparture:value.Thenatanygiventime,youiteratethe
upvote0 arrayandif:arrival<now<departure==TRUEyouincrementacounter.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 17/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
downvote Done.
answeredMar1'13at23:51
editedMar2'13at0:00
share|improvethisanswer
HackyStack
2,74521024
No.Thisisnotstoredinadatabase.Ihaveupdatedthequestion.Pleasehavealookatitonceagain.Thanks.user1540945Mar1'13at23:52
Seemyupdatedanswer.HackyStackMar2'13at0:01
@HackyStack:Whyhaveanarrayofdictionaries?Healreadyhasalistofpairsasinput,whichisexactlythesame.Yoursolutionhascomplexityof
O(n)foreachquery,buttheoptimalsolutionisO(logN)foreachquery.OmriBarelMar2'13at0:07
@HackyStack:Idon'thaveanyquerytime.Ihaverephrasedthequestiononceagainwithanexample.user1540945Mar2'13at0:21
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdesignoraskyourown
question.
asked 2yearsago
viewed 939times
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 18/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
active 2yearsago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Related
3
Howtodetermineitemataindexinpattern
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
7
Isthereanywaytomakeaprobabilisticconstanttimeequalitycheckoncollectiontypes?
3
Existenceofapermutationunderconstraints(InterviewStreetManipulativeNumbers)
0
Howtocalculatetheminimumnumberofpersonpresentduringtwotimes
6
AmazonInterviewDesignMeetingScheduler
0
Startandendtimeshowmanyconcurrenteventsperhour/day/weeketc
1
HowtodeterminethemaximumofeventstowhichIcanapply?
1
Amazoninterview:Timestampsorting:Findthethreepagesubsetsequencerepeatedmaximumnumberoftimes
1
Maximumnumberthatcanbeformedfromthegivendigits
HotNetworkQuestions
Removestaticobjectsfromanimagesequence
Doblockingcreatureshealbacktofullbetweenphases?
zero,zerosorzeroes?
Troublewithterminatinga<apex:pageBlockSection>
WhydosomepeoplerefertoLinuxasGNU/Linux?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
Shouldmy(sequential)collectionstartatindex0orindex1?
Nicelytypesettingverbatimtext
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
Whatistheoriginofthepowericon?
HowcanIcheckifmyfunctionprint/echo'ssomething?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
WhoinventedStarTreksideburnsandwhy?
MementoVivereMomentumMori
DoesCIDRreally"doaway"withIPaddressclasses?
CanICultureBombfaraway?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Functionsthataretheirowninversion.
What'sanexpressionforacunninglyfakefriend?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Needtostartareligionwithapredefinedselfdestruct
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. WordPress
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 19/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
4. Web Development Answers 4. SeasonedAdvice (Judaism) (stats) Exchange
Applications 5. Geographic 3. SharePoint (cooking) 4. Travel 3. Theoretical 3. Area51
5. AskUbuntu InformationSystems 4. User 5. Home 5. Christianity ComputerScience 4. Stack
6. Webmasters 6. Electrical Experience Improvement 6. Arqade(gaming) 4. Physics Overflow
7. Game Engineering 5. Mathematica 6. PersonalFinance 7. Bicycles 5. MathOverflow Careers
Development 7. AndroidEnthusiasts 6. Salesforce &Money 8. Roleplaying 6. more(7)
8. TeX 8. InformationSecurity 7. more(14) 7. Academia Games
LaTeX 8. more(10) 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
amazoninterviewprob
Thereisabigfileofwordswhichisdynamicallychanging.Wearecontinuouslyaddingsomewordsintoit.Howwouldyoukeeptrackoftop10trendingwords
ateachmoment?
upvote IfoundthisquestioninablogbutIcouldn'tunderstandtheanswer.Theansweris:hashtable+minheap
13
down Iunderstandwhyhashtablebutnotminheappart,cansomeonehelpme?
vote
favorite algorithm
9 editedAug28'12at0:13 askedAug26'12at19:04
share|improvethisquestion
Charles rplusg
36.6k105792 1,17431741
YouusuallywantaminheaptokeeptrackofthehighestNanswers,becauseateachstageyouhaveacandidateanswerandyouwanttoknowifitisbetter
thantheworstanswerintheminheapifitis,removetheworstanswerofthetopNfromtheminheapandinsertthecandidate.Havingtheintuitive
2 maxheapmakesitveryeasytopickouttheverybestanswer,butwhendecidingwhethertoacceptanewcandidateanswer,thisisnotwhatyouwant.(Just
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 20/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
rememberthatwhenyouextractthetopNanswersattheend,theywillcomeoffwiththeworstofthoseNfirst).mcdowellaAug26'12at19:46
addacomment|
2Answers
activeoldestvotes
Ifit'stop10trendingwordsthenyoushoulduseamaxheapalongwithahashtable.
Whenanewwordisaddedtothefilethen:
Createanewelementxwithx.key=wordandx.count=1.
Addxtothehashtable.O(1).
Addxtothemaxheap.O(lgn).
Whenanexistingwordisaddedtothefilethen:
upvote7 Findxinthehashtable.O(1).
down Updatex.counttox.count++.
vote
accepted Whenthereisaneedtoretrievethetop10trendingwordsthen:
Extract10timesfromthemaxheap.10*O(lgn)=O(10*lgn)=O(lgn).
Asyoucansee,alltheneededoperationsaredoneinatmostO(lgn).
answeredAug27'12at5:38
editedNov11'13at7:04
share|improvethisanswer
AviCohen
1,2501819
youwouldwanttouseaminheap:whenanexistingwordthat'snotintop10becomesatop10,removingtheminwouldbeconsistenttime.aw626
4
Dec8'12at17:01
"Updatex.counttox.count++inthemaxheap"shouldn'tthatbeO(n)?Youhavetofirstfindxinthemaxheap,butyoudon'tknowwhereitis.Onceyou
1
findit,incrementingitandbubblingitupisaO(lgn)operation.BConNov10'13at20:13
@BCon:Sincemaxheapandhashtablepointtothesameelementxthenthereisnoneedtofinditagaininthehashtable.Iwillfixthat,thanks.Avi
CohenNov11'13at7:04
YouhavetouseaMinHeap,notMaxHeap.So,ifyouhavekitemsintheheap,thepeekoftheheapisthesmallestandeveryoneelse(k1)islarger
thanthepeek.Now,ifanewwordwithcount>peekcomesin,wewanttoextractthemin(O(logk))andinsertthenewitem(O(logk)).Ifnewitemhas
5
countsmallerthanpeek,thatmeansitissmallerthananyotheritemintheheap(asit'saMinHeap).Wejustdiscardthatwordasthatwillnotbeapartof
topk.AmitJan2'14at22:10
@Amit:Youareright.Whynotaddyoursolutionasanotherone?AviCohenJan3'14at8:00
|show2morecomments
Ifyouonlywanttokeepthetop10,usingamaxheapisoverkill.Keepingthe10entriesinasortedarraywillbesimplerandfaster.
Forsorting,justuseinsertionsortstartingfromthebottomofthearray.Youwillhavetocheckforthecasewherethecandidateisalreadyonthetopten
up updatingitspositionifrequired.
vote1
down answeredAug28'12at7:05
vote
share|improvethisanswer
salva
5,99321441
1 ifyoudon'tkeeptheotherentries,nonewentrywillevermakeittothetop10.KarolyHorvathSep16'13at14:33
@KarolyHorvath:obviouslyyoustillneedthehashtabletocountthehitsperentry.Mypointisthatusingaminheapformanagingthetop10entriesis
overkill.Asimplesortedarraywouldperformbetterandtheimplementationwouldbealsoquitesimpler.Actually,foranincrementallyupdatedtopN(and
unlessyouhavemassiveties)asortedarraywouldalwaysperformbetterthanaminheap.salvaSep17'13at7:53
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 21/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmoraskyourownquestion.
asked 2yearsago
viewed 3881times
active 1yearago
Lookingforajob?
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
FrontendEngineer
gozoomo.com
Bengaluru,India
angularjsreactjs
Gettheweeklynewsletter!
Topquestionsand
answers
Important
announcements
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 22/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Unanswered
questions
Signupforthenewsletter
Related
33
Whyaresomanyalgorithmproblemsaskedininterviews?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
134
TrickyGoogleinterviewquestion
43
Algorithmpuzzleinterview
13
Arethereany'tricks'tospeedupsamplingofaverylargeknapsackcombinationtypeprob?
9
Algorithmoninterview
4
InterviewOracle
3
Whatisabettermethodtosolvethisprob?
6
AmazonInterviewDesignMeetingScheduler
2
IsthereabetteralgorithmforthisWerewolfProb?
HotNetworkQuestions
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
CanIwriteapaperoutofasimpleidea
Alarmclockprinting
What'sanexpressionforacunninglyfakefriend?
Packagetodonotes:HowcanIchangethetextcolor?
Whyadding"incolour"whenreferringto"WizardofOz"?
FiveAnglesinaStar
40Numbersin9Bytes
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Passfilenamefrombashtopython
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
HowdoIfacilitateafirsttimeAgileretrospective?
HowcouldaresurrectedJesusproveheisJesus?
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
howcanItaketotalminutesfromtime?
DoesaUSB3.0connectionrequireaUSB3.0cord?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
WhydosomepeoplerefertoLinuxasGNU/Linux?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Whycan'tanonabeliangroupbe75%abelian?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 23/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
binarytreeconstructionfrompreorder
ThisisanAmazoninterviewquestion.Cananyonegiveanalgorithmtodothis?
Thereisabinarytreewiththefollowingproperties:
Allofitsinnernodehavethevalue'N',andalltheleaveshavethevalue'L'.
Everynodeeitherhastwochildrenorhasnochild.
upvote4down
votefavorite Givenitspreorder,constructthetreeandreturntherootnode.
5
algorithmbinarytree
editedMar16'11at3:38 askedMar16'11at2:54
share|improvethisquestion
TheVillageIdiot Nohsib
24.6k1073135 1,02632849
YoureallyshouldhaveknowledgeindatastructuresbutpreorderissimplyRoot,LeftNode,RightNode.TrevorArjeskiMar16'11at3:00
@TrevorMAThat'strue,butit'snotwhat'sbeingasked.Theideaishowtoreconstructthetreegiventhetraversal,whichrequiresyoutoknow
4
morethanjustwhatpreorderis.templatetypedefMar16'11at3:06
addacomment|
4Answers
activeoldestvotes
Sinceitisguaranteedthateachinternalnodehasexactly2children,wecansimplybuildthetreerecursivelyusingthat.
Wecallourfunctionwiththeinputprovided,anditexaminesthefirstcharacteritgot.Ifitisaleafnode,itjustreturnsaleaf.Ifitisaninternalnode,itjust
callsitselffortheleftandrightsubtreesandreturnsthetreeformedusingthenodeasrootandtheleftandrightsubtreesasitsleftandrightchildren.
Codefollows(inPython).Note,Iamusingtuplestorepresentnode,sothetreeisatupleoftuples.
#!/usr/bin/envpython
fromcollectionsimportdeque
defbuild_tree(pre_order):
root=pre_order.popleft()
ifroot=='L':
returnroot
else:
return(root,build_tree(pre_order),build_tree(pre_order))
if__name__=='__main__':
printbuild_tree(deque("NNLLL"))
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 24/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Edit:CodeinJava
importjava.util.*;
classPreorder{
publicstaticNodebuildTree(List<Character>preorder){
chartoken=preorder.remove(0);
if(token=='L'){
returnnewNode(token,null,null);
}
else{
returnnewNode(token,buildTree(preorder),buildTree(preorder));
upvote3
down }
vote }
publicstaticvoidmain(Stringargs[]){
List<Character>tokens=newLinkedList<Character>();
Stringinput="NNLLL";
for(inti=0;i<input.length();i++)tokens.add(input.charAt(i));
System.out.println(buildTree(tokens));
}
}
classNode{
charvalue;
Nodeleft,right;
publicNode(charvalue,Nodeleft,Noderight){
this.value=value;
this.left=left;
this.right=right;
}
publicStringtoString(){
if(left==null&&right==null){
return"("+value+")";
}
else{
return"("+value+","+left+","+right+")";
}
}
}
answeredMar16'11at5:14
editedMar16'11at6:45
share|improvethisanswer
MAK
13.9k53662
ifyoucouldprovidethecodeinjavaorc,itwouldbegreat.Thanksinadvance.NohsibMar16'11at6:14
@Nohsib:AddedcodeinJava.QuiteabitlongerthanPython(Javaissomewhatmoreverbose),butthesameidea.MAKMar16'11at6:41
:Thanksalot,willtryitout...NohsibMar16'11at22:03
addacomment|
Icanthinkofarecursivealgorithm.
head=newnode.removefirstcharacterinpreorderString
Invokef(head,preorderString)
Recursivefunctionf(node,s)
removefirstcharfroms,ifLthenattachtonodeasleaf.
upvote0downvote elsecreateanodeLeft,attachtonode,invokef(nodeLeft,s)
removefirstcharfroms,ifLthenattachtonodeasleaf.
elsecreateanodeRight,attachtonode,invokef(nodeRight,s)
answeredMar16'11at3:59
share|improvethisanswer
CMR
715514
addacomment|
Ithinkthekeypointistorealizethattherearethreepossibilitiesfortheadjacentnodes:NN,NL?,L?(``?''meanseitherNorL)
1. NN:thesecondNistheleftchildofthefirstN,butwedon'tknowwhattherightchildofthefirstNis
2. NL?:thesecondNistheleftchildofthefirstN,andtherightchildofthefirstNis?
3. L?:?istherightchildofSTACKtop
ASTACKisusedbecausewhenwereadanodeinapreordersequence,wedon'tknowwhereitsrightchildis(wedoknowwhereitsleftchildis,aslongas
ithasone).ASTACKstoresthisnodesothatwhenitsrightchildappearswecanpopitupandfinishitsrightlink.
NODE*preorder2tree(void)
{
NODE*head=next_node();
NODE*p=head;
NODE*q;
while(1){
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 25/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
q=next_node();
if(!q)
break;
/*possibilitiesofadjacentnodes:
*NN,NL?,L?
*/
upvote0 if(p>val=='N'){
downvote p>L=q;
if(q>val=='N'){/*NN*/
push(p);
p=q;
}else{/*NL?*/
q=next_node();
p>R=q;
p=q;
}
}else{/*L?*/
p=pop();
p>R=q;
p=q;
}
}
returnhead;
}
Thecodeabovewastestedusingsomesimplecases.Hopefullyit'scorrect.
answeredMar16'11at15:44
editedMar16'11at15:50
share|improvethisanswer
Forrest
413
addacomment|
Hereisthejavaprogram::
importjava.util.*
classpreorder_given_NNNLL{
staticStack<node>stk=newStack<node>();
staticnoderoot=null;
staticclassnode
{
charvalue;
nodeleft;
noderight;
publicnode(charvalue)
{
this.value=value;
this.left=null;
this.right=null;
}
publicstaticnodestkoper()
{
nodeposr=null,posn=null,posl=null;
posr=stk.pop();
if(stk.empty())
{
stk.push(posr);
returnnull;
}
else
posl=stk.pop();
if(stk.empty())
{
stk.push(posl);
stk.push(posr);
returnnull;
}
else
{
posn=stk.pop();
}
if(posn.value=='N'&&posl.value=='L'&&posr.value=='L')
{
root=buildtree(posn,posl,posr);
if(stk.empty())
{
returnroot;
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 26/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
}
else
{
upvote0downvoteaccepted
stk.push(root);
root=stkoper();
}
}
else
{
stk.push(posn);
stk.push(posl);
stk.push(posr);
}
returnroot;
publicstaticnodebuildtree(nodeposn,nodeposl,nodeposr)
{
posn.left=posl;
posn.right=posr;
posn.value='L';
returnposn;
publicstaticvoidinorder(noderoot)
{
if(root!=null)
{
inorder(root.left);
if((root.left==null)&&(root.right==null))
System.out.println("L");
else
System.out.println("N");
inorder(root.right);
}
}
publicstaticvoidmain(Stringargs[]){
Stringinput="NNNLLLNLL";
char[]pre=input.toCharArray();
for(inti=0;i<pre.length;i++)
{
nodetemp=newnode(pre[i]);
stk.push(temp);
root=stkoper();
}
inorder(root);
answeredMar18'11at15:44
share|improvethisanswer
Nohsib
1,02632849
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 27/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmbinarytreeoraskyourown
question.
asked 4yearsago
viewed 4686times
active 3yearsago
Lookingforajob?
ApplicationDeveloper,Hyderabad
ThoughtWorksTechnologies
Hyderabad,India
rubyonrails.net
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Related
4
ConvertPreorderlistingofabinarytreetopostorderandviceversa
5
Constructtreewithpreordertraversalgiven
1
binarytreewithspecialproperty
9
Removingduplicatesubtreesfrombinarytree
1
HowtoformaBinaryTreefromaPreorderandaChildrencharsequence
0
Findtreeheightgivenpreorder
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 28/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
0
Buildabinarytreefromagivenpreordertraversal
0
ConstructionofBinarySearchTreefrompreordertraversaliteratively(notrecursion)
0
ConstructBinaryTreefrominorderandpostorderTraversals
6
Howdoesinorder+preorderconstructuniquebinarytree?
HotNetworkQuestions
What'sthebestwaytoinvestformakingregulardonations?
Patchingabinarywithdd
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Howtoprotectaspaceelevatoragainstterrorism
Whyweren'ttheWeasleysapartoftheOriginalOrder?
Shouldmy(sequential)collectionstartatindex0orindex1?
Passfilenamefrombashtopython
Justifyingsuboptimalresearchqualitybylackofsupervision
Whyadding"incolour"whenreferringto"WizardofOz"?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Troublewithterminatinga<apex:pageBlockSection>
Packagetodonotes:HowcanIchangethetextcolor?
MementoVivereMomentumMori
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
ThenthTernary
HowcanIcheckifmyfunctionprint/echo'ssomething?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
zero,zerosorzeroes?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 29/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
binarytreeconstructionfrompreorder
ThisisanAmazoninterviewquestion.Cananyonegiveanalgorithmtodothis?
Thereisabinarytreewiththefollowingproperties:
Allofitsinnernodehavethevalue'N',andalltheleaveshavethevalue'L'.
Everynodeeitherhastwochildrenorhasnochild.
upvote4down
votefavorite Givenitspreorder,constructthetreeandreturntherootnode.
5
algorithmbinarytree
editedMar16'11at3:38 askedMar16'11at2:54
share|improvethisquestion
TheVillageIdiot Nohsib
24.6k1073135 1,02632849
YoureallyshouldhaveknowledgeindatastructuresbutpreorderissimplyRoot,LeftNode,RightNode.TrevorArjeskiMar16'11at3:00
@TrevorMAThat'strue,butit'snotwhat'sbeingasked.Theideaishowtoreconstructthetreegiventhetraversal,whichrequiresyoutoknow
4
morethanjustwhatpreorderis.templatetypedefMar16'11at3:06
addacomment|
4Answers
activeoldestvotes
Sinceitisguaranteedthateachinternalnodehasexactly2children,wecansimplybuildthetreerecursivelyusingthat.
Wecallourfunctionwiththeinputprovided,anditexaminesthefirstcharacteritgot.Ifitisaleafnode,itjustreturnsaleaf.Ifitisaninternalnode,itjust
callsitselffortheleftandrightsubtreesandreturnsthetreeformedusingthenodeasrootandtheleftandrightsubtreesasitsleftandrightchildren.
Codefollows(inPython).Note,Iamusingtuplestorepresentnode,sothetreeisatupleoftuples.
#!/usr/bin/envpython
fromcollectionsimportdeque
defbuild_tree(pre_order):
root=pre_order.popleft()
ifroot=='L':
returnroot
else:
return(root,build_tree(pre_order),build_tree(pre_order))
if__name__=='__main__':
printbuild_tree(deque("NNLLL"))
Edit:CodeinJava
importjava.util.*;
classPreorder{
publicstaticNodebuildTree(List<Character>preorder){
chartoken=preorder.remove(0);
if(token=='L'){
returnnewNode(token,null,null);
}
else{
returnnewNode(token,buildTree(preorder),buildTree(preorder));
upvote3
down }
vote }
publicstaticvoidmain(Stringargs[]){
List<Character>tokens=newLinkedList<Character>();
Stringinput="NNLLL";
for(inti=0;i<input.length();i++)tokens.add(input.charAt(i));
System.out.println(buildTree(tokens));
}
}
classNode{
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 30/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
charvalue;
Nodeleft,right;
publicNode(charvalue,Nodeleft,Noderight){
this.value=value;
this.left=left;
this.right=right;
}
publicStringtoString(){
if(left==null&&right==null){
return"("+value+")";
}
else{
return"("+value+","+left+","+right+")";
}
}
}
answeredMar16'11at5:14
editedMar16'11at6:45
share|improvethisanswer
MAK
13.9k53662
ifyoucouldprovidethecodeinjavaorc,itwouldbegreat.Thanksinadvance.NohsibMar16'11at6:14
@Nohsib:AddedcodeinJava.QuiteabitlongerthanPython(Javaissomewhatmoreverbose),butthesameidea.MAKMar16'11at6:41
:Thanksalot,willtryitout...NohsibMar16'11at22:03
addacomment|
Icanthinkofarecursivealgorithm.
head=newnode.removefirstcharacterinpreorderString
Invokef(head,preorderString)
Recursivefunctionf(node,s)
removefirstcharfroms,ifLthenattachtonodeasleaf.
upvote0downvote elsecreateanodeLeft,attachtonode,invokef(nodeLeft,s)
removefirstcharfroms,ifLthenattachtonodeasleaf.
elsecreateanodeRight,attachtonode,invokef(nodeRight,s)
answeredMar16'11at3:59
share|improvethisanswer
CMR
715514
addacomment|
Ithinkthekeypointistorealizethattherearethreepossibilitiesfortheadjacentnodes:NN,NL?,L?(``?''meanseitherNorL)
1. NN:thesecondNistheleftchildofthefirstN,butwedon'tknowwhattherightchildofthefirstNis
2. NL?:thesecondNistheleftchildofthefirstN,andtherightchildofthefirstNis?
3. L?:?istherightchildofSTACKtop
ASTACKisusedbecausewhenwereadanodeinapreordersequence,wedon'tknowwhereitsrightchildis(wedoknowwhereitsleftchildis,aslongas
ithasone).ASTACKstoresthisnodesothatwhenitsrightchildappearswecanpopitupandfinishitsrightlink.
NODE*preorder2tree(void)
{
NODE*head=next_node();
NODE*p=head;
NODE*q;
while(1){
q=next_node();
if(!q)
break;
/*possibilitiesofadjacentnodes:
*NN,NL?,L?
*/
upvote0 if(p>val=='N'){
downvote p>L=q;
if(q>val=='N'){/*NN*/
push(p);
p=q;
}else{/*NL?*/
q=next_node();
p>R=q;
p=q;
}
}else{/*L?*/
p=pop();
p>R=q;
p=q;
}
}
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 31/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
returnhead;
}
Thecodeabovewastestedusingsomesimplecases.Hopefullyit'scorrect.
answeredMar16'11at15:44
editedMar16'11at15:50
share|improvethisanswer
Forrest
413
addacomment|
Hereisthejavaprogram::
importjava.util.*
classpreorder_given_NNNLL{
staticStack<node>stk=newStack<node>();
staticnoderoot=null;
staticclassnode
{
charvalue;
nodeleft;
noderight;
publicnode(charvalue)
{
this.value=value;
this.left=null;
this.right=null;
}
publicstaticnodestkoper()
{
nodeposr=null,posn=null,posl=null;
posr=stk.pop();
if(stk.empty())
{
stk.push(posr);
returnnull;
}
else
posl=stk.pop();
if(stk.empty())
{
stk.push(posl);
stk.push(posr);
returnnull;
}
else
{
posn=stk.pop();
}
if(posn.value=='N'&&posl.value=='L'&&posr.value=='L')
{
root=buildtree(posn,posl,posr);
if(stk.empty())
{
returnroot;
}
else
{
upvote0downvoteaccepted stk.push(root);
root=stkoper();
}
}
else
{
stk.push(posn);
stk.push(posl);
stk.push(posr);
}
returnroot;
publicstaticnodebuildtree(nodeposn,nodeposl,nodeposr)
{
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 32/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
posn.left=posl;
posn.right=posr;
posn.value='L';
returnposn;
publicstaticvoidinorder(noderoot)
{
if(root!=null)
{
inorder(root.left);
if((root.left==null)&&(root.right==null))
System.out.println("L");
else
System.out.println("N");
inorder(root.right);
}
}
publicstaticvoidmain(Stringargs[]){
Stringinput="NNNLLLNLL";
char[]pre=input.toCharArray();
for(inti=0;i<pre.length;i++)
{
nodetemp=newnode(pre[i]);
stk.push(temp);
root=stkoper();
}
inorder(root);
answeredMar18'11at15:44
share|improvethisanswer
Nohsib
1,02632849
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 33/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmbinarytreeoraskyourown
question.
asked 4yearsago
viewed 4686times
active 3yearsago
Lookingforajob?
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
Related
4
ConvertPreorderlistingofabinarytreetopostorderandviceversa
5
Constructtreewithpreordertraversalgiven
1
binarytreewithspecialproperty
9
Removingduplicatesubtreesfrombinarytree
1
HowtoformaBinaryTreefromaPreorderandaChildrencharsequence
0
Findtreeheightgivenpreorder
0
Buildabinarytreefromagivenpreordertraversal
0
ConstructionofBinarySearchTreefrompreordertraversaliteratively(notrecursion)
0
ConstructBinaryTreefrominorderandpostorderTraversals
6
Howdoesinorder+preorderconstructuniquebinarytree?
HotNetworkQuestions
What'sthebestwaytoinvestformakingregulardonations?
Patchingabinarywithdd
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Howtoprotectaspaceelevatoragainstterrorism
Whyweren'ttheWeasleysapartoftheOriginalOrder?
Shouldmy(sequential)collectionstartatindex0orindex1?
Passfilenamefrombashtopython
Justifyingsuboptimalresearchqualitybylackofsupervision
Whyadding"incolour"whenreferringto"WizardofOz"?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 34/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Troublewithterminatinga<apex:pageBlockSection>
Packagetodonotes:HowcanIchangethetextcolor?
MementoVivereMomentumMori
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
ThenthTernary
HowcanIcheckifmyfunctionprint/echo'ssomething?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
zero,zerosorzeroes?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
checkingif2numbersofarrayadduptoI
Isawainterviewquestionasfollows:GiveanunsortedarrayofintegersAandandanintegerI,findoutifanytwomembersofAaddupto
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 35/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
I.
anyclues?
upvote7downvote timecomplexityshouldbeless
favorite
6 algorithm
editedFeb4'11at7:04 askedFeb4'11at7:03
share|improvethisquestion
SachinShanbhag mindtree
25.2k54579 113238
addacomment|
14Answers
activeoldestvotes
Ifyouhavetherangewhichtheintegersarewithin,youcanuseacountingsortlikesolutionwhereyouscanoverthearrayandcountanarrayup.Ex
youhavetheintegers
input=[0,1,5,2,6,4,2]
Andyoucreateanarraylikethis:
count=int[7]
which(inJava,C#etc.)aresuitedforcountingintegersbetween0and6.
foreachintegerininput
count[i]=count[i]+1
upvote7down
Thiswillgiveyouthearray[1,1,2,0,1,1,1].Nowyoucanscanoverthisarray(halfofit)andcheckwhetherthereareintegerswhichaddsuptoi
voteaccepted
like
forj=0tocount.length1
ifcount[j]!=0andcount[ij]!=0then//Checkforarrayoutofboundshere
WUHUU!theintegersjandijaddsup
OverallthisalgorithmgivesyouO(n+k)wherenisfromthescanovertheinputoflengthnandkisthescanoverthecountarrayoflengthk
(integersbetween0andk1).Thismeansthatifn>kthenyouhaveaguaranteedO(n)solution.
answeredFeb5'11at11:59
share|improvethisanswer
LasseEspeholt
12.7k33775
addacomment|
Inserttheelementsintohashtable.
Whileinsertingx,checkifIxalreadyexists.O(n)expectedtime.
Otherwise,sortthearrayascending(fromindex0ton1).Havetwopointers,oneatmaxandoneatmin(callthemMandmrespectively).
upvote17
downvote Ifa[M]+a[m]>IthenM
Ifa[M]+a[m]<Ithenm++
Ifa[M]+a[m]==Iyouhavefoundit
Ifm>M,nosuchnumbersexist.
answeredFeb4'11at7:08
share|improvethisanswer
Aryabhatta
HashMaphasverygoodbestcaseperformance.Butinworstcase(everynumberproducingthesamehash)youwon'tlikeit.yankeeFeb4'11at
7:14
@yankee:Canyoutellmethenameofalibrarythathasanexistingandpragmaticimplementationofahashtablethatproducesthesamehash
2
valueeachtime?GManNickGFeb4'11at7:17
@Moron:"Whileinsertingx,checkifIxalreadyexists."canactuallybeO(logn)forinstancewithasimpledichotomy,oraselfbalancing
binarysearchtree.EOLFeb4'11at7:53
@EOL:itwillbeO(logn)forEACHnumberyou'reinserting,sofornnumbersO(nlogn)...It'sjustlikesortingwhileinserting.YochaiTimmer
Feb4'11at9:30
1 @EOL:ItisO(n)expectedtimeforthewholearray,notjustoneelement.AryabhattaFeb4'11at16:53
|show4morecomments
1. sortthearray
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 36/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
2. foreachelementXinA,performabinarysearchforIX.IfIXisinA,wehaveasolution.
ThisisO(nlogn).
IfAcontainsintegersinagiven(smallenough)range,wecanuseatricktomakeitO(n):
upvote7down
vote 1. wehaveanarrayV.ForeachelementXinA,weincrementV[X].
2. whenweincrementV[X]wealsocheckifV[IX]is>0.Ifitis,wehaveasolution.
answeredFeb4'11at7:06
share|improvethisanswer
GabiPurcaru
17.1k43572
SortingthearrayusingwhichalgorithmyankeeFeb4'11at7:07
YoucanalsothrowoutanyitemsbiggerthanI1whilesortingthearraytomakethesearchfaster,thoughworstcaseperformanceisthesame.
DanGrossmanFeb4'11at7:08
@yankeeHeapSort,MergeSort,QuickSort(notworstcaseO(n*logn))LasseEspeholtFeb4'11at7:09
@Dan:Youcan'tdothis,becausetheremaybenegativeintegersinthelist.Negativeinteger+Integer>IcanwelladduptiI.yankeeFeb4'11
3
at7:10
afteryousort,thebetterwayisjusthave1pointerateachendandmovetheminward.lookatAryabhatta'ssolutionkharlesJul9'14at19:36
addacomment|
Forexample,loopandaddpossiblenumbertosetorhashandiffound,justreturnit.
>>>A=[11,3,2,9,12,15]
>>>I=14
>>>S=set()
>>>forxinA:
...ifxinS:
...printIx,x
...S.add(Ix)
upvote5downvote ...
113
212
>>>
answeredFeb4'11at7:17
share|improvethisanswer
YOU
51.1k12101159
ThisisinO(nlogn),whichisgood.EOLFeb4'11at7:57
ThisisO(n).xinSisO(1),S.add(Ix)isO(1),worstcasebeingO(n)wiki.python.org/moin/TimeComplexityRohitApr30'14at8:16
addacomment|
publicstaticbooleanfindSum2(int[]a,intsum){
if(a.length==0){
returnfalse;
}
Arrays.sort(a);
inti=0;
intj=a.length1;
while(i<j){
inttmp=a[i]+a[j];
if(tmp==sum){
System.out.println(a[i]+"+"+a[j]+"="+sum);
returntrue;
upvote3downvote }elseif(tmp>sum){
j;
}else{
i++;
}
}
returnfalse;
}
answeredNov12'11at20:33
share|improvethisanswer
naani
311
addacomment|
O(n)timeandO(1)space
IfthearrayissortedthereisasolutioninO(n)timecomplexity.
Supposearearrayisarray={0,1,3,5,8,10,14}
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 37/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Andourx1+x2=k=13,sooutputshouldbe=5,8
1. Taketwopointersoneatstartofarray,oneatendofarray
upvote2down 2. Addboththeelementsatptr1andptr2array[ptr1]+array[ptr2]
vote 3. ifsum>kthendecrementptr2elseincrementptr1
4. Repeatstep2andstep3tillptr1!=ptr2
Samethingexplainedindetailhere.SeemslikeanAmazoninterviewQuestionhttp://indergnu.blogspot.com/2007/10/findtwonosinarraywhose
sumx.html
answeredOct18'11at12:54
share|improvethisanswer
EFreak
386619
Oops..readtheQuestionwrong!thought,itwassorted.ButanywayskeepingtheanswersinceitisincontextEFreakOct18'11at12:56
addacomment|
fornlogn:Sortthearrayandforeachelement[0<=j<lenA],subtractiA[j]anddoabinarysearchforthiselementinsortedarray.
hashmap(frequencyofno,number)shouldworkinO(n).
upvote0downvote answeredFeb4'11at7:07
share|improvethisanswer
ayush
7,21953160
addacomment|
foreacheleinthearray
if(sumele)ishashedandhashedvalueisnotequaltoindexofele
printele,sumele
endif
Hasheleaskeyandindexasvalue
endfor
upvote0downvote
answeredFeb4'11at7:10
editedFeb4'11at7:37
share|improvethisanswer
codaddict
192k38315400
addacomment|
PERLimplementationtodetectifasortedarraycontainstwointegerthatsumuptoNumber
my@a=(11,3,2,9,12,15);
my@b=sort{$a<=>$b}@a;
my%hash;
my$sum=14;
my$index=0;
foreachmy$ele(@b){
my$sum_minus_ele=$sum$ele;
print"Trace:$ele::$index::$sum_minus_ele\n";
upvote0downvote if(exists($hash{$sum_minus_ele})&&$hash{$sum_minus_ele}!=$index){
print"\tElement:".$ele."::Sumele:".$sum_minus_ele."\n";
}
$hash{$ele}=$index;
$index++;
}
answeredFeb20'11at5:00
share|improvethisanswer
Alexsea
1
addacomment|
Thismightbepossibleinthefollowingway:Beforeputtingtheelementsintothehashmap,youcancheckiftheelementisgreaterthantherequiredsum.Ifit
is,youcansimplyskipthatelement,elseyoucanproceedwithputtingitintothehashmap.Itsaslightimprovementonyouralgorithm,althoughtheoverall
timestillremainsthesame.
upvote0
down editedJul1'12at7:18 answeredJul1'12at0:32
vote
share|improvethisanswer
swiecki Setafire
2,05021218 13212
addacomment|
ThiscanbesolvedusingtheUNIONFINDalgorithm,whichcancheckinconstanttimewhetheranelementisintoaset.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 38/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
So,thealgorithmwouldbeso:
foundsum0=false;
foreach(el:array){
iffind(x):foundsum0=true;
elseunion(x);
upvote0downvote }
FINDandUNIONareconstant,O(1).
answeredSep29'12at18:56
share|improvethisanswer
alinsoar
3,99011025
addacomment|
hereisaO(n)solutioninjavausingO(n)extraspace.ThisuseshashSettoimplementit
http://www.dsalgo.com/UnsortedTwoSumToK.php
upvote0downvote answeredJan30'13at13:27
share|improvethisanswer
parthapratimsirker
211
addacomment|
Hereisasolutionwitchtakesintoaccountduplicateentries.Itiswritteninjavascriptandassumesarrayissorted.ThesolutionrunsinO(n)timeanddoesnot
useanyextramemoryasidefromvariable.Chooseasortingalgorithmofchoice.(radixO(kn)!)andthenrunthearraythroughthisbaby.
varcount_pairs=function(_arr,x){
if(!x)x=0;
varpairs=0;
vari=0;
vark=_arr.length1;
if((k+1)<2)returnpairs;
varhalfX=x/2;
while(i<k){
varcurK=_arr[k];
varcurI=_arr[i];
varpairsThisLoop=0;
if(curK+curI==x){
//ifmidpointandequalfindcombinations
if(curK==curI){
varcomb=1;
while(k>=i)pairs+=(comb++);
break;
}
//countpairandkduplicates
pairsThisLoop++;
while(_arr[k]==curK)pairsThisLoop++;
//addksidepairstorunningtotalforeveryisidepairfound
pairs+=pairsThisLoop;
while(_arr[++i]==curI)pairs+=pairsThisLoop;
}else{
upvote0 //ifweareatamidpoint
downvote if(curK==curI)break;
vardistK=Math.abs(halfXcurK);
vardistI=Math.abs(halfXcurI);
if(distI>distK)while(_arr[++i]==curI);
elsewhile(_arr[k]==curK);
}
}
returnpairs;
}
Isolvedthisduringaninterviewforalargecorporation.Theytookitbutnotme.Sohereitisforeveryone.
Startatbothsideofthearrayandslowlyworkyourwayinwardsmakingsuretocountduplicatesiftheyexist.
Itonlycountspairsbutcanbereworkedto
findthepairs
findpairs<x
findpairs>x
Enjoyanddon'tforgettobumpifitsthebestsolution!
answeredMar29'13at14:40
share|improvethisanswer
dRoneBrain
16117
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 39/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Splitthearrayintotwogroups<=I/2and>I/2.Thensplitthoseinto<=I/4,>I/4and<=3I/4,>3I/4Andrepeatforlog(I)stepsandcheckthepairsjoining
fromtheoutsidee.g1I/8<=and>7I/8andiftheybothcontainatleastoneelementthentheyaddtoI.Thiswilltaken.Log(I)+n/2stepsandforI
upvote0
answeredMar12'14at9:36
downvote
share|improvethisanswer
JordanBrown
4251520
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmoraskyourownquestion.
asked 4yearsago
viewed 14911times
active 1yearago
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 40/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Lookingforajob?
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
ApplicationDeveloper,Hyderabad
ThoughtWorksTechnologies
Hyderabad,India
rubyonrails.net
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
Linked
0
InaArrayhowwefind2elementwho'sdifferencesinagivenNumber..?lessthenO(n^2)time
2
Determineifarraycontainstwoelementswhichequalacertainsum?
Related
6
WhatisbestefficientalgorithmforGivenanunsortedarrayofpositiveintegersandanintegerN,returnNifNexistedinthearrayorthefirstnumberthatissmaller
thanN.Problem?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
4
findingmiddleelementofanarray
2
arrayquestion
173
Givenanumber,findthenexthighernumberwhichhastheexactsamesetofdigitsastheoriginalnumber
808
AlgorithmimprovementforCocaColacanshaperecognition
2
Findthesmallestmissingnumberinanarray
2
Howtofind2numbersandtheirsuminanunsortedarray
2450
Pairsocksfromapileefficiently?
256
Writeaprogramtofind100largestnumbersoutofanarrayof1billionnumbers
HotNetworkQuestions
Howtodecidewhetherastoryisworthwriting?
Isturninggraphitecarbonintodiamondindustriallydoable?
Justifyingsuboptimalresearchqualitybylackofsupervision
Whatis`$?`?Isitavariable?
FiveAnglesinaStar
Howtoprotectaspaceelevatoragainstterrorism
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Thetwopronunciationsof
ImageOpensasLayer0ratherthanBackground
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
CanIflywithagoldbar?
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
Howtodrawsequenceofshapeswitharrowsandtext
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 41/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
WhydosomepeoplerefertoLinuxasGNU/Linux?
RollmyD&Dcharacter'sabilityscores
HowdoIfacilitateafirsttimeAgileretrospective?
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
LeapyearcheckinJava
HowtoprovemyGmailhasbeenhacked?
Needhelprecreatingcrazycolors/materialfromexample
Jumpingcarwithtoomanyamps?
Whyshouldakeybemadeexplicit?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Convertthestructureofthetreelikealeftalignedtreewhoseeachnode
containsadownpointerandarightpointer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 42/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ThisisaquestionaskedininterviewofAmazon.Givenabinarytreeasbelow
A
/\
BC
/\
DE
//\
FGH
Convertthestructureofthetreelikealeftalignedtreewhoseeachnodecontainsadownpointerandarightpointerandlookslikethebelowtree.
A
upvote0down |
votefavorite BC
|
DE
|
FGH
Cananyonehelpmehowtosolvethisquestion.Thanks.
algorithmdatastructurestreebinarytree
askedFeb27at12:35
share|improvethisquestion
ravi_rock
1
Haveyoutriedsomething?Itlooksthatforeveryleftmost(andtheroot)nodeyouarecreatingadownpointerwhichpointstotheleftmostnodefor
thenextlevelandarightpointerwhichlinkstoalistwithallthenodesinthesameleveligavriilFeb27at12:38
1 Whathaveyoutried?thisisjustamodifiedbreadthfirstsearch:)PhamTrungFeb27at12:55
addacomment|
1Answer
activeoldestvotes
Youcanusemodifiedbreadthfirstsearchtodothis.Youneedtokeeptrackofwhenyouswitchtonewlevelbyusingfrontier.
Somethinglikethisshouldwork.
Queuequeue=newqueue();
Queuefrontier=newqueue();
queue.enqeue(root.children);
newTree.add(root);
previousLevelParent=root;
addRightPointer=false;
while(!queue.isEmpty())
Nodetmp=queue.dequeue();
frontier.enqueue(tmp.children);
if(addRightPointer)
//Addthistotherightofcurrentlevel
upvote0downvote newTree.addRight(tmp);
else
//Createnewlevelinthenewtreewiththe
//previousLevelParentastheparent
newTree.createNewLevel(previousLevelParent,tmp);
previousLevelParent=tmp;
addRightPointer=true;
if(queue.isEmpty())
queue=frontier;
frontier=newqueue();
addRightPointer=false;
answeredFeb27at13:08
share|improvethisanswer
Mazvl
5851417
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 43/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdatastructurestreebinary
treeoraskyourownquestion.
asked 4monthsago
viewed 40times
active 4monthsago
Lookingforajob?
ChiefSoftwareArchitectJava$100K
Crossover
Bengaluru,India/remote
eclipsenetbeans
SeniorTechnicalConsultant/DeveloperInnovation
iSpace(aConnollyiHea
Hyderabad,India/remote
scalaakka
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Related
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 44/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
What'sagooddatastructureforbuildingequivalenceclassesonnodesofatree?
2
DatastructureformappingURLsorlocalpaths
0
QuestiononTreeDataStructure:Howcanwefillallinordersuccessorpointerofalltreenodes?
2
BinarytreefromPreorderandinordertraversal
14
ReverseABinaryTree(LefttoRight)
0
Finddiameteroftreeifforeachnode,parentpointerisgiven
1
InterviewQ:BinarytreeInordertraversal
3
PassingBinaryTreeonanetworkwithminimumspace
1
HowmanyRightRotationisneedtoconvertatree?
0
Definitionofcompletebinarytree
HotNetworkQuestions
MementoVivereMomentumMori
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
Isturninggraphitecarbonintodiamondindustriallydoable?
Whydosocksstink?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
WhatdoesitmeanifanACmotorhastwovoltageratings?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Jumpingcarwithtoomanyamps?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
Howtodrawsequenceofshapeswitharrowsandtext
Patchingabinarywithdd
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Antiferromagneticordering
Howtoprotectaspaceelevatoragainstterrorism
Whatisatemporarysolutionforadamagedcarbody?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
SixMusicalFriends
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
ThenthTernary
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Isthereawordforpeopleincapableofthinking?
Removestaticobjectsfromanimagesequence
Whatistheoriginofthepowericon?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 45/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Findthenumberofuniquelongestcommonsubsequences
For2strings,IwanttofindthenumberofdistinctLCS's.IreadonwikionhowtoprintallLCS'sbuthowtocheckthattheyaredistinct?Thehashtable
isnotfeasibleasmyinputstringeachcanbe15002000characterslongsomaximumnumberofLCS'scanbe2000choose1000
upvote1
downvote algorithmdatastructures
favorite askedNov2'09at11:09
1
share|improvethisquestion
Wifi
63
Sinceyoureonlyinterestedinthelongestcommonsubsequences,theirnumbershouldbequitesmall.Whatswrongwiththehashtableapproach?
1
KonradRudolphNov2'09at11:38
LikeIwrote,thenumberofLCScanbequitelarge,soitwouldbeinfeasibletostoretheminhashtable.(ifallaredistinct)WifiNov2'09at
11:47
Ihavejustgotapaper.Cansomeonedownloadthis?Iamnotabletodoit.Thetitleis:ComputingtheNumberofLongestCommonSubsequences
byRonaldIgreenbergWifiNov2'09at11:55
addacomment|
4Answers
activeoldestvotes
Canyouspecify.
Dosubstringshavetobeconsecutive,oranysubsequencewouldbeok?Forexample,in"abcde"would"abde"beavalidsubstring?
Whatdoyoumeanbydistinct?
upvote0
downvote answeredNov2'09at11:33
share|improvethisanswer
husayt
4,64641543
Notheydontneedtobeconsecutive.ItisthesamestandardLCSproblemofdp.ItsjustthattofindthenumberofdistinctLCSifmultipleLCSoccur
WifiNov2'09at11:35
Toansweryourfirstquestion:no.Thisisnotasubstringbydefinition.Rather,itisasubsequence(again,bydefinition).KonradRudolphNov2
'09at11:35
canyouexplainwhatdoyoumeanbydistinct?husaytNov2'09at11:37
Itwillalsobeagoodideatoshowwhatyouwantonexample.Asthereareanumberofsimilarproblems,withtinydiffs.Butthesediffstheyare
enoughtochangetheapproachdramatically.husaytNov2'09at11:41
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 46/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Youcanuseahashtable,butinsteadofstoringthewholesubstring,youjuststore(alistof)thebeginningandendofitrelativetotheoriginalstring.This
way,youcandoastringcompareintheoriginalstringifthereareanycollisions.
upvote0 answeredNov3'09at21:22
downvote
share|improvethisanswer
JohannesHoff
1,54611726
addacomment|
Throwthetwostringstoasuffixtree.Thisistimeandspacelinearinlengthoftheconcatenationofthetwostrings.
upvote0 answeredNov4'09at5:42
down
vote share|improvethisanswer
DavidLehavi
982510
ThisistheanswerIwasthinkingofposting.Thisdatastructureisbestforfindingcommonsubsequenceswhenthemostflexibilityisneeded.For
example,iftherearelotsofduplicatedlongsubsequences,thisdatastructurewillhaveacceptableperformance.HeathHunnicuttNov5'09at20:58
I'mnotawarethatasuffixtreecanbeusedforlongestcommonsubsequences.Theycanhoweverbeusedtofindthelongestcommonsubstring.MAK
1
Feb6'10at16:25
addacomment|
GoodgodIfoundapostingonthistopic.Actually,IfacedthisprobleminAmazoninterviewrecentlyandIsentacodetothemforreview.Theydidnottellme
whetheritscorrectorwrongbutIdidnotgetanyfurtherinputsfromthem(soIassumedihaveerredsomewhere).Idontwanttheefficientimplementationas
youguysdiscuss.CananyonejustreviewthecodeI'vewrittentocheckitscorrectornot.
http://www.technicalypto.com/2010/02/findcommonsequencethatisoutof.html
upvote
0down Manythanks
vote
answeredFeb6'10at16:13
editedFeb17'10at21:29
share|improvethisanswer
bragboy
15.7k1461134
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 47/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdatastructuresoraskyour
ownquestion.
asked 5yearsago
viewed 1458times
active 5yearsago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Related
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
529
Findanintegernotamongfourbilliongivenones
84
Mostefficientwaytostorethousandtelephonenumbers
12
Howtofindlongestcommonsubstringusingtrees?
2450
Pairsocksfromapileefficiently?
6
FindcommonelementsinNsortedarrayswithnoextraspace
12
Findthekthelevennonfreenumber
2
DeterminingtheLongestContinguousSubsequence
5
Totalnumberofpalindromicsubsequencesinastring
1
Longestcommonsubsequenceoptimized
HotNetworkQuestions
Whatwereshoesolesmadefrominpreviousages?
Whatis`$?`?Isitavariable?
CanIwriteapaperoutofasimpleidea
Howtogetearlyentryintomystictheurge?
HowcouldaresurrectedJesusproveheisJesus?
Whydotheymanifestasrings?
HowdoIupgradefromGPLv2toGPLv3?
OptimalRopeBurning
Needtostartareligionwithapredefinedselfdestruct
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 48/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
PythonLabelExpression?ArcGIS10.3.1
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
HowcanIcheckifmyfunctionprint/echo'ssomething?
What'sanexpressionforacunninglyfakefriend?
DoesCIDRreally"doaway"withIPaddressclasses?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
Drawarrowinamindmap
zero,zerosorzeroes?
HowdoIfacilitateafirsttimeAgileretrospective?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Packagetodonotes:HowcanIchangethetextcolor?
ImageOpensasLayer0ratherthanBackground
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Findtwolinesinfilethatarethesame
IwasaskedthisquestioninanAmazoninterview.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 49/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Youhaveafilewithmanylinesbuttwoofthelinesarethesame.Findthosetwolines.IgavetheobviousanswerthatraninN^2time.Ithencameupwithan
answerthatusedahashtable,buttheydidn'tlikethatanswereitherbecausetheysayitwouldn'tworkifthefilewasinthegigabytes.AnotheranswerIcameup
withwasinsteadofstoringthehashresultinmemory,createafilewiththesamenameasthehashvalue,andstorethelineswiththesamesamehashvaluein
thefile.Eithertheycouldn'tunderstandmysolutionortheydidn'tlikeit.
upvote
6down Anythoughts?
vote
favorite Thanks
1
algorithmsearch
editedDec6'12at21:46 askedDec6'12at21:31
share|improvethisquestion
Charles JohnSmith
36.6k105792 554
1 ForLinuxitiseasysort<filename>|uniqc|grep'^2'EdHealDec6'12at21:44
Ok,letmelookattheothersolutions,butwouldn'tthisslurpthefileintomemory?JohnSmithDec6'12at21:50
@JohnSmith:GNUsortknowshowtodoanexternalsortwhenthedatadoesn'tfitinmemory(vkundeti.blogspot.co.uk/2008/03/).SteveJessopDec
6'12at22:09
addacomment|
3Answers
activeoldestvotes
Icanthinkoftwoessentialclassesofsolutionstothisproblem:
1. Probabilisticinmemorysolutions.Youcantrytosolvethisproblembystoringasummaryofthelinesofthefileinmainmemory.Youcanthendo
computationsinmainmemorytoidentifypossibleduplicates,thencheckeachpossibleduplicatebylookingbackondisk.Thesesolutionsareprobably
thebest,sincetheyhavelowmemoryusage,highefficiency,andmimizediskaccesses.Solutionsinthiscategoryinclude
1. Computeahashofeachlineofthefile,thenstorethehashes.Anylinesthathaveahashcollisionrepresentonepossiblepairoflinesthatmight
collide,andjustthoselinescanbeexplored.
2. UseaBloomFiltertostoreallthelinesofthefile,thencheckonlypairsthatcollideintheBloomFilter.Thisisessentiallyavariationof(1)that
ismorespaceefficient.
2. Deterministicondisksolutions.Youcantrytodocomputationswiththeentiredatasetondisk,usingmainmemoryastemporaryscratchspace.This
upvote4 wouldletyougetexactanswerswithouthavingtoholdthewholefileinmemory,butwouldprobablybeslowerunlessyouweredoingsomelater
downvote processingandcouldbenefitfromrestructuringthedata.Solutionsinthiscategoryinclude
accepted
1. Useanexternalsortingalgorithm(externalquicksort,externalradixsort,etc.)tosortthefile,thenlinearsearchitforapairofduplicateelements.
2. BuildanondiskdatastructurelikeaBtreeholdingallofthestrings,thenquerytheBtree.Thistakesalotofpreprocessingtime,butmakes
futureoperationsonthefilealotfaster.
3. Puteverythinginadatabaseandquerythedatabase.
Hopethishelps!
answeredDec6'12at21:40
share|improvethisanswer
templatetypedef
157k35389625
Externalsortseemslikethemoststraightforwardsolution.Oneoptimizationisthatwhileyouaresorting,youcoulddeterminetheduplicatesasyougo
alongandmergethechunks,thuspotentiallyhavingtosorttheentirefile.JohnSmithDec8'12at4:09
I'llmarkthisasthecorrectanswerbecauseithasmanycorrectanswers,answerswhereIlearnedsomethingnew,especiallyexternalsortandBloom
Filters.JohnSmithDec8'12at15:48
addacomment|
YoucanuseaBloomfilter:
http://en.wikipedia.org/wiki/Bloom_filter
up Thenyoucandetect(withfewfalsepositives)linesthatarerepeatedandstoretheninmemory,andthengothroughthefileonceagain.
vote2
down Twopassesthroughthefile,verylittlememoryusage,beautiful
vote
answeredDec6'12at21:35
share|improvethisanswer
user1816548
1,337315
Thesecondpassdoesnothavetobesequentialisn'tit?Itcanbedonewithabunchoffseek()callsifwestorethelocationofeachlinealongwiththehashI
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 50/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
believe.AsiriRathnayakeDec6'12at22:06
No,thepointisthatifyoustorelocations,youarestoringalotmorethanthecoupleofbitsperentrythatBloomfiltersstore.user1816548Dec6'12at
22:08
Isee,IhavemisunderstoodtheBloomfilter.Thanks!AsiriRathnayakeDec6'12at22:19
AfterreadingaboutBloomfilters,here'showIthinkitwillwork:(1)Buildandmaintainthebitmapforeachline.(2)Ifforaline,ifallthebitsarealready
1 inthevector,addthelinetoalistinmemory.Savethatforlater,becausethatindicatesthelineisprobablyalreadytherebefore.(3)Afteryou'redonewith
onepassofthefile,gothroughthelistinmemoryanddeterminewhichlinesareduplicates.JohnSmithDec8'12at3:33
Correct,exactlylikethat.user1816548Dec8'12at9:12
addacomment|
Runthroughthelinesandcomputelengthsofeachline.You'llendupwithsomethinglike:
0:4
1:6
2:10
3:4
....
Compareonlythooselinesthathavethesamelength.Workingwithsuchindexcanbefurtheroptimized(e.g.notstoringeverythinginaflatarray,butin
upvote0 somekindoftree,orwhatever).
downvote
Bytheway,yousecondideawithfilemightbedeclinedduetoperformancereasons.It'sgenerallybadideatohavefrequentrandomIOwithharddisk:
trytostoreasmuchasyoucaninmemory.
answeredDec6'12at21:34
editedDec6'12at21:39
share|improvethisanswer
omnomnom
38.7k793148
Ithinkthisisanelegantsolution,buttheymightcomplainthatyou'rehavingtouseextramemory.Ofcourse,ifthefilehasmanylineswiththesame
size,you'llhaveaproblem.JohnSmithDec8'12at3:37
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 51/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmsearchoraskyourown
question.
asked 2yearsago
viewed 138times
active 2yearsago
Lookingforajob?
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Related
1196
Grepafile,butshowseveralsurroundinglines?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
529
Findanintegernotamongfourbilliongivenones
0
Howtosearchcommonpasswordsfromtwogivenfilesofsize20GB?
3
Algorithmtofindsimilarityofquestions
648
FindingallfilescontainingatextstringonLinux
1
Howtofindthesetoftreeseveryoneofwhichspansoveranothergiventree?
0
ModifyingA*tofindapathtoclosestofmultiplegoalsonarectangulargrid
0
`3n`distinctelementsandfindingtwovalues,`x<y`?
0
SearchStringfromdatabaseoftextfiles,Ignoringspecialcharactersandpunctuation
HotNetworkQuestions
Whatistheoriginofthisphotoofanunexplodedbomb?
Troublewithterminatinga<apex:pageBlockSection>
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 52/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
CanIflywithagoldbar?
HowtodealwithaGMwhodoesnottelluseverything?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
Multiplypurefunctionwithscalar
Packagetodonotes:HowcanIchangethetextcolor?
Functionsthataretheirowninversion.
What'sanexpressionforacunninglyfakefriend?
Needtostartareligionwithapredefinedselfdestruct
Drawarrowinamindmap
Whatis`$?`?Isitavariable?
Needhelprecreatingcrazycolors/materialfromexample
CanIwriteapaperoutofasimpleidea
HowdoIupgradefromGPLv2toGPLv3?
Shouldmy(sequential)collectionstartatindex0orindex1?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
HowdoIfacilitateafirsttimeAgileretrospective?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
CanICultureBombfaraway?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
Patchingabinarywithdd
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 53/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Findwinnerinlistoftournamentmatches
Icheckedforduplicatequestionsonstackoverflow.Thiscouldbeclose:findnumberoftennismatchesrequired
ThisisanAmazoninterviewquestion.Iwanttoknowif(logp)operationsoncriticalpathistherightanswertothis(Onthesamelinesas
tournamentbarrieralgorithm>JohnMellorCrummey),for'p'players.
Sayforexample,wehave4players1,2,3,4.Wecanschedulematchesbetween:
1)Between(1&2)
2)Between(3&4)
3)organizethethirdmatchbetweenwinnersofthesetwomatches.
upvote0down Similarlyfor5(oddnumberof)playerswecouldschedulematchesbetween:
votefavorite
1)(1&2)and(3&4)
2)Winnerfrom(1&2)ORwinnerfrom(3&4)against5
3)Winnerbetweenwinnerofnotchosengroupandwinnerfrompreviousmatch
algorithm
editedMar16'13at18:22 askedMar16'13at17:45
share|improvethisquestion
angelatlarge user1071840
2,8212525 95111230
Sothequestionis"Whatisminimalnumberofmatchestowinatournamentwithpplayersifeachmatchinvolvestwoopposingplayers?Isthat
numberlog(p)?".Isthatthequestion?angelatlargeMar16'13at17:57
Wedon'tknowwhatthequestionwas.Votingtoclose.KarolyHorvathMar16'13at18:02
Igotitfromglassdoor.com,IwishIknewthecompletequestiontoo.user1071840Mar16'13at18:04
addacomment|
1Answer
activeoldestvotes
Everymatcheliminatesexactlyoneplayer.Toreducefrompplayersto1playerrequriesp1matches..
Ifyouareschedulingamaximalnumberofmatchesconcurrently,withtheconstraintthataplayercanparticipateinonlyonematchatatime,and
wanttoknowhawmanyroundsarerequired,thatisceiling(logp).
upvote4downvote
accepted answeredMar16'13at18:00
share|improvethisanswer
PieterGeerkens
7,1181937
Thanksforclearingtheconfusion.Isawmanypostswheretheanswerfor(n1)forplayersbuttheconstraintwasn'tveryclear.user1071840
Mar16'13at18:07
BeinganAhHa!question(Obviousandimpossibletoforgetonceseenbuttrickytorecognizeinitially.),itmakesaverypoorinterview
question.PieterGeerkensMar16'13at18:09
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 54/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmoraskyourownquestion.
asked 2yearsago
viewed 263times
active 2yearsago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Linked
0
findnumberoftennismatchesrequired
Related
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
11
InterviewquestionFindingnumbers
37
PossibleInterviewQuestion:HowtoFindAllOverlappingIntervals
0
findnumberoftennismatchesrequired
529
Findanintegernotamongfourbilliongivenones
2
Howtofindthewinnerofamodifiedothello/reversigame?
15
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 55/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Tennistournamentalgorithm
1
TennisTournamentPairing(1x3x5x7x9x(2n1))
1
FindingMaximumMatchingTopcoder
6
GraphTheory:AlgorithmtoFindWinnerinTournamentGraph(ifthereisany)
HotNetworkQuestions
Patchingabinarywithdd
40Numbersin9Bytes
HowdoIfacilitateafirsttimeAgileretrospective?
Thetwopronunciationsof
HowtodealwithaGMwhodoesnottelluseverything?
MementoVivereMomentumMori
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
SixMusicalFriends
Whyshouldakeybemadeexplicit?
Passfilenamefrombashtopython
Whydotheymanifestasrings?
Clientwantsfontaslogo
Howtodecidewhetherastoryisworthwriting?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Howtodrawsequenceofshapeswitharrowsandtext
Removestaticobjectsfromanimagesequence
Troublewithterminatinga<apex:pageBlockSection>
Shouldmy(sequential)collectionstartatindex0orindex1?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
ThenthTernary
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
morehotquestions
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 56/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Givenanumber,howtofindaclosestnumberinaseriesoffloatingpointdata
IcameacrossthisquestionwhilelookingforAmazoninterviewquestionsandwantedtoask.
Givenanumber,howcanyoufindtheclosestnumberinaseriesoffloatingpointdata?
Ifeverythingisinteger,answerissubstractingthenumberfromeverynumberinthearray,thenlookfortheelementwithminimumabsolutevalueinthe
array.
upvote4
downvote Butwhenitcomestofloatingpoints,itshouldbehighlynontirival.
favorite
2 Aniideas??Thanks.
algorithmfloatingpointprecision
askedMay13at19:32
editedMay13at20:04
share|improvethisquestion
DogacanSbdb
242
2 Whydoyouthinkfloatingpointchangesthealgorithm?MarkRansomMay13at19:43
Whatexactlydoes"series"mean?Canyousortitandusebinarysearch?Binarysearchshouldn'thaveproblemswithfloatingpoint.KolmarMay13
1
at19:45
Ifeverythingisinteger,answerissubstractingthenumberfromeverynumberinthearray,thenlookfortheminimalelementofthe
array.don'tyoumeanminimalabsolutevalue(i.e.closesttozero)?OramIcompletelymisunderstandingwhatyouaretryingtoachieve?amitMay
13at19:47
@MarkRansomTheproblemwithfloatingpointislimitedprecision.Examples:1)x=1e100,arr=[1,1,0].Answershouldbe1,butallabsvaluesof
2 differencesareequalto1e1002)x=1;arr=[1e100,1e100].Thenanswershouldbe1e100butbothabsofdifferencesareequalto1e100.(and
binarysearchwon'thelpinthelattercaseaswell...)KolmarMay13at19:55
@amit,yougotitcompletelycorrect.Imeantabsolutevalue,mywritingwasn'tcorrect.DogacanSbdbMay13at20:03
|show4morecomments
1Answer
activeoldestvotes
Theproblemwithfloatsisroundingerrors.However,comparisonoffloatsisnotsubjecttoroundingerrors:therefore,youcancorrectlyfindthenumberjust
biggerandjustsmallerthanxinlineartime:
sm=inf;
bg=inf;
for(ifrom0ton)
if(arr[i]>x&&arr[i]<bg)
bg=arr[i];
if(arr[i]<x&&arr[i]>sm)
sm=arr[i];
upvote1
downvote Nowyouonlyneedtodeterminewhichofthesetwonumbersisclosertox.Sincebgisbiggerandsmissmaller,theonlytimeyoucanhaveroundingerroris
whenbg>>xorx>>smineitherofthesecases,itwillonlyincreasethemagnitudeoftheroundeddifference.
(Ifthemagnitudesarethesame,forinstanceifx=1andarr=[1e100,1e100],youcanknowthatxisclosertothevaluewiththesamesignasitself.)
answeredMay13at21:25
share|improvethisanswer
Kittsil
56710
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 57/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmfloatingpointprecisionor
askyourownquestion.
asked 1monthago
viewed 116times
active 1monthago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
UIDeveloperataprofitableSaaSstartup
Recruiterbox
Bengaluru,India/relocation
htmlcss
Linked
38
HowshouldIdofloatingpointcomparison?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 58/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Related
324
Limitingfloatstotwodecimalpoints
28
Giventwolinesonaplane,howtofindintegerpointsclosesttotheirintersection?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
6
underlyingdatastructureforfloatinpython
529
Findanintegernotamongfourbilliongivenones
0
Floatingpointsystemerrorestimationintermsofmachineprecisionepsilon
1
Whyarethererandomtrashdigitsinfloatingpointnumbers?
0
Howcanweimproveerrorindecisionmakingbyapplyingconditioningonfloatingpointnumbers?
1
Whataretheuses/applicationsofSingleprecisionFloatingpointnumbers?
0
WhyfloatpointprecisioninChas7decimaldigitsofprecision?
HotNetworkQuestions
Isturninggraphitecarbonintodiamondindustriallydoable?
What'sthebestwaytoinvestformakingregulardonations?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
HowdoIupgradefromGPLv2toGPLv3?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Justifyingsuboptimalresearchqualitybylackofsupervision
Howtodrawsequenceofshapeswitharrowsandtext
Wordfor"animals,includinghumans"?
Clientwantsfontaslogo
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
Howtodecidewhetherastoryisworthwriting?
ALN*NTicTacToeGame
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Patchingabinarywithdd
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Whyshouldakeybemadeexplicit?
Whatis`$?`?Isitavariable?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
Antiferromagneticordering
HowcouldaresurrectedJesusproveheisJesus?
WhoinventedStarTreksideburnsandwhy?
FindingoutifawordisanAnagramofanother
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
morehotquestions
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 59/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Goodwaytostoredataaboutucustomerswhovisitedwwebpagesonddays
ThisisinterviewquestionfromAmazon.
Givenulistsofcustomerswhovisitedwwebpagesonddays,designadatastructuretogetcustomerswhohavevisitedthewebsiteonexactlykdaysand
shouldhavevisitedatleastmdistinctpagesaltogether.
upvote2 Assumeu,wanddarelargenumbers.
downvote
favorite Howdowestorethisinformation?Maybewecanusehashmaps,trees,etc.
4
algorithmdatastructurestree
editedJul8'13at14:29 askedJul8'13at10:09
share|improvethisquestion
Dukeling user1660982
33.2k83169 569512
2 Howcanthenumberofdaysbelarge,giventhatWWWhasbeenaroundforlessthan8,500days?dasblinkenlightJul8'13at10:19
@dasblinkenlightthisisthewayintervieweraskedsuchquestion..cantsaymuchaboutthatuser1660982Jul8'13at12:21
@dasblinkenlightGoodpoint,butIsupposethisismoreofatheoreticalquestion,testingtheknowledge/potentialoftheinterviewee.Forthesakeof
practicality,wecanprobablygeneralizetohours/minutesorassumethisdatastructurewillbeusedforthenextfewthousandyears.DukelingJul
8'13at13:32
Does"thewebsite"mean"anygivenwebsite"?AndIsupposeit'sncustomers,owebpagesandpdays(presumablydifferentnumbersn=n=n
whilen?=o?=p).DukelingJul8'13at13:34
@Dukelingyahcorrect.user1660982Jul9'13at7:11
addacomment|
3Answers
activeoldestvotes
Assumptions:
Wehavequerieswhichgivesomewebpagejandaskforalistofusersthathavevisitedthewebpagesonexactlykdaysandhavevisitedatleastmdistinct
pagesintotal.
Forthebelow,assume"map"="hashmap",whichwould,ideally,giveconstanttimequeries.Onecanalsouse"treemap"atalogarithmiccosti.t.othe
numberofelements.Similarlyfor"set","hashset","treeset".
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 60/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
I'massumingtheinputisn'tstatic,butIwon'treallychangemyapproachifitis.
Basicidea:
Foreachuser,haveamapofwebpagestocountsandlastvisitedday.Wecanhaveamapofuseridentifierstothemapofwebpages.
Wheneverauservisitsapage:
Ifit'sanewpage,justcreateamapentrywiththepagetoacountof1andthelastvisitedday
otherwise,ifthedayisthesameasthelastvisitedday,donothing,
otherwise,incrementthecountandupdatethelastvisitedday.
Totaltimeperupdate=O(1)
Forqueries:
LoopthroughallusersO(u)
LookupthepageforthatuserandcheckthatthecountmatchesO(1)
Checkthatthecountofthemapis>=mO(1)
upvote3 Totaltimeperquery=O(n)
downvote
Improvements:
WecanhaveaseparatemapofwebpagetouniqueID(thenobviouslyusetheuniqueIDinsteadoftheURLfortheabovemap).Itwon'treallychange
thecomplexity,butshouldimproveboththespaceandtimecomplexitybyaconstantfactor.
Atthecostofquiteabitofspace,wecandothefollowing(inadditiontohavingthemapfromBasicidea):
Foreachwebpage,haveanarrayofsetsofuseridentifierswhereindexiinthearrayisasetofallusersthatvisitedthatpageonexactlyidays.
Wheneverauservisitsapage:
DothesameasinBasicidea
Movetheuserfromthecurrentnumberofvisitsforthatpagetothenewnumberofvisits(orinsertintothe1visitsetifnew).
Totaltimeperupdate=O(1)
Forqueries:
WecanfindallusersthatvisitedanygivenpageonexactlykdaysinO(1).
Fromherewerunthroughthissmallerlistofusers(saytherearepofthem)andcheckthecountsofthemapsofeachuser(inO(1)).
Totaltimeperquery=O(p)
FeelfreetopointoutifImissedanything.
answeredJul8'13at14:25
editedJul8'13at14:30
share|improvethisanswer
Dukeling
33.2k83169
addacomment|
ThemoststraightforwardstructurewouldbetoemulatewhatanRDBMSwoulddo:
1.Haveanobjectthatcontainsallthebasicinfo:(Customer,DaysCount,DistinctPagesCount)
2.Then,addaTreethatfunctionsasanindextothis,using(DaysCount,DistinctPagesCount)asitskey(Btree,orsomethingsimilar)
3.YoucouldalsohaveanotherindextypestructurewithkeyofCustomer.Thatway,youcanupdatetheinformationquickly
upvote1
downvote 4.Finally,youwouldneedtohavemoredetailedinformationtofigureoutwhetherapagebeingvistedwasunique.ThiswouldinvolvestoringDistinctpage
informationunderthecustomer(notclearfromthequestionifthismeansdistinctonaparticularday,oracrossalldays)
answeredJul8'13at14:40
share|improvethisanswer
DariusX.
1,573821
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 61/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Implementusingtwohashmaps:
1. hashmap<customerId,HashSet<webpages>>
2. hashmap<customerId,HashSet<days>>
Ifnewcustomeridthencreatenewhashsetinsertinitelseputthatdayorwebpageinhashsetforexistingcustomer.
upvote1downvote
Foreachcustomeridseesetlength>=minfirsthashmapandinsecondhashmapsetlength=koutputthatcustomer.
editedDec1'13at15:20 answeredDec1'13at15:01
share|improvethisanswer
KonradKokosa cooldude
10.4k11133 111
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdatastructurestreeorask
yourownquestion.
asked 2yearsago
viewed 558times
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 62/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
active 1yearago
Lookingforajob?
ChiefSoftwareArchitectJava$100K
Crossover
Bengaluru,India/remote
eclipsenetbeans
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Related
0
Howtostoreandcollectdataforminingsuchinformationasmostviewedforlast24hours,last7days,last30days,last365days?
5
DesignaDataStructureforwebservertostorehistoryofvisitedpages
1
designanalgorithmtodoquerieswithinalogfile
5
Mostefficientwaytoconstructalinkedlistfromstoreddata?
3
Efficientdatastructureforalistofindexsets
5
LookingforamatureMTreeimplementation
1
Indexingfulltextsearchqueriesforefficientfanout
3
UsingBTreeinsteadofTrie
2
Determinethetop'm'mostoccurringkPagesequence
3
JavaLibraryprovidingperfecthashing?
HotNetworkQuestions
WhatdoesitmeanifanACmotorhastwovoltageratings?
Wordfor"animals,includinghumans"?
SixMusicalFriends
Multiplypurefunctionwithscalar
Functionsthataretheirowninversion.
HowdoIupgradefromGPLv2toGPLv3?
Thetwopronunciationsof
Doblockingcreatureshealbacktofullbetweenphases?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Whyadding"incolour"whenreferringto"WizardofOz"?
Whydosocksstink?
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
40Numbersin9Bytes
Howtodecidewhetherastoryisworthwriting?
Whyshouldakeybemadeexplicit?
HowcanIcheckifmyfunctionprint/echo'ssomething?
Justifyingsuboptimalresearchqualitybylackofsupervision
Needhelprecreatingcrazycolors/materialfromexample
Whydotheymanifestasrings?
NineTallMenAreStandingTall
Isturninggraphitecarbonintodiamondindustriallydoable?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
FindingoutifawordisanAnagramofanother
Nicelytypesettingverbatimtext
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. WordPress
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 63/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
4. Web Development Answers 4. SeasonedAdvice (Judaism) (stats) Exchange
Applications 5. Geographic 3. SharePoint (cooking) 4. Travel 3. Theoretical 3. Area51
5. AskUbuntu InformationSystems 4. User 5. Home 5. Christianity ComputerScience 4. Stack
6. Webmasters 6. Electrical Experience Improvement 6. Arqade(gaming) 4. Physics Overflow
7. Game Engineering 5. Mathematica 6. PersonalFinance 7. Bicycles 5. MathOverflow Careers
Development 7. AndroidEnthusiasts 6. Salesforce &Money 8. Roleplaying 6. more(7)
8. TeX 8. InformationSecurity 7. more(14) 7. Academia Games
LaTeX 8. more(10) 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Howtofind3numbersinincreasingorderandincreasingindicesinanarrayin
lineartime
Icameacrossthisquestiononawebsite.Asmentionedthere,itwasaskedinamazoninterview.Icouldn'tfigureoutapropersolutioningiven
constraint.Pleasehelp.
Givenanarrayofnintegers,find3elementssuchthata[i]<a[j]<a[k]andi<j<kin0(n)time.
upvote7downvote
favorite arraysalgorithm
6 editedApr4'12at9:50 askedApr4'12at9:08
share|improvethisquestion
IvayloStrandjev rajneesh2k10
42.5k54692 168212
1 So,whathaveyoutried?HenkHoltermanApr4'12at9:12
@HenkHoltermanMythinkingtookmetosimilardirectionasoftwall'sapproachbelow.ButfinallyIendedupwithfindingoutbugsinmy
ownsolution...:(rajneesh2k10Apr4'12at15:57
addacomment|
8Answers
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 64/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
activeoldestvotes
Sohereishowyoucansolvetheproblem.Youneedtoiterateoverthearraytwice.Onthefirstiterationmarkallthevaluesthathaveanelementgreater
thenthemontherightandontheseconditerationmarkalltheelementsmallerthenthemontheirleft.Nowyouranswerwouldbewithanelementthat
hasboth:
intgreater_on_right[SIZE];
intsmaller_on_left[SIZE];
memset(greater_on_rigth,1,sizeof(greater_on_right));
memset(smaller_on_left,1,sizeof(greater_on_right));
intn;//numberofelements;
inta[n];//actualelements;
intgreatest_value_so_far=a[n1];
intgreatest_index=n1;
for(inti=n2;i>=0;i){
if(greatest_value_so_far>a[i]){
greater_on_rigth[i]=greatest_index;
}else{
greatest_value_so_far=a[i];
greatest_index=i;
upvote17 }
downvote }
accepted
//Dothesameontheleftwithsmallervalues
for(inti=0;i<n;++i){
if(greater_on_rigth[i]!=1&&smaller_on_left[i]!=1){
cout<<"Indices:"<<smaller_on_left[i]<<","<<i<<","<<greater_on_rigth[i]<<endl;
}
}
Thissolutioniterates3timesoverthewholearrayandisthereforlinear.Ihavenotprovidedthewholesolutionsothatyoucantrainyourselfontheleft
toseeifyougetmyidea.Iamsorrynottogivejustsometipsbutcouldn'tfigureouthowtogiveatipwithoutshowingtheactualsolution.
Hopethissolvesyourproblem.
answeredApr4'12at9:40
share|improvethisanswer
IvayloStrandjev
42.5k54692
Greatthinking!Mywayofdoingithadtomanyflaws,Iadmit,Ishouldhavethoughtinabroadersense:lineardoesn'tatallmeaninoneiteration,
1
eventhoughIamquitesureitwouldbedoable.I'lltrytofindasolutionlater!devsndApr4'12at9:47
Awesomandperfect!!rajneesh2k10Apr5'12at2:23
CorrectmeifIamwrong,butiftheinputis{1,2,3,4}youarenotfindingallthetriplets,whichare[1,2,3][1,2,4][1,3,4][2,3,4]danieleSep26'13
at10:24
@danieleyouareonlyrequiredtofindonetriplet,notallofthem.Youcannotexpecttobeabletoprintalltripletsinlineartimeastheirnumber
maybecubic.IvayloStrandjevSep26'13at10:46
addacomment|
Didyoufindthisquestioninteresting?Tryournewsletter
Signupforournewsletterandgetourtopnewquestionsdeliveredtoyourinbox(seeanexample).
emailaddress Subscribe
Success!Pleaseclickthelinkintheconfirmationemailtoactivateyour Subscribed!
subscription.
Ipostedanotherapproachtoresolveithere.
#include<stdio.h>
//Afunctiontofundasortedsubsequenceofsize3
voidfind3Numbers(intarr[],intn)
{
intmax=n1;//Indexofmaximumelementfromrightside
intmin=0;//Indexofminimumelementfromleftside
inti;
//Createanarraythatwillstoreindexofasmaller
//elementonleftside.Ifthereisnosmallerelement
//onleftside,thensmaller[i]willbe1.
int*smaller=newint[n];
smaller[0]=1;//firstentrywillalwaysbe1
for(i=1;i<n;i++)
{
if(arr[i]<arr[min])
{
min=i;
smaller[i]=1;
}
else
smaller[i]=min;
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 65/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
}
//Createanotherarraythatwillstoreindexofa
//greaterelementonrightside.Ifthereisnogreater
//elementonrightside,thengreater[i]willbe1.
int*greater=newint[n];
greater[n1]=1;//lastentrywillalwaysbe1
for(i=n2;i>=0;i)
{
if(arr[i]>arr[max])
{
upvote2downvote max=i;
greater[i]=1;
}
else
greater[i]=max;
}
//Nowfindanumberwhichhasbothagreaternumberon
//rightsideandsmallernumberonleftside
for(i=0;i<n;i++)
{
if(smaller[i]!=1&&greater[i]!=1)
{
printf("%d%d%d",arr[smaller[i]],
arr[i],arr[greater[i]]);
return;
}
}
//Ifwereachnumber,thentherearenosuch3numbers
printf("Nosuchtripletfound");
return;
}
//Driverprogramtotestabovefunction
intmain()
{
intarr[]={12,11,10,5,6,2,30};
intn=sizeof(arr)/sizeof(arr[0]);
find3Numbers(arr,n);
return0;
}
editedJun8'12at21:10 answeredJun8'12at20:35
share|improvethisanswer
nickb Pramod
39.7k53674 211
1 exactlysameasthesolutiongivenby@IvayloStrandjev.TryingAug1'13at2:51
addacomment|
Justforfun:InJAVA:
List<Integer>OrderedNumbers(int[]nums){
List<Integer>res=newLinkedList<>();
intn=nums.length;
//iflessthen3elements,returntheemptylist
if(n<3)returnres;
//run1forlooptodeterminelocalminandlocalmaxforeachindex
int[]lMin=newint[n],lMax=newint[n];
lMin[0]=nums[0];lMax[n1]=nums[n1];
for(inti=1;i<n1;i++){
lMin[i]=Math.min(lMin[i1],nums[i]);
lMax[ni1]=Math.max(lMax[ni],nums[ni1]);
}
upvote1downvote //ifaconditionismetwheremin(whichalwayscomesbeforenums[i]andmax)<nums[i]<max,addtoresultsetandreturn;
for(inti=1;i<n1;i++){
if(lMin[i]<nums[i]&&nums[i]<lMax[i]){
res.add(lMin[i]);
res.add(nums[i]);
res.add(lMax[i]);
returnres;
}
}
returnres;
}
answeredJun2at21:12
share|improvethisanswer
so_jin_ee
45416
addacomment|
Trytocreatetwovariables:
1.index_sequence_length_1=indexisuch
a[i]isminimalnumber
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 66/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
2.index_sequence_length_2=indexjsuch
Thereisindexi<jsuchthata[i]<a[j]anda[j]isminimal
upvote0down Iterateoverwholearrayandupdatethisvariablesineachiteration.
vote
Ifyouiterateoverelementthatisgreaterthana[index_sequence_length_2],thanyoufoundyoursequence.
answeredApr4'12at9:18
share|improvethisanswer
JarosawGomuka
2,448519
Ithinkthedescriptionisincomplete!Lotsofcaseshavenotbeenconsideredandtheapproachisnotleadingtotoacorrectsolution.
rajneesh2k10Apr14'12at13:46
addacomment|
Sorry,icouldn'tresistbuttosolvethepuzzle...Hereismysolution.
//arrayindices
inti,j,k=1;
//valuesatthoseindices
intiv,jv,kv=0;
for(intl=0;l<a.length();l++){
//ifthereisavaluegreaterthanthebiggestvalue
//shiftallvaluesfromktoi
if(a[l]>kv||j==1||i==1){
i=j;
iv=jv;
upvote0 j=k;
jv=kv
downvote kv=a[l]
k=l
}
if(iv<jv&&jv<kv&&i<j&&j<k){
break;
}
}
answeredApr4'12at9:16
editedApr4'12at9:41
share|improvethisanswer
devsnd
3,08311429
+1.Nice.:)Iwouldn'thaveusediv,jv,andkvthough,butIguessit'smoreefficientthatwaysoIcan'tcomplain.Howwouldyouknowyou've
foundit?Checkifi!=j&&j!=k.NeilApr4'12at9:19
Whatisthissupposedtodo?Fortheinput"100,1,2,3"youwillonlysetkv=100andthatisit,whilethereisavalidsetofthreenumbers.Ivaylo
2
StrandjevApr4'12at9:23
@izomorphius,goodpoint.Iwouldaddif(a[l]>kv||k<2)NeilApr4'12at9:27
Iupdatedmyanswer,thanksfortheinput,izomorphius&NeildevsndApr4'12at9:29
OKandnowwhatwouldyoudofortheinput"1001,100,200,1,2,3"?Idonotthinkyourapproachisinthecorrectdirection.IvayloStrandjevApr
4'12at9:31
addacomment|
Iterateonceanddone:
publicstaticint[]orderedHash(int[]A){
intlow=0,mid=1,high=2;
for(inti=3;i<A.length;i++){
if(A[high]>A[mid]&&A[mid]>A[low])
break;
if(A[low]>A[i])
low=mid=high=i;
elseif(low==mid&&mid==high)
mid=high=i;
elseif(mid==high){
if(A[high]<A[i])
high=i;
else
mid=high=i;
}
elseif(A[mid]<A[i])
high=i;
elseif(A[high]<A[i]){
mid=high;
high=i;
upvote0 }
down else
vote mid=high=i;
}
returnnewint[]{A[low],A[mid],A[high]};
}//
Thentestwithmain:
publicstaticvoidmain(String[]args){
int[][]D={{1,5,5,3,2,10},
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 67/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
{1,5,5,6,2,10},
{1,10,5,3,2,6,12},
{1,10,5,6,8,12,1},
{1,10,5,12,1,2,3,40},
{10,10,10,3,4,5,7,9}};
for(int[]E:D){
System.out.format("%sGIVES%s%n",Arrays.toString(E),Arrays.toString(orderedHash(E)));
}
}
answeredApr4'12at19:16
share|improvethisanswer
kasavbere
2,77021949
Thanksforreply,butitsalwaysgoodtowritealgorithmforbetterunderstandingofothersratherthanjustbombardingyourcode.Evenifyouaredoing
1
so,itshouldbewellcommented.:)Codesarewelcomeincasetheideacannotbeexpressedwellinalgorithms...rajneesh2k10Apr12'12at9:20
ThisisjustaforloopandafewifelsesoIfiguredthiswaseasytofollow.Anyspecificsyoudon'tunderstand?Iwillbehappytohelp.kasavbereApr
12'12at18:47
NowIlookedatyourcodeandI'mafraiditsnotproducingcorrectresult!Trythistestcase:3,10,5,1,11rajneesh2k10Apr14'12at2:51
addacomment|
WhatifyoubuildamaxheapO(n)andthendoExtractMaxO(1)3times?
upvote0down answeredApr10'12at20:59
vote
share|improvethisanswer
barefootshoes
415
Itdoesn'tfulfiltheconstraintsmentioned!!Moreoveryouneedtocheckthecomplexitiesyoumentioned...:)rajneesh2k10Apr12'12at
16:46
addacomment|
StartcreatingabinarySearchTree,eachNodewillcontainaintegercounttotracknoofrightchilds.
eachweareinsertingarightchildweincrementthecountofitsparent.
Ifcountofanynodereaches2,thenthatnodeanditsnodesintherightsubtreewillgiveyoutheresult
upvote0downvote Complexityofthissollutionnlog(n)
answeredJun19'12at13:39
share|improvethisanswer
Tejas
194
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 68/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedarraysalgorithmoraskyourown
question.
asked 3yearsago
viewed 5794times
active 1monthago
Jobsnearyou
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
MorejobsnearMumbai
Related
22
FindanumberwhereitappearsexactlyN/2times
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
22
FindtheElementOccurringbtimesinananarrayofsizen*k+b
15
givenanarray,findoutthenextminimumelementforeachelement
3
Decimaldominantnumberinanarray
2450
Pairsocksfromapileefficiently?
4
Findasortedsubsequenceofsize4inanarrayinlineartime
8
Findthenumberofcoupleswiththesamedifferenceinasortedarray
1
Separatingnumbersandalphabetsinanarray
36
Howtofindtheonlynumberinanarraythatdoesn'toccurtwice
HotNetworkQuestions
Whycan'tanonabeliangroupbe75%abelian?
Clientwantsfontaslogo
MementoVivereMomentumMori
Multiplypurefunctionwithscalar
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
WhoinventedStarTreksideburnsandwhy?
Derivativeofadefiniteintegralissue
Patchingabinarywithdd
Passfilenamefrombashtopython
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 69/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Wordfor"animals,includinghumans"?
HowdoIupgradefromGPLv2toGPLv3?
Canmathbesubjective?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
Jumpingcarwithtoomanyamps?
howcanItaketotalminutesfromtime?
Ciertasconjugacionesverbalesnoconvencionales
What'sanexpressionforacunninglyfakefriend?
WhatdoesitmeanifanACmotorhastwovoltageratings?
Whyshouldakeybemadeexplicit?
Drawarrowinamindmap
Isthereawordforpeopleincapableofthinking?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Howtofindthedeepestpathfromrootmadeupofonly1'sinabinarysearch
tree?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 70/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Wehaveabinarytree(notaBST)madeupofonly0sand1s.weneedtofindthedeepest1withapathfromrootmadeuponlyof1's
Source:AmazoninterviewQ
upvote5downvotefavorite algorithmdatastructuresbinarytree
4 editedMay13'13at5:27 askedMay24'11at12:52
share|improvethisquestion
TheIndependentAquarius kc3
3,5981774166 7213913
2 findthelastnodeofthelongestsequenceof1s?MarinoimiMay24'11at12:54
@MarinoSimicYeskc3May24'11at12:57
Isrootshouldbe1?ILLUMINATI7590May24'11at13:15
addacomment|
1Answer
activeoldestvotes
publicstaticintfindMaxOnesDepth(Noderoot){
if(root!=null&&root.getValue()==1){
returnMath.max(1+findMaxOnesDepth(root.getLeft()),
1+findMaxOnesDepth(root.getRight());
}
else{
return0;
}
}
Ifthenodeyouareonisa'0',thenthedepthof'1'sis0.Otherwise,ifthenodeyouareonisa'1',thenadd1tothemaximum'one'sdepth'ofbothyour
leftandrightchildrenandreturnthemaximumofthose.
Theabovecodefindsthelength,tofindtheactualnodesalongthepath,youcouldusealisttokeeptrackofthis
publicstaticArrayList<Node>findLongestOnesPath(Noderoot){
ArrayList<Node>currStack=newArrayList<Node>();
if(root!=null&&root.getValue()==1){
upvote9
downvote currStack.add(root);
ArrayList<Node>leftStack=findLongestOnesPath(root.getLeft());
ArrayList<Node>rightStack=findLongestOnesPath(root.getRight());
if(leftStack.size()>rightStack.size()){
currStack.addAll(leftStack);
}
else{
currStack.addAll(rightStack);
}
returncurrStack;
}
answeredMay24'11at13:01
editedMay24'11at18:20
share|improvethisanswer
Shafeen
1613
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 71/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdatastructuresbinarytree
oraskyourownquestion.
asked 4yearsago
viewed 626times
active 2yearsago
Lookingforajob?
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareDevelopmentEngineerUI
AudienceScience
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 72/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Pune,India
htmlcss
Related
33
Thebestwaytocalculatetheheightinabinarysearchtree?(balancinganAVLtree)
66
FindkthsmallestelementinabinarysearchtreeinOptimumway
13
Findpathsinabinarysearchtreesummingtoatargetvalue
1
Binarytreevisit:getfromoneleaftoanotherleaf
12
binarysearchvsbinarysearchtree
4
Findingaloopinapossiblymalformedbinarytreebyusingtherelationbetweenthenumberofverticesandnumberofedges
1
CreateAncestorMatrixfromgivenBinaryTree
0
ImplementingtheaddmethodforaBinarySearchTree
0
ConstructionofBinarySearchTreefrompreordertraversaliteratively(notrecursion)
1
WhyisaddinunbalancedBinarySearchTreeO(n)?
HotNetworkQuestions
FindingoutifawordisanAnagramofanother
FiveAnglesinaStar
Howtodecidewhetherastoryisworthwriting?
RollmyD&Dcharacter'sabilityscores
Whyadding"incolour"whenreferringto"WizardofOz"?
Multiplypurefunctionwithscalar
Wordfor"animals,includinghumans"?
Howtoprotectaspaceelevatoragainstterrorism
NineTallMenAreStandingTall
zero,zerosorzeroes?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Paidcashforacar,butdealerwantstochangeprice
40Numbersin9Bytes
Canmathbesubjective?
Nicelytypesettingverbatimtext
Whatwereshoesolesmadefrominpreviousages?
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
Derivativeofadefiniteintegralissue
Doblockingcreatureshealbacktofullbetweenphases?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Packagetodonotes:HowcanIchangethetextcolor?
WhydosomepeoplerefertoLinuxasGNU/Linux?
OptimalRopeBurning
SixMusicalFriends
morehotquestions
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 73/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Iwasaskedthisinarecentinterview
IwasaskedtostayawayfromHashMaporanysortofHashing.
Thequestionwentsomethinglikethis
LetssayyouhavePRODUCTIDsofupto20decimals,alongwithProductDescriptions.WithoutusingMapsoranysortofhashingfunction,what'sthe
best/mostefficientwaytostore/retrievetheseproductIDsalongwiththeirdescriptions?
upvote4
downvote WhyisusingMapsabadideaforsuchascenario?
favorite
6 WhatchangeswouldyoumaketosellyoursolutiontoAmazon?
algorithmdatastructures
editedOct11'09at16:03 askedOct11'09at15:17
share|improvethisquestion
JW. maximus
21.9k166992 234
Upto20PRODUCTID's,oruptoPRODUCTID'swith20digits?SedatKapanogluOct11'09at15:23
Thissoundslikeapureinterviewquestiontoallowtheinterviewersto"seehowyouthink."In"therealworld"ProductIdandDescriptionwouldjust
1 betwocolumnsofadatabasetable.Andifyouonlyneededtotrack20products,well,thatjustsoundslikeashoppingcartandwhocaresifyouusea
hashmaporacommadelimitedlist?PaulSasikOct11'09at15:50
ProductIDcouldbeupto20decimaldigitsmaximusOct11'09at15:52
2 20decimalproductIDs,not20decimalproductIDs.kentlaw.edu/academics/lrw/grinker/LwtaCompound_Adjectives.htmindivOct11'09at16:03
SinceIamnewtothiscommunity,isitpossibletochoosemultiplecorrectanswers?maximusOct11'09at19:35
|show1morecomment
14Answers
activeoldestvotes
Amapisgoodtousewheninsert/remove/lookupoperationsareinterleaved.EveryoperationsareamortizedinO(logn).
Inyourexempleyouareonlydoingsearchoperation.Youmayconsiderthatanydatabaseupdate(inserting/removingaproduct)won'thappensomuchtime.
Thereforeprobablytheinterviewerwantyoutogetthebestdatastructureforlookupoperations.
InthiscaseIcanseeonlysomeasalreadyproposedinotheranswers:
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 74/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Sortedarray(doingabinarysearch)
Hasmap
trie
Withatrie,ifproductidsdonotshareacommonprefix,thereisgoodchancetofindtheproductdescriptiononlylookingatthefirstcharacteroftheprefix(or
onlytheveryfirstcharacters).Forinstance,let'stakethatproductidlist,with125products:
"1"
"2"
"3"
upvote ...
11down "123"
vote "124"
accepted "1234567"
Let'sassumeyouarelookingfortheproductidtitled"1234567"inyourtrie,onlylookingtothefirstletters:"1"then"2"then"3"then"4"willleadtothegood
productdescription.Noneedtoreadtheremainingoftheproductidasthereisnootherpossibilities.Consideringtheproductidlengthasn,yourlookupwill
beinO(n).Butasintheexempleexplaineditaboveitcouldbeevenfastertoretreivetheproductdescription.AstheprocductIDislimitedinsize(20
characters)thetrieheightwillbelimitedto20levels.Thatactuallymeansyoucanconsiderthelookupoperationswillnevergoesbeyondaconstanttime,as
yoursearchwillnevergoesbeyongthetrieheight=>O(1).WhileanyBSTlookupsareatbestamortizedO(logN),Nbeingthenumberofitemsinyour
tree.
Whileanhashmapcouldleadyoutoslowerlookupasyou'llneedtocomputeanindexwithanhashfunctionthatisprobablyimplementedreadingthewhole
productidlength.Plusbrowsingalistincaseofcollisionwithotherproductids.
Doingabinarysearchonasortedarray,andperformanceinlookupoperationswilldependsonthenumberofitemsinyourdatabase.
answeredOct11'09at16:15
editedOct11'09at17:02
share|improvethisanswer
yvesBaumes
4,92222353
Noticethatinspiteofthecorrectpointsyouraiseinfavorofthetrie,themainreasonhashesarechosenovertriesarecachelocality.AnnaOct12'09at
19:22
@Annatrue,Iexpectanhashtablenottohavetoomuchcollisionthushavingveryshortlist.Inpracticeitisworthtotestboth.yvesBaumesOct12'09
at20:28
+1Crystalclear...YanfleaFeb20'12at23:00
addacomment|
ABTreeinmyopinion.DoesthatstillcountasaMap?
up Mostlybecauseyoucanhavemanyitemsloadedatonceinmemory.Searchingtheseitemsinmemoryisveryfast.
vote6
down answeredOct11'09at15:23
vote
share|improvethisanswer
EdisonGustavoMuenz
3,17022034
BSTwasmyanswertoobuttheinterviewertoldmethateveryoneguessesBSTwhenaskednottousemaps.IstherereallyabettersolutionthanBSTor
wasIjustBSed?maximusOct11'09at15:25
IvoteforBSed.BSTworksextremelywellwithnumbers,becauseallit'sdoingislessthan/greaterthan.Ithinkhe'sjustgotafavoritealgorithmandwants
1 youtoguessit,sinceBSTisaperfectlyvalid(andrealworld)answer.Funfact:std::mapisusuallyimplementedasaBST.Sodoesthatmakeita"Map?"
TojiOct11'09at15:39
Oh,andwhatintheworldishelookingforwhenasking:"WhatchangeswillyoudotosellyoursolutiontoAmazon?"Doeshemean"Wouldyoudoit
differentlyifsellingittoathirdparty?"or"Wouldyoudoitdifferentlyifsellingtoathirdpartywithextremeneeds?"Ifthelatter,theansweris:Don'thave
meimplementit,useadatabaseinstead!:)I'mnotsureIreallyfollowthisguy'strainoflogic.TojiOct11'09at15:43
6 BST(BinarySearchTree)!=BTreeFogleBirdOct11'09at16:13
IagreewithTojiwhenhetoldheguessestheinterviewerwantedmaximustoavoidtofocusonmap,oranyotherkindofBinarysearchtreetofindthe
1 solutionhetoughwasthebest.SGI'sSTLMapareimplementedusingredblacktreeasfarasIknow,whichisaBSTamongstothers.yvesBaumesOct
11'09at16:58
|show3morecomments
Consecutiveintegernumbersgiveperfectchoiceforthehashmapbutitonlyhasoneproblem,asitdoesnothavemultithreadedaccessbydefault.Alsosince
AmazonwasmentionedinyourquestionImaythinkthatyouneedtotakeintoaccountconcurencyandRAMlimitationissues.
Whatyoumightdointheresponsetosuchquestionistoexplainthatsinceyouaredissallowedtouseanybuiltindatastorageschemes,allyoucandoisto
"emulate"one.
So,let'ssayyouhaveM=10^20productswiththeirnumbersanddescriptions.YoucanpartitionthissettothegroupsofNsubsets.ThenyoucanorganizeM/N
containerswhichhavesugnificantlyreducednumberofelements.Usingthisidearecursivelywillgiveyouawaytostorethewholesetincontainerswithsuch
propertythataccesstothemwouldhaveacceptedperformancerate.
Toillustratethisidea,considerasmallerexampleofonly20elements.Iwouldlikeyoutoimagivethefilesystemwithdirectories"1","2","3","4".Ineach
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 75/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
directoryyoustoretheproductdescriptionsasfilesinthefollowingway:
up
vote folder1:files1to5
folder2:files6to10
4 ...
down folder4:files16to20
vote
Thenyoursearchwouldonlyneedtwostepstofindthefile.First,yousearchforacorrectfolderbydividing20/5(yourM/N).Then,youusethegivenIDtoread
theproductdescriptionstoredinafile.
Thisisjustaveryroughdescription,however,theideaisveryintuitive.So,perhapsthisiswhatyourinterviewerwantedtohear.
Asformyself,whenIfacesuchquestionsoninterview,evenifIfailtogetthequestioncorrectly(whichistheworstcase:))Ialwaystrytogetthecorrectanswer
fromtheinterviewer.
answeredOct11'09at16:19
editedOct11'09at17:04
share|improvethisanswer
alexkr
3,14611220
Thatsagoodtaketoo.Solocatingthecorrectfolderwillbeinconstanttimebutlocatingthefilewillbeo(n)wherenrepresentsthenumberoffilesstoredin
everyfolder.maximusOct11'09at16:26
@AlexyourideaisclosetotheTriedatastructure(seemyanswer).ButaccordingtomeusingaTrieisbetterchoice:inyourexempleyoudeepenthefolder
leveluptoapointthereisonlyonefileperfolder.HavealooktothewikipediapageforTrieimplementation.Nicereading:)yvesBaumesOct11'09at
16:36
Theideaofmypostingwastointroducethewayofstoringdatawithoutuseofanydatastructureatall.TrieisgoodbutasfarasIunderstandtheoriginal
posterhadrestrictionofnotabletouseanydatastructures.ThedisadvantageoftheTrieaswellasanyMaporHashTableisthatyouneedtostorethisina
distributedway(IthinkthatswhyAmazonwasmentioned).Inmypostyouseethatallyouneedtohaveisadistributedfilesystem.So,abouttheO(n)inthe
folder,youareright,youcanpartitionyoursetasdeepaspossibleuntilyouhave1fileonly.alexkrOct11'09at16:48
+1:ThisisthefirstsolutionthatcametomindwhenIreadtheproblem,andprobablywhatIwouldgivetopcreditforinaninterviewusethefilesystem.
JohnPirieOct11'09at17:26
theinterviewerprobablywantedtohaveaalgorithmickindofanswer.Iwouldn'texpectsuchanswerifIwereaninterviewerforadeveloperjob.Butwho
1
knows.yvesBaumesOct11'09at17:36
|show1morecomment
Best/efficientforwhat?Wouldhavebeenmyanswer.
E.g.forstoringthem,probablythefastthingtodoaretwoarrayswith20elementseach.Onefortheids,onforthedescription.Iteratingoverthoseis
prettyfastto.Anditisefficientmemorywise.
upvote2down Ofcoursethesolutionisprettyuselessforanyrealapplication,butsoisthequestion.
vote
answeredOct11'09at15:38
share|improvethisanswer
JensSchauder
27.4k865145
addacomment|
ThereisaninterestingalternativetoBTree:RadixTree
upvote1 answeredOct11'09at15:43
down
vote editedOct11'09at16:00
share|improvethisanswer
Kamarey
5,12713154
Kamareyyoursolutionisclosetomine.Thewikipediapageyouarepointingoutexplainwellwhyapatriciatrie(orradixtree)iswelcomedhere,
providedthattheproductIDisboundedto20characters.Seethesectiontitled"Comparisontootherdatastructures"onthewikipedia'sradixtreepage.
yvesBaumesOct11'09at17:11
addacomment|
Ithinkwhathewantedyoutodo,andI'mnotsayingit'sagoodidea,istousethecomputermemoryspace.
Ifyouusea64bit(virtual)memoryaddress,andassumingyouhavealltheaddressspaceforyourdata(whichisneverthecase)youcanstoreaonebytevalue.
YoucouldusetheProductIDasanaddress,castingittoapointer,andthengetthatbyte,whichmightbeanoffsetinanothermemoryforactualdata.
upvote Iwouldn'tdoitthisway,butperhapsthatistheanswertheywerelookingfor.
1down
vote Asaf
answeredOct11'09at16:16
share|improvethisanswer
AsafR
3,59843158
Thatsaninterestingapproach.maximusOct11'09at16:21
Idon'tseehowthiscouldworkreliablyingeneral...whatiftheproductID,whencasttoapointer,pointstosomeothercriticalpieceof(nonproduct)data
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 76/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
thatyourappisusing?Ifyouthenwriteproductinfotothatlocation,yourappwillbecorruptedifyoudon't,youcan'tstoreinformationforthatproduct
ID.JeremyFriesnerOct11'09at17:38
@JeremyIt'snotaveryfeasiblesolution,butwith20decimaldigitsanda64bitaddressspaceyouareleftwithsome"extraspace".Makeahandcrafted
processthatfulfillsrequestsforIDresolutionandhavenootherappactivityinthatprocess.It'spossibletocreatehierarchiestohavelessmemoryineach
process.Iwouldn'tdoitifIwerepaidto,maybeifmylifedependedonit.Maybe.AsafROct11'09at19:35
addacomment|
Iwonderiftheywantedyoutonotethatinanecommerceapplication(suchasAmazon's),acommonusecaseis"reverselookup":retrievetheproductIDusing
thedescription.Forthis,aninvertedindexisused,whereeachkeywordinadescriptionisanindexkey,whichisassociatedwithalistofrelevantproduct
identifiers.Binarytreesorskiplistsaregoodwaystoindexthesekeywords.
Regardingtheproductidentifierindex:Inpractice,BTrees(whicharenotbinarysearchtrees)wouldbeusedforalarge,diskbasedindexof20digit
upvote identifiers.However,theymayhavebeenlookingforatoysolutionthatcouldbeimplementedinRAM.Sincethe"alphabet"ofdecimalnumbersissosmall,it
1down lendsitselfverynicelytoatrie.
vote
answeredOct11'09at22:01
share|improvethisanswer
erickson
149k31231342
addacomment|
Thehashmapsworkreallywellifthehashingfunctiongivesyouaveryuniformdistributionofthehashvaluesoftheexistingkeys.Withreallybadhash
functionitcanhappensothathashvaluesofyour20valueswillbethesame,whichwillpushtheretrievaltimetoO(n).Thebinarysearchontheotherhand
guarantiesyouO(logn),butinsertingdataismoreexpensive.
upvote Allofthisisveryincremental,thebiggeryourdatasetisthelessarethechancesofabadkeydistribution(ifyouareusingagood,provenhashalgorithm),and
0down onsmallerdatasetsthedifferencebetweenO(n)andO(logn)isnotmuchtoworryabout.
vote
answeredOct11'09at15:31
share|improvethisanswer
mfeingold
5,41111736
addacomment|
Ifthesizeislimitedsometimesit'sfastertouseasortedlist.
WhenyouuseHashanything,youfirsthavetocalculateahash,thenlocatethehashbucket,thenuseequalsonallelementsinthebucket.Soitalladdsup.
OntheotherhandyoucouldusejustasimpleArrayList(oranyotherListflavorthatissuitablefortheapplication),sortitwithjava.util.Collections.sort
andusejava.util.Collections.binarySearchtofindanelement.
upvote0 ButasArtyomhaspointedoutmaybeasimplelinearsearchwouldbemuchfasterinthiscase.
down
vote Ontheotherhand,frommaintainabilitypointofview,IwouldnormallyuseHashMap(orLinkedHashMap)here,andwouldonlydosomethingspecialhere
whenprofilerwouldtellmetodoit.Alsocollectionsof20haveatendencytobecomecollectionsof20000overtimeandallthisoptimizationwouldbe
wasted.
answeredOct11'09at15:44
share|improvethisanswer
AlexanderPogrebnyak
28.7k54880
addacomment|
There'snothingwrongwithhashingorBtreesforthiskindofsituationyourinterviewerprobablyjustwantedyoutothinkalittle,insteadofcomingoutwith
theexpectedanswer.It'sagoodsign,wheninterviewerswantcandidatestothink.Itshowsthattheorganizationvaluesthought,asopposedtomerelyparroting
outsomethingfromthelecturenotesfromCS0210.
Incidentally,I'massumingthat"20decimalproductids"means"alargecollectionofproductids,whoseformatis20decimalcharacters"....becauseifthere's
only20ofthem,there'snovalueinconsideringthealgorithm.Ifyoucan'tusehashingorBtreescodealinearsearchandmoveon.Ifyoulike,sortyourarray,
anduseabinarysearch.
upvote Butifmyassumptionisright,thenwhattheinterviewerisaskingseemstorevolvearoundthetime/spacetradeoffofhashmaps.It'spossibletoimproveonthe
0down time/spacecurveofhashmapshashmapsdohavecollisions.Soyoumightbeabletogetsomeimprovementbyconvertingthe20decimaldigitstoanumber,
vote andusingthatasanindextoasparselypopulatedarray...areallybigarray.:)
SellingittoAmazon?Goodluckwiththat.Whateveryoucomeupwithwouldhavetobepatentable,andnothinginthisdiscussionseemstorisetothatlevel.
answeredOct11'09at15:47
share|improvethisanswer
CPerkins
5,72121840
IalsotoldhimaboutconvertingtheDecimalnumber(upto20digits)tosomethingsmallerandthenstoringtheminanarrayindexonwhichtheresponseI
gotwas"Howisthisnothashing"?maximusOct11'09at15:56
Becauseconvertingadecimalnumbertoabinarynumberisreversiblewhereashashfunctionsloseinformationandthusarenotreversible.PaulOct11
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 77/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
'09at16:09
addacomment|
20decimalPRODUCTIDs,alongwithProductDescription
Simplelinearsearchwouldbeverygood...
Iwouldcreateonesimplearraywithids.Andotherarraywithdata.
upvote0down
vote Linearsearchforsmallamountofkeys(20!)ismuchmoreefficientthenanybinarytreeorhash.
editedOct11'09at16:17 answeredOct11'09at15:36
share|improvethisanswer
JimFerrans Artyom
15.2k63464 19.1k1281164
Andwhenis2432902008176640000=20!consideredsmallamountofkeysforalinearsearch?:)Thatsatotaloverkill.alexkrOct11'09at
2
16:02
@AlexYepIguesstoo.yvesBaumesOct11'09at16:33
addacomment|
Ihaveafeelingbasedontheiransweraboutproductidsandtwodigitstheanswertheywerelookingforistoconvertthenumericproductidsintoa
differentbasesystemorpackedform.
Theymadeapointtoindicatetheproductdescriptionwaswiththeproductidstotellyouthatahigherbasesystemcouldbeusedwithinthecurrent
upvote0down fieldsdatatype.
vote
answeredOct11'09at16:40
share|improvethisanswer
Einstein
3,16411217
addacomment|
Yourinterviewermightbelookingforatrie.Ifyouhavea[small]constantupperboundonyourkey,thenyouhaveO(1)insertandlookup.
answeredOct11'09at16:56
upvote0downvote
share|improvethisanswer
ElleryNewcomer
779418
addacomment|
Ithinkwhathewantedyoutodo,andI'mnotsayingit'sagoodidea,istousethecomputermemoryspace.
Ifyouusea64bit(virtual)memoryaddress,andassumingyouhavealltheaddressspaceforyourdata(whichisneverthecase)youcan
storeaonebytevalue.
Unfortunately2^64=approx=1.8*10^19.Justslightlybelow10^20.Coincidence?
log2(10^20)=66.43.
Here'saslightlyevilproposal.
OK,2^64bitscanfitinsideamemoryspace.
AssumeaboundofNbytesforthedescription,sayN=200.(whowantstodownloadAnnaKareninawhenthey'relookingfortoasters?)Commandeer
upvote0 8*N64bitmachineswithheavyRAM.Amazoncanswingthis.
downvote
Everymachineloadsintheir(verysparse)bitmaponebitofthedescriptiontextforalldescriptions.LettheMMU/virtualmemoryhandlethesparsity.
Broadcasttheproducttagasa59bitnumberandthebitmaskforonebyte.(59=ceil(log2(10^20))8)
Everymachinereturnsonebitfromtheproductdescription.Lookupsareavirtualmemorydereference.Youcaneveninsertanddelete.
Ofcoursepagingwillstarttobeabitchatsomepoint!
Oddlyenough,itwillworkthebestifproductid'sareasclumpyandungoodahashaspossible.
answeredOct12'09at8:50
editedOct12'09at9:02
share|improvethisanswer
MattKennel
1142
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 78/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdatastructuresoraskyour
ownquestion.
asked 5yearsago
viewed 1905times
active 5yearsago
Jobsnearyou
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
MorejobsnearMumbai
Related
35
Algorithm/DataStructureDesignInterviewQuestions
33
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 79/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Whyaresomanyalgorithmproblemsaskedininterviews?
9
HowtoDealwithAlgorithm/DataStructuresProblemsinInterviewProcess?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
5
InterviewQuestion:Datastructureforalargesocialnetwork
7
MSpaintcodeaskedinaninterview
19
Arrayof10000having16bitelements,findbitsset(unlimitedRAM)Googleinterview
4
Algorithms/DataStructuresInterview
5
Interview:Suggestadatastructurewhichoptimizesinsertion,deletionandrandomvaluegeneration
4
InterviewQ:Givenmstationandnhouse,outputnearestkstationsforeachhouse
HotNetworkQuestions
Howtodecidewhetherastoryisworthwriting?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
WhoinventedStarTreksideburnsandwhy?
ImageOpensasLayer0ratherthanBackground
Antiferromagneticordering
HowdoIupgradefromGPLv2toGPLv3?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Whyshouldakeybemadeexplicit?
DoesaUSB3.0connectionrequireaUSB3.0cord?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Whatisatemporarysolutionforadamagedcarbody?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
PythonLabelExpression?ArcGIS10.3.1
Canmathbesubjective?
FiveAnglesinaStar
Whyweren'ttheWeasleysapartoftheOriginalOrder?
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
Whycan'tanonabeliangroupbe75%abelian?
Isturninggraphitecarbonintodiamondindustriallydoable?
Howtodrawsequenceofshapeswitharrowsandtext
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
DoesCIDRreally"doaway"withIPaddressclasses?
Whydotheymanifestasrings?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 80/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Iwasaskedthisinarecentinterview
IwasaskedtostayawayfromHashMaporanysortofHashing.
Thequestionwentsomethinglikethis
LetssayyouhavePRODUCTIDsofupto20decimals,alongwithProductDescriptions.WithoutusingMapsoranysortofhashingfunction,what'sthe
best/mostefficientwaytostore/retrievetheseproductIDsalongwiththeirdescriptions?
upvote4
downvote WhyisusingMapsabadideaforsuchascenario?
favorite
6 WhatchangeswouldyoumaketosellyoursolutiontoAmazon?
algorithmdatastructures
editedOct11'09at16:03 askedOct11'09at15:17
share|improvethisquestion
JW. maximus
21.9k166992 234
Upto20PRODUCTID's,oruptoPRODUCTID'swith20digits?SedatKapanogluOct11'09at15:23
Thissoundslikeapureinterviewquestiontoallowtheinterviewersto"seehowyouthink."In"therealworld"ProductIdandDescriptionwouldjust
1 betwocolumnsofadatabasetable.Andifyouonlyneededtotrack20products,well,thatjustsoundslikeashoppingcartandwhocaresifyouusea
hashmaporacommadelimitedlist?PaulSasikOct11'09at15:50
ProductIDcouldbeupto20decimaldigitsmaximusOct11'09at15:52
2 20decimalproductIDs,not20decimalproductIDs.kentlaw.edu/academics/lrw/grinker/LwtaCompound_Adjectives.htmindivOct11'09at16:03
SinceIamnewtothiscommunity,isitpossibletochoosemultiplecorrectanswers?maximusOct11'09at19:35
|show1morecomment
14Answers
activeoldestvotes
Amapisgoodtousewheninsert/remove/lookupoperationsareinterleaved.EveryoperationsareamortizedinO(logn).
Inyourexempleyouareonlydoingsearchoperation.Youmayconsiderthatanydatabaseupdate(inserting/removingaproduct)won'thappensomuchtime.
Thereforeprobablytheinterviewerwantyoutogetthebestdatastructureforlookupoperations.
InthiscaseIcanseeonlysomeasalreadyproposedinotheranswers:
Sortedarray(doingabinarysearch)
Hasmap
trie
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 81/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Withatrie,ifproductidsdonotshareacommonprefix,thereisgoodchancetofindtheproductdescriptiononlylookingatthefirstcharacteroftheprefix(or
onlytheveryfirstcharacters).Forinstance,let'stakethatproductidlist,with125products:
"1"
"2"
"3"
upvote ...
11down "123"
vote "124"
accepted "1234567"
Let'sassumeyouarelookingfortheproductidtitled"1234567"inyourtrie,onlylookingtothefirstletters:"1"then"2"then"3"then"4"willleadtothegood
productdescription.Noneedtoreadtheremainingoftheproductidasthereisnootherpossibilities.Consideringtheproductidlengthasn,yourlookupwill
beinO(n).Butasintheexempleexplaineditaboveitcouldbeevenfastertoretreivetheproductdescription.AstheprocductIDislimitedinsize(20
characters)thetrieheightwillbelimitedto20levels.Thatactuallymeansyoucanconsiderthelookupoperationswillnevergoesbeyondaconstanttime,as
yoursearchwillnevergoesbeyongthetrieheight=>O(1).WhileanyBSTlookupsareatbestamortizedO(logN),Nbeingthenumberofitemsinyour
tree.
Whileanhashmapcouldleadyoutoslowerlookupasyou'llneedtocomputeanindexwithanhashfunctionthatisprobablyimplementedreadingthewhole
productidlength.Plusbrowsingalistincaseofcollisionwithotherproductids.
Doingabinarysearchonasortedarray,andperformanceinlookupoperationswilldependsonthenumberofitemsinyourdatabase.
answeredOct11'09at16:15
editedOct11'09at17:02
share|improvethisanswer
yvesBaumes
4,92222353
Noticethatinspiteofthecorrectpointsyouraiseinfavorofthetrie,themainreasonhashesarechosenovertriesarecachelocality.AnnaOct12'09at
19:22
@Annatrue,Iexpectanhashtablenottohavetoomuchcollisionthushavingveryshortlist.Inpracticeitisworthtotestboth.yvesBaumesOct12'09
at20:28
+1Crystalclear...YanfleaFeb20'12at23:00
addacomment|
ABTreeinmyopinion.DoesthatstillcountasaMap?
up Mostlybecauseyoucanhavemanyitemsloadedatonceinmemory.Searchingtheseitemsinmemoryisveryfast.
vote6
down answeredOct11'09at15:23
vote
share|improvethisanswer
EdisonGustavoMuenz
3,17022034
BSTwasmyanswertoobuttheinterviewertoldmethateveryoneguessesBSTwhenaskednottousemaps.IstherereallyabettersolutionthanBSTor
wasIjustBSed?maximusOct11'09at15:25
IvoteforBSed.BSTworksextremelywellwithnumbers,becauseallit'sdoingislessthan/greaterthan.Ithinkhe'sjustgotafavoritealgorithmandwants
1 youtoguessit,sinceBSTisaperfectlyvalid(andrealworld)answer.Funfact:std::mapisusuallyimplementedasaBST.Sodoesthatmakeita"Map?"
TojiOct11'09at15:39
Oh,andwhatintheworldishelookingforwhenasking:"WhatchangeswillyoudotosellyoursolutiontoAmazon?"Doeshemean"Wouldyoudoit
differentlyifsellingittoathirdparty?"or"Wouldyoudoitdifferentlyifsellingtoathirdpartywithextremeneeds?"Ifthelatter,theansweris:Don'thave
meimplementit,useadatabaseinstead!:)I'mnotsureIreallyfollowthisguy'strainoflogic.TojiOct11'09at15:43
6 BST(BinarySearchTree)!=BTreeFogleBirdOct11'09at16:13
IagreewithTojiwhenhetoldheguessestheinterviewerwantedmaximustoavoidtofocusonmap,oranyotherkindofBinarysearchtreetofindthe
1 solutionhetoughwasthebest.SGI'sSTLMapareimplementedusingredblacktreeasfarasIknow,whichisaBSTamongstothers.yvesBaumesOct
11'09at16:58
|show3morecomments
Consecutiveintegernumbersgiveperfectchoiceforthehashmapbutitonlyhasoneproblem,asitdoesnothavemultithreadedaccessbydefault.Alsosince
AmazonwasmentionedinyourquestionImaythinkthatyouneedtotakeintoaccountconcurencyandRAMlimitationissues.
Whatyoumightdointheresponsetosuchquestionistoexplainthatsinceyouaredissallowedtouseanybuiltindatastorageschemes,allyoucandoisto
"emulate"one.
So,let'ssayyouhaveM=10^20productswiththeirnumbersanddescriptions.YoucanpartitionthissettothegroupsofNsubsets.ThenyoucanorganizeM/N
containerswhichhavesugnificantlyreducednumberofelements.Usingthisidearecursivelywillgiveyouawaytostorethewholesetincontainerswithsuch
propertythataccesstothemwouldhaveacceptedperformancerate.
Toillustratethisidea,considerasmallerexampleofonly20elements.Iwouldlikeyoutoimagivethefilesystemwithdirectories"1","2","3","4".Ineach
directoryyoustoretheproductdescriptionsasfilesinthefollowingway:
up folder1:files1to5
vote folder2:files6to10
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 82/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
4 ...
down folder4:files16to20
vote
Thenyoursearchwouldonlyneedtwostepstofindthefile.First,yousearchforacorrectfolderbydividing20/5(yourM/N).Then,youusethegivenIDtoread
theproductdescriptionstoredinafile.
Thisisjustaveryroughdescription,however,theideaisveryintuitive.So,perhapsthisiswhatyourinterviewerwantedtohear.
Asformyself,whenIfacesuchquestionsoninterview,evenifIfailtogetthequestioncorrectly(whichistheworstcase:))Ialwaystrytogetthecorrectanswer
fromtheinterviewer.
answeredOct11'09at16:19
editedOct11'09at17:04
share|improvethisanswer
alexkr
3,14611220
Thatsagoodtaketoo.Solocatingthecorrectfolderwillbeinconstanttimebutlocatingthefilewillbeo(n)wherenrepresentsthenumberoffilesstoredin
everyfolder.maximusOct11'09at16:26
@AlexyourideaisclosetotheTriedatastructure(seemyanswer).ButaccordingtomeusingaTrieisbetterchoice:inyourexempleyoudeepenthefolder
leveluptoapointthereisonlyonefileperfolder.HavealooktothewikipediapageforTrieimplementation.Nicereading:)yvesBaumesOct11'09at
16:36
Theideaofmypostingwastointroducethewayofstoringdatawithoutuseofanydatastructureatall.TrieisgoodbutasfarasIunderstandtheoriginal
posterhadrestrictionofnotabletouseanydatastructures.ThedisadvantageoftheTrieaswellasanyMaporHashTableisthatyouneedtostorethisina
distributedway(IthinkthatswhyAmazonwasmentioned).Inmypostyouseethatallyouneedtohaveisadistributedfilesystem.So,abouttheO(n)inthe
folder,youareright,youcanpartitionyoursetasdeepaspossibleuntilyouhave1fileonly.alexkrOct11'09at16:48
+1:ThisisthefirstsolutionthatcametomindwhenIreadtheproblem,andprobablywhatIwouldgivetopcreditforinaninterviewusethefilesystem.
JohnPirieOct11'09at17:26
theinterviewerprobablywantedtohaveaalgorithmickindofanswer.Iwouldn'texpectsuchanswerifIwereaninterviewerforadeveloperjob.Butwho
1
knows.yvesBaumesOct11'09at17:36
|show1morecomment
Best/efficientforwhat?Wouldhavebeenmyanswer.
E.g.forstoringthem,probablythefastthingtodoaretwoarrayswith20elementseach.Onefortheids,onforthedescription.Iteratingoverthoseis
prettyfastto.Anditisefficientmemorywise.
upvote2down Ofcoursethesolutionisprettyuselessforanyrealapplication,butsoisthequestion.
vote
answeredOct11'09at15:38
share|improvethisanswer
JensSchauder
27.4k865145
addacomment|
ThereisaninterestingalternativetoBTree:RadixTree
upvote1 answeredOct11'09at15:43
down
vote editedOct11'09at16:00
share|improvethisanswer
Kamarey
5,12713154
Kamareyyoursolutionisclosetomine.Thewikipediapageyouarepointingoutexplainwellwhyapatriciatrie(orradixtree)iswelcomedhere,
providedthattheproductIDisboundedto20characters.Seethesectiontitled"Comparisontootherdatastructures"onthewikipedia'sradixtreepage.
yvesBaumesOct11'09at17:11
addacomment|
Ithinkwhathewantedyoutodo,andI'mnotsayingit'sagoodidea,istousethecomputermemoryspace.
Ifyouusea64bit(virtual)memoryaddress,andassumingyouhavealltheaddressspaceforyourdata(whichisneverthecase)youcanstoreaonebytevalue.
YoucouldusetheProductIDasanaddress,castingittoapointer,andthengetthatbyte,whichmightbeanoffsetinanothermemoryforactualdata.
upvote Iwouldn'tdoitthisway,butperhapsthatistheanswertheywerelookingfor.
1down
vote Asaf
answeredOct11'09at16:16
share|improvethisanswer
AsafR
3,59843158
Thatsaninterestingapproach.maximusOct11'09at16:21
Idon'tseehowthiscouldworkreliablyingeneral...whatiftheproductID,whencasttoapointer,pointstosomeothercriticalpieceof(nonproduct)data
thatyourappisusing?Ifyouthenwriteproductinfotothatlocation,yourappwillbecorruptedifyoudon't,youcan'tstoreinformationforthatproduct
ID.JeremyFriesnerOct11'09at17:38
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 83/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
@JeremyIt'snotaveryfeasiblesolution,butwith20decimaldigitsanda64bitaddressspaceyouareleftwithsome"extraspace".Makeahandcrafted
processthatfulfillsrequestsforIDresolutionandhavenootherappactivityinthatprocess.It'spossibletocreatehierarchiestohavelessmemoryineach
process.Iwouldn'tdoitifIwerepaidto,maybeifmylifedependedonit.Maybe.AsafROct11'09at19:35
addacomment|
Iwonderiftheywantedyoutonotethatinanecommerceapplication(suchasAmazon's),acommonusecaseis"reverselookup":retrievetheproductIDusing
thedescription.Forthis,aninvertedindexisused,whereeachkeywordinadescriptionisanindexkey,whichisassociatedwithalistofrelevantproduct
identifiers.Binarytreesorskiplistsaregoodwaystoindexthesekeywords.
Regardingtheproductidentifierindex:Inpractice,BTrees(whicharenotbinarysearchtrees)wouldbeusedforalarge,diskbasedindexof20digit
upvote identifiers.However,theymayhavebeenlookingforatoysolutionthatcouldbeimplementedinRAM.Sincethe"alphabet"ofdecimalnumbersissosmall,it
1down lendsitselfverynicelytoatrie.
vote
answeredOct11'09at22:01
share|improvethisanswer
erickson
149k31231342
addacomment|
Thehashmapsworkreallywellifthehashingfunctiongivesyouaveryuniformdistributionofthehashvaluesoftheexistingkeys.Withreallybadhash
functionitcanhappensothathashvaluesofyour20valueswillbethesame,whichwillpushtheretrievaltimetoO(n).Thebinarysearchontheotherhand
guarantiesyouO(logn),butinsertingdataismoreexpensive.
upvote Allofthisisveryincremental,thebiggeryourdatasetisthelessarethechancesofabadkeydistribution(ifyouareusingagood,provenhashalgorithm),and
0down onsmallerdatasetsthedifferencebetweenO(n)andO(logn)isnotmuchtoworryabout.
vote
answeredOct11'09at15:31
share|improvethisanswer
mfeingold
5,41111736
addacomment|
Ifthesizeislimitedsometimesit'sfastertouseasortedlist.
WhenyouuseHashanything,youfirsthavetocalculateahash,thenlocatethehashbucket,thenuseequalsonallelementsinthebucket.Soitalladdsup.
OntheotherhandyoucouldusejustasimpleArrayList(oranyotherListflavorthatissuitablefortheapplication),sortitwithjava.util.Collections.sort
andusejava.util.Collections.binarySearchtofindanelement.
upvote0 ButasArtyomhaspointedoutmaybeasimplelinearsearchwouldbemuchfasterinthiscase.
down
vote Ontheotherhand,frommaintainabilitypointofview,IwouldnormallyuseHashMap(orLinkedHashMap)here,andwouldonlydosomethingspecialhere
whenprofilerwouldtellmetodoit.Alsocollectionsof20haveatendencytobecomecollectionsof20000overtimeandallthisoptimizationwouldbe
wasted.
answeredOct11'09at15:44
share|improvethisanswer
AlexanderPogrebnyak
28.7k54880
addacomment|
There'snothingwrongwithhashingorBtreesforthiskindofsituationyourinterviewerprobablyjustwantedyoutothinkalittle,insteadofcomingoutwith
theexpectedanswer.It'sagoodsign,wheninterviewerswantcandidatestothink.Itshowsthattheorganizationvaluesthought,asopposedtomerelyparroting
outsomethingfromthelecturenotesfromCS0210.
Incidentally,I'massumingthat"20decimalproductids"means"alargecollectionofproductids,whoseformatis20decimalcharacters"....becauseifthere's
only20ofthem,there'snovalueinconsideringthealgorithm.Ifyoucan'tusehashingorBtreescodealinearsearchandmoveon.Ifyoulike,sortyourarray,
anduseabinarysearch.
upvote Butifmyassumptionisright,thenwhattheinterviewerisaskingseemstorevolvearoundthetime/spacetradeoffofhashmaps.It'spossibletoimproveonthe
0down time/spacecurveofhashmapshashmapsdohavecollisions.Soyoumightbeabletogetsomeimprovementbyconvertingthe20decimaldigitstoanumber,
vote andusingthatasanindextoasparselypopulatedarray...areallybigarray.:)
SellingittoAmazon?Goodluckwiththat.Whateveryoucomeupwithwouldhavetobepatentable,andnothinginthisdiscussionseemstorisetothatlevel.
answeredOct11'09at15:47
share|improvethisanswer
CPerkins
5,72121840
IalsotoldhimaboutconvertingtheDecimalnumber(upto20digits)tosomethingsmallerandthenstoringtheminanarrayindexonwhichtheresponseI
gotwas"Howisthisnothashing"?maximusOct11'09at15:56
Becauseconvertingadecimalnumbertoabinarynumberisreversiblewhereashashfunctionsloseinformationandthusarenotreversible.PaulOct11
'09at16:09
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 84/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
20decimalPRODUCTIDs,alongwithProductDescription
Simplelinearsearchwouldbeverygood...
Iwouldcreateonesimplearraywithids.Andotherarraywithdata.
upvote0down
vote Linearsearchforsmallamountofkeys(20!)ismuchmoreefficientthenanybinarytreeorhash.
editedOct11'09at16:17 answeredOct11'09at15:36
share|improvethisanswer
JimFerrans Artyom
15.2k63464 19.1k1281164
Andwhenis2432902008176640000=20!consideredsmallamountofkeysforalinearsearch?:)Thatsatotaloverkill.alexkrOct11'09at
2
16:02
@AlexYepIguesstoo.yvesBaumesOct11'09at16:33
addacomment|
Ihaveafeelingbasedontheiransweraboutproductidsandtwodigitstheanswertheywerelookingforistoconvertthenumericproductidsintoa
differentbasesystemorpackedform.
Theymadeapointtoindicatetheproductdescriptionwaswiththeproductidstotellyouthatahigherbasesystemcouldbeusedwithinthecurrent
upvote0down fieldsdatatype.
vote
answeredOct11'09at16:40
share|improvethisanswer
Einstein
3,16411217
addacomment|
Yourinterviewermightbelookingforatrie.Ifyouhavea[small]constantupperboundonyourkey,thenyouhaveO(1)insertandlookup.
answeredOct11'09at16:56
upvote0downvote
share|improvethisanswer
ElleryNewcomer
779418
addacomment|
Ithinkwhathewantedyoutodo,andI'mnotsayingit'sagoodidea,istousethecomputermemoryspace.
Ifyouusea64bit(virtual)memoryaddress,andassumingyouhavealltheaddressspaceforyourdata(whichisneverthecase)youcan
storeaonebytevalue.
Unfortunately2^64=approx=1.8*10^19.Justslightlybelow10^20.Coincidence?
log2(10^20)=66.43.
Here'saslightlyevilproposal.
OK,2^64bitscanfitinsideamemoryspace.
AssumeaboundofNbytesforthedescription,sayN=200.(whowantstodownloadAnnaKareninawhenthey'relookingfortoasters?)Commandeer
upvote0 8*N64bitmachineswithheavyRAM.Amazoncanswingthis.
downvote
Everymachineloadsintheir(verysparse)bitmaponebitofthedescriptiontextforalldescriptions.LettheMMU/virtualmemoryhandlethesparsity.
Broadcasttheproducttagasa59bitnumberandthebitmaskforonebyte.(59=ceil(log2(10^20))8)
Everymachinereturnsonebitfromtheproductdescription.Lookupsareavirtualmemorydereference.Youcaneveninsertanddelete.
Ofcoursepagingwillstarttobeabitchatsomepoint!
Oddlyenough,itwillworkthebestifproductid'sareasclumpyandungoodahashaspossible.
answeredOct12'09at8:50
editedOct12'09at9:02
share|improvethisanswer
MattKennel
1142
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 85/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdatastructuresoraskyour
ownquestion.
asked 5yearsago
viewed 1904times
active 5yearsago
Lookingforajob?
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Related
35
Algorithm/DataStructureDesignInterviewQuestions
33
Whyaresomanyalgorithmproblemsaskedininterviews?
9
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 86/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
HowtoDealwithAlgorithm/DataStructuresProblemsinInterviewProcess?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
5
InterviewQuestion:Datastructureforalargesocialnetwork
7
MSpaintcodeaskedinaninterview
19
Arrayof10000having16bitelements,findbitsset(unlimitedRAM)Googleinterview
4
Algorithms/DataStructuresInterview
5
Interview:Suggestadatastructurewhichoptimizesinsertion,deletionandrandomvaluegeneration
4
InterviewQ:Givenmstationandnhouse,outputnearestkstationsforeachhouse
HotNetworkQuestions
RollmyD&Dcharacter'sabilityscores
Whydotheymanifestasrings?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
40Numbersin9Bytes
Derivativeofadefiniteintegralissue
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Troublewithterminatinga<apex:pageBlockSection>
howcanItaketotalminutesfromtime?
Nicelytypesettingverbatimtext
IsWolframwrongaboutunique3colorability,oramIjustconfused?
HowtodealwithaGMwhodoesnottelluseverything?
What'sthebestwaytoinvestformakingregulardonations?
Functionsthataretheirowninversion.
Patchingabinarywithdd
ThenthTernary
Shouldmy(sequential)collectionstartatindex0orindex1?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Whyadding"incolour"whenreferringto"WizardofOz"?
HowdoIfacilitateafirsttimeAgileretrospective?
Multiplypurefunctionwithscalar
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
HowtoprovemyGmailhasbeenhacked?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Howtodrawsequenceofshapeswitharrowsandtext
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 87/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
LCAproblematinterview
SometimesIcomeacrossinterviewquestionslikethis:"Findthecommonparentofany2nodesinatree".InoticedthattheyaskLCAquestionsalsoat
Google,Amazon,etc.
AswikipediasaysLCAcanbefoundbyintersectionofthepathsfromthegivennodestotherootandittakesO(H),whereHistheheightofthetree.
Besides,therearemoreadvancedalgorithmsthatprocesstreesinO(N)andanswerLCAqueriesinO(1).
upvote3 IwonderwhatexactlyinterviewerswanttolearnaboutcandidatesaskingthisLCAquestion.Thefirstalgorithmofpathsintersectionseemstrivial.Do
downvote theyexpectthecandidatestorememberpreprocessingalgorithms?Dotheyexpectthecandidatestoinventthesealgorithmsanddatastructuresonthefly
favorite ?
3
algorithmleastcommonancestor
askedDec26'10at14:05
editedDec26'10at19:35
share|improvethisquestion
Michael
8,3392070151
itsnottrivialquestionifudontknowitalready.restrictionssuchasnotallowedtostoreparentandstoringadditionalnodesfor"general"treemakes
itbitdifficult.Iflunkedmyinterviewbcozofthisquestion:(PranaleeFeb18'13at15:25
addacomment|
2Answers
activeoldestvotes
Theywanttoseewhatyou'remadeof.Theywanttoseehowyouthink,howyoutackleonproblem,andhandlestressfromdeadline.Isupposethatifyou
solvetheproblembecauseyoualreadyknowthesolutionthentheywilljustposeyouanotherproblem.It'snotthesolutiontheywant,it'syourbrainz.
upvote8
down answeredDec26'10at14:14
vote
share|improvethisanswer
Dialecticus
10.2k31749
2 +1forgettingtotherootofthecompaniesdesire:smartpeople.DavidannDec26'10at16:03
+1,but@David,It'snotjustforIQtest,theywillseeyourmannerinhardsituationandyourreactionwhennewproblemcomestoyou.SaeedAmiri
1
Dec26'10at17:36
addacomment|
Withmanyalgorithmsquestionsinaninterview,Idon'tcare(orwant)youtoremembertheanswer.Iwantyoutobeabletoderivetheanswerfromthemain
principlesyouknow.
Realistically:Icouldgivetwocareslessifyoualreadyknowtheanswerto"howtodoX",ifyouareabletoquicklyconstructanansweronthefly.Ultimately:
intherealworld,Ican'tnecessarilyassumeyouhaveexperiencetacklingproblemsofdomainX,butifyourunacrossaprobleminsaiddomain,Iwillcertainly
up hopeyou'llhavetheanalyticalabilitytofigureoutareasonableanswer,basedonthegeneralknowledgeyouhold.
vote2
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 88/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
down Atreeisacommondatastructureit'ssafetoassumemostwillknowifyouknowtheansweroffhand,youshouldbeabletoexplainit.Ifyoudon'tknowthe
vote answer,butunderstandthedatastructure,youshouldbeabletofairyeasilyderivetheanswer.
answeredDec30'10at2:32
share|improvethisanswer
James
5,7891324
IconcurthatitisprettyeasytoderiveO(H)solution.Howeveritisprettydifficult(IMO)toderivethepreprocessingsolution.So,Iwonderifoneexpect
candidatestoderiveit.MichaelDec30'10at16:57
@MichaelIthinkallofthisappliesmoretothecasewhereyoudon'thaveparentpointers.ThatmakesitmoresuitablefortheprocessJamesisdescribing.
keyserSep27'14at16:43
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmleastcommonancestoror
askyourownquestion.
asked 4yearsago
viewed 2631times
active 4yearsago
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 89/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Lookingforajob?
DevOpsEngineerContinuousIntegration
DigitalAssess
Thiruvananthapuram,India
continuousintegrationjenkins
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Gettheweeklynewsletter!
Topquestionsand
answers
Important
announcements
Unanswered
questions
Signupforthenewsletter
Related
33
Whyaresomanyalgorithmproblemsaskedininterviews?
19
IsitcorrecttoasktosolveanNPcompleteproblemonajobinterview?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
3
Isthereabetterwaytofindlowestcommonancestor?
10
Interviewquestiononproblemsolving(arrays)
0
lcaofbinarytreeoftwonodesifthosetwonodesoccurmanytimes
3
modificationtoLCAcodeforbinarytreetocheckifnodeispresentinJava
1
InterviewQ:BinarytreeInordertraversal
2
FindmultipleLCAsinunrootedtree
1
What'swrongwiththisleastcommonancestoraglorithm?
HotNetworkQuestions
OptimalRopeBurning
DoesCIDRreally"doaway"withIPaddressclasses?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
HowcanIcheckifmyfunctionprint/echo'ssomething?
Multiplypurefunctionwithscalar
Whyshouldakeybemadeexplicit?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 90/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Needhelprecreatingcrazycolors/materialfromexample
Jumpingcarwithtoomanyamps?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Nicelytypesettingverbatimtext
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Removestaticobjectsfromanimagesequence
NineTallMenAreStandingTall
Justifyingsuboptimalresearchqualitybylackofsupervision
WhatdoesitmeanifanACmotorhastwovoltageratings?
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
Isthereawordforpeopleincapableofthinking?
FindingoutifawordisanAnagramofanother
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
Troublewithterminatinga<apex:pageBlockSection>
morehotquestions
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Longestchainofpairs
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 91/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Youaregivennpairsofnumbers.Ineverypair,thefirstnumberisalwayssmallerthanthesecondnumber.Apair(c,d)canfollow(a,b)
ifandonlyifbislessthanc.Chainsofpairscanbeformedinthismanner.Findthelongestchainofpairsformed.
IgotthisquestioninaninterviewwithAmazonbutcouldn'tfigureouttheanswer,justthatitisrelatedtotheLISproblem.
upvote9down
votefavorite algorithmlis
3 editedJul8'13at15:24 askedJul8'13at15:20
share|improvethisquestion
arshajii user2467973
71k13102160 515
Istheinitialorderingofpairsimportant?I.e.,inLIS,itemsinsubsequencehavetobeinsameorderanintheoriginalsequence.Isthisthecase
1
here,too?tobias_kJul8'13at15:28
Initiallyorderedinrandomorderuser2467973Jul8'13at15:30
Areyouallowedtosortthepairs?arunmoezhiJul8'13at15:40
Ithinkthequestionistoconsiderthegivenpermutationofnpairsandfindthelargestchainofpairsforthatgivenpermutation.Soweshouldn'tbe
1
sorting.arunmoezhiJul8'13at15:50
3 It'saclassicaldatastructureproblem.ThisproblemisavariationoftheproblemOPasks.FallenJul8'13at15:52
|show8morecomments
4Answers
activeoldestvotes
Becausethetwovaluesofeach(X,Y)pairmustbeinorder(X<Y),andtheYvalueofonepairmustbelessthantheXvalueofthenextpair,youare
essentiallybuildingonecontinuouschainofvaluesalongonedimension.YoujustneedtosortbytheYvalues.
Giventhissampledata:
(15,40)(5,8)(1,10)(6,8)(9,20)(2,4)(36,37)(34,35)(9,14)(30,31)
SortbyYtoget:
(2,4)(6,8)(5,8)(1,10)(9,14)(9,20)(30,31)(34,35)(36,37)(15,40)
Thenloopthrough,addingapairtothechainifitsXisgreaterthanthelastYinthechain,andignoringitotherwise.
Noticethatinthisexample,(6,8)happenedtobesortedbefore(5,8).Itdoesn'tmatterwhichpairischosenforthechainwhentheirYvaluesareequal,as
longastheXvaluesatisfiestheconditionofbeinggreaterthanthepreviousY.
upvote6 Here'sadiagramshowingthesortedpairsasbarsaboveanumberline.Startingatthefirstpair,(2,4),eachonethatisaddedtothechainatthebottomis
downvote coloredyellow.Visually,thegrayonesareskippedbecausethere'sayellowone"intheway"ofitbeingdroppedintothechain(overlappingvalues).
accepted
diagramofsortedpairs
Proof:TheonlywaytoincludemorepairsinthechainistoreplaceapairwithonewithasmallerYvalue,toallowforthenextpairtohaveasmallerX
value,potentiallyfittinganotherpairwhereitcouldn'tfitbefore.IfyoureplaceapairwithonewiththesameYvalue,yougainnothing.Ifthereplacement
hasalargerYvalue,allyou'vedoneispotentiallyblocksomepairsthatwould'vefitbefore.
BecausethepairshavebeensortedbyYvalues,youwillneverfindareplacementwithasmallerY.Looking"forward"inthesortedpairs,theywillallhave
thesameorgreaterYvalue.Looking"backward",anythatwereeliminatedfromthechaininitiallywerebecausetheXvaluewasn'thighenough,whichwill
stillbethecase.
answeredJul8'13at19:03
editedJul11'13at12:18
share|improvethisanswer
BrianStephens
2,625417
Canyouprovethatthiswillbethelongestchainpossible?Thanks!!user2467973Jul10'13at18:59
OK,Iaddedanexplanationthathopefullyprovesmypoint.BrianStephensJul11'13at12:19
Youjustdiscoveredtheactivityselectionproblem'ssolution!!Excellentanswer!!user2467973Jul25'13at17:54
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 92/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
First,thisproblemcanbeviewedasplottingpointsonatwodimensionalgridwherexcoordinateofeachpointislessthanycoordinateofthatpoint.Now
you'reaskedtofindthelongestchainsuchthateveryi+1thpointisbothaboveandtotherightoftheithpoint(andtheycoordinateoftheithpointislessthanx
coordinateofi+1thpoint).
nowlet'ssortthepointsfirstbasedontheirxcoordinate.Thenwestartvisitingthesortedpointsfromlowestxcoordinate,ifthere'satieforxcoordinatethen
we'llvisitpointswithhigherycoordinatefirst.nowforanexampleifwe'reworkingontheithpoint,weknowthatallpointsalreadyvisitedhaveloweror
similarxcoordinateoftheithone.Sothelongestchainendatpointiwillbethelongestchainthatwe'vealreadygotwithycoordinate<=xcoordinateofthe
up currentpoint.
vote1
down WecandoitefficientlywithanefficientdatastructurelikesegmenttreeorBinaryindexedtree.
vote
Runtimeofthissolutionis:O(NlgN)whereNisthenumberofpoints(pairsinthegivenproblem).
answeredJul8'13at16:05
editedJul8'13at18:06
share|improvethisanswer
Fallen
2,2341724
+1:However,notethattheconditionisnotquitethatpointsareupandtotheright.Consider(3,10)and(4,11).Thesecondpointisupandtotheright,but
2 thisisnotanadmissiblechainbecauseb=10isnotlessthanc=4.Nevertheless,Ithinkthisalgorithmworksifyousimplychangeittosearchforthelongest
chainwithycoordinate<xcoordinateofthecurrentpoint.PeterdeRivazJul8'13at18:01
Thanks!Nicecatch:)Edited...FallenJul8'13at18:06
addacomment|
Abasicwaytosolvingthisproblemwouldbetocreateatree,whereeachnodeisapair,andconstructdirectededgesfromonenodetoanotherwhenitislegal
(ie,"Apair(c,d)canfollow(a,b)ifandonlyifbislessthanc").Youcandoamodifiedbreadthfirsttraversalfromeachnodethatkeepstrackofthelengthof
up thelongestpathfromthatnode,andwhenyouarefinishedwiththatcanjustlookoverallthenodestofindthelongestpath.
vote0
down answeredJul8'13at17:06
vote
share|improvethisanswer
EricKim
185
addacomment|
Itseemstomethatonecharacteristicofthelongestchainisthatitminimizesthetotalspanofanytwoadjacenttuples(tomaximizethenumberofpossibletuples
foranyrange).
Inthatcase,asBrianStephenssuggested,weneedonlysortbythesecondnumber,ascending(toguaranteethesmallestspanwhensearchingforthenexttuple),
andbuildthechainstartingwiththefirsttupleinthesortedlist.
up
vote WecanprovethatthissolutionisoptimalbypositingthatifS(0)isthechainstartingonthefirsttuple,thereexistsanS(i),whereiisnotinS(0),thatislonger
0 thanS(0)andthereforealsoachainS(i+1)thatislongerthanS(1).Weknowthatthestartofimustbebeforetheendofi1oritwouldhavebeenincludedin
down S(0).Nowiftheendofi1wereequaltotheendofi,S(i+1)wouldbepartofS(0),whichcontradictsourpremise.Alternatively,iftheendofiweregreaterthan
vote theendofi1,againS(i+1)wouldbeincludedinS(0).Theendoficouldnotbelessthantheendofi1sincethelistissortedbythisproperty.
answeredJul9'13at21:14
editedJul10'13at3:44
share|improvethisanswer
3,417525
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 93/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmlisoraskyourownquestion.
asked 2yearsago
viewed 557times
active 1yearago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
108PeopleChatting
JavaScript
1houragoKendallFrey
Awal
Luggage:
Octavian
Madara
uselesschien:
Caprica
ssube:
Garg:
1 Damiean:
Uchiha:
1 Six:1
PHP
1houragoPeeHaa
PeeHaa:
bwoebi:
Rafee:
NikiC:
ircmaxell:
Joe user3692125:
1 1 1 1 1 Watkins: 1
Linked
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 94/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
5
LongestIncreasingSubsequence(LIS)withtwonumbers
3
MaximumLengthofPairsinincreasingorder
Related
18
longestincreasingsubsequence(O(nlogn))
2450
Pairsocksfromapileefficiently?
2
LongestIncreasingSubsequence
1
LongestIncresingSubsequencetosolvebuildingbridge
1
Longestchainofarrayofpairs
0
ImprovingtheLongestIncreasingSequenceAlgorithm
1
longestnondecreasingsubsequenceinO(nlgn)
0
Numberoflongestincreasingsubsequences
1
WhatisthemostoptimizedalgorithmtofindALLlongestincreasingsubsequence?
1
Determinewhichitemsinanarrayarepartoflongestincreasingsubsequence(s)
HotNetworkQuestions
CanIflywithagoldbar?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
Howtoprotectaspaceelevatoragainstterrorism
Whatistheoriginofthepowericon?
Thetwopronunciationsof
Antiferromagneticordering
ImageOpensasLayer0ratherthanBackground
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
FindingoutifawordisanAnagramofanother
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
HowtodealwithaGMwhodoesnottelluseverything?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
Whyshouldakeybemadeexplicit?
Patchingabinarywithdd
Wordfor"animals,includinghumans"?
Drawarrowinamindmap
CanIwriteapaperoutofasimpleidea
Shouldmy(sequential)collectionstartatindex0orindex1?
Howtogetearlyentryintomystictheurge?
Nicelytypesettingverbatimtext
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
HowdoIupgradefromGPLv2toGPLv3?
Howtodecidewhetherastoryisworthwriting?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 95/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Maximumnonsegmentsum
Wehavealist/arrayofnumbers(positivesandnegativesareallpossible).
Asegmentisdefinedascontiguoussubsequenceofthenumbers.Forexample,[12345]isthearrayandasegmentofitis[123]or[234],etc.All
numbersinasegmentmustbecontiguous.
Anonsegmentisdefinedasallsubsequencesofthearray,exceptallsegments.Socontiguousnumbersarepossibleinanonsegment,buttheremust
beatleasttwonumberswhicharenotcontiguous.
Forexample,[134]isanonsegment,[1235]isalsoanonsegmentbecause3and5arenotcontiguous(thereisa'4'betweenthemintheoriginal
array).
Thequestioniswhatisthenonsegmenthavingthemaximumsum?
upvote0 Note
downvote
favorite 1. Numberscanbemixofpositivesandnegatives
2. Itisnottheproblemofhttp://algorithmsbyme.wordpress.com/2012/07/29/amazoninterviewquestionmaximumpossiblesumwithnon
consecutivenumbers/orMaximumsumofnonconsecutiveelements.Inthoseproblems,nonumberscanbecontiguousandallnumbersare
positive.
Thisisproblem11inthebookPearlsoffunctionalalgorithmdesignanditsaysthereisalinearwaytosolveit.
ButIcan'tunderstandnorfindoutalinearway.SoItrymyluckhere.
algorithmfunctionalprogramming
askedJan9'14at23:42
share|improvethisquestion
JacksonTale
8,0501257141
addacomment|
3Answers
activeoldestvotes
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 96/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Here'sasolutionbettersuitedtothefunctionalprogrammingidiom.Onecanimagineafourstatefiniteautomatonthatacceptsstringshavingtwonon
adjacent1s.
0100,1
____________
v/1v/0v/1v/
>(q0)>(q1)>(q2)>((q3))
WhattheHaskellprogrambelowdoesisessentiallytoscanthenumbersoneatatimeandrememberthemaximumvaluesthatcanbemadeviachoicesthat,
wheninterpretedas0sand1s,puttheautomatoninstateq1(segmentEndingHere),stateq2(segmentNotEndingHere),orstateq3(nonSegment).Thistechniqueis
asledgehammerthatworksonmanyoftheseproblemsaboutoptimizationonasequence.
maximumNonSegmentSum::(Numa,Orda)=>[a]>Maybea
maximumNonSegmentSum=mnssNothingNothingNothing
upvote0 where
downvote (^+)::(Numa)=>a>Maybea>Maybea
accepted (^+)=liftM.(+)
+50
mnss::
(Numa,Orda)=>Maybea>Maybea>Maybea>[a]>Maybea
mnsssegmentEndingHeresegmentNotEndingHerenonSegmentxs
=casexsof
[]>nonSegment
x:xs'
>mnss((x^+segmentEndingHere)`max`Justx)
(segmentNotEndingHere`max`segmentEndingHere)
(((x`max`0)^+nonSegment)`max`(x^+segmentNotEndingHere))
xs'
answeredJan13'14at16:40
share|improvethisanswer
DavidEisenstat
21.2k51139
Ifiguredoutthewayfromthatbookjustbeforeyouranswer.thanks.Alsoithinkthisfunctionalwayisthebestthinkingandwillhelpimperativeway
aswell.Haveyoureadthatbook?JacksonTaleJan14'14at12:06
addacomment|
Takeallofthepositivenumbers.Iftheyformasegment,checkifyoucanaddinsomethingnotadjacenttoit.Alsocheckifyoucanpicksomethingoffinthe
middle.Alsocheckifyoucanpickoffanendandputinthenumbernexttoit.It'snottoohardtoprovethatoneoftheseleadstothebestnonsegment.
upvote0
down answeredJan10'14at0:33
vote
share|improvethisanswer
tmyklebu
9,60931141
addacomment|
Thereare2possibilities:
Thereexistsatmost2nonnegativenumbers,and,inthecaseof2existing,they'reneighbouring.
Inthiscasewepickthelargestpairofnonneighbouringnumbers.Thiscanbedoneinlineartimebyfindingthelargestnumberandthesumofthat
withthelargestnonneighbouringnumber,andthenthesumofbothitsneighbouringnumbers.
Example:
Input:[5,10,6,2,1,2,10]
Thelargestnumberis1,sowesum1andthelargestnonneighbouringnumber(5),whichgives6.Thenwealsotry2and2,giving4.Sothe
largestnonsegmentsumis4.
Thereexistsatleasttwononneighbouringnonnegativenumbers.
Wepickallpositivenumbers.Ifthelargestnumberiszero(i.e.therearenopositivenumbers),pickallthezero'sinstead.
Ifallthepickednumbersareconsecutive,tryto:
Excludethesmallestonethat'snotononeoftheends.
Includethelargest(i.e.closestto0)nonpositivenumberthat'snotneighbouringtothepickednumbers(ifthereexistssucha0,thiswouldbe
thebestoption).
Inturn,trytoexcludethenumbersfromtheendsofthesequence,thenincludethenonpositivenumbernexttoit(dothisonlyifthereexistsa
numbernexttoit).
upvote0 Picktheoptionheregivingthelargestsum.
downvote
Clearlyallofthiscanhappeninlineartime.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 97/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Example:
Input:[5,1,5,7,9,11,1,10]
Sofirstwepickallpositivenumbers5,7,9,11,butthey'reconsecutive.
Sowetrytoexcludethesmallestnonendnumber(7),
givingussum(5,9,11)=25.
Thenwetrytoincludethelargestnonneighbouringnegativenumber(5),
givingussum(5,5,7,9,11)=27.
Thenwetrytoexcludetheleftedge(5)andincludethenumbernexttoit(1),
givingussum(1,7,9,11)=26.
Thenwetrytoexcludetherightedge(11)andincludethenumbernexttoit(1),
givingussum(1,5,7,9)=20.
Clearlythemaximumsumis27.
Notehowwecanmakeanyoftheconditionsthemaximumsumbyjustchangingavalue,thusalltheconditionsareneeded.
answeredJan10'14at0:40
editedJan10'14at1:00
share|improvethisanswer
Dukeling
33.2k83169
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 98/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmfunctionalprogrammingor
askyourownquestion.
asked 1yearago
viewed 155times
active 1yearago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Linked
9
Maximumsumofnonconsecutiveelements
Related
42
Gettingthesubmatrixwithmaximumsum?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
1
Findingthemaximumsumsub=rectanglewithinamatrix
1
Maximumsumofnonconsecutiveelements(withkelementsfromanywhere)
3
FindtheLongestIncreasingSubsequencewiththeMaximumSum
1
Expectationofthemaximumconsecutivesubsequencesumofarandomsequence
2
FindasubarraywhosesumisdivisiblebyanumberKthesubarrayshouldbeofmaximumsumofallpossiblesubarrays
2
Maximumsumoftwointervals
3
MaximumSumSubArray
1
Algorithmtofindthemaximumnonadjacentsuminnarytree
HotNetworkQuestions
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
RollmyD&Dcharacter'sabilityscores
Alarmclockprinting
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Antiferromagneticordering
CanIflywithagoldbar?
ThenthTernary
Whycan'tanonabeliangroupbe75%abelian?
Whydotheymanifestasrings?
Whyadding"incolour"whenreferringto"WizardofOz"?
WhydosomepeoplerefertoLinuxasGNU/Linux?
Justifyingsuboptimalresearchqualitybylackofsupervision
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
FindingoutifawordisanAnagramofanother
ImageOpensasLayer0ratherthanBackground
Howtodrawsequenceofshapeswitharrowsandtext
HowcanIcheckifmyfunctionprint/echo'ssomething?
Patchingabinarywithdd
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 99/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Packagetodonotes:HowcanIchangethetextcolor?
Jumpingcarwithtoomanyamps?
40Numbersin9Bytes
CanIwriteapaperoutofasimpleidea
What'sthebestwaytoinvestformakingregulardonations?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
mergencoinswithminimumcosttocreateonesinglecoin
Fromhttp://www.geeksforgeeks.org/amazoninterviewset89/
Wehavengoldcoins.Weneedtoamalgamateallthencoinstocreateonesinglecoin,wecanmergetwocoinsatonce.Thecostof
mergingtwocoinsisequaltothevalueofthosecoins.Howdoweensurethatthecostofmergingncoinsinminimum.
Ex:5,8,4,3,9,6
Wewillmerge3and4,cost=7{Remainingcoins:5,8,9,6,7}
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 100/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Thenwemerge5and6,cost=11{Remainingcoins:11,8,9,7}
Thenwemerge7and8,cost=15{Remainingcoins:11,15,9}
Thenwemerge9and11,cost=20{Remainingcoins:20,15}
Thenwemerge20and15,cost=35{Remainingcoins:35}
Totalcost:7+11+15+20+35=88
Ifwehadmergedthecoinarray{5,8,4,3,9,6}indifferentfashion:
upvote9down
votefavorite Merging5and8,cost=13{Remainingcoins:13,4,3,9,6}
2 Merging13and4,cost=17{Remainingcoins:17,3,9,6}
Merging17and3,cost=20{Remainingcoins:20,9,6}
Merging20and9,cost=29{Remainingcoins:29,6}
Merging29and6,cost=35{Remainingcoins:35}
Totalcost:114
Aswecanseethatthecostislessinthefirstcase.howtogettheminimumcostofmergingallthencoins??
thisisjustanexample,numberofcoinsmayoftherange10^9
algorithm
editedJul7'14at13:41 askedJul1'14at17:51
share|improvethisquestion
ColonelPanic Guru
35.2k22153207 966
1 @FrdricHamidithisisjustanexample,coinsmayoftherange10^9GuruJul1'14at17:55
UnlessIseeacounterexampleI'dassumethatalwaysmergingthesmallestcoinsisbest.Becauseyoualwayshavetodothesamenumberof
5
mergers,andbythiswaythecostpermergershouldbelowest.Can'tprooveit,though.tobias_kJul1'14at17:56
@tobias_ktakeforexample3489asperyouralgorithmanswewrshouldbe7+15+24=46butanswershouldbe24GuruJul1'14at18:03
Howdoyouget24?24isthesumofthosecoins,butifyoucanmergeonlytwocoinsatonce,thatcan'tbe.OrmaybeImisunderstoodthe
2
question?tobias_kJul1'14at18:05
@tobias_ksorrymybadletmethinkoncemoreGuruJul1'14at18:09
|show4morecomments
2Answers
activeoldestvotes
I'venotgiventhisalotofthought,butoffthetopofmyhead,itseemsprettylikelythatagreedyapproachwillwork:sortthecoinsandalwaysmergethe
smallestonesfirst.Theintuitionbehindthisisthatyouwantto"merge"themostexpensivecoinasinfrequentlyaspossible.
Ifyouhaveonecoin,you'redone.Ifyouhavetwocoins,youhaveonlyonechoice.Considerthecasewiththreecoins:A<B<C.Wecanmergethesein
threeways:
A+B,(A+B)+C=>2A+2B+C
A+C,(A+C)+B=>2A+2C+B
B+C,(B+C)+A=>2B+2C+A
upvote7
Weseethatthefirstoption,mergingthesmallestcoins,isbest.SeeBill'sanswerforavaluableinsightontakingtheproofallthewayacommentI
down
contributediscopiedhere:
vote
accepted Youcanthinkofthecoins'valuesasbeingtokenfrequenciesusedinHuffmanencoding.Forveryfrequenttokens,youwantashortcodepath.IthinkBill's
pointingoutthatthe"merging"canbethoughtofassortofmovinguptheHuffmantree:thenumberoftimesacoingetsmergedisitsdistancefromtheroot.
Therefore,theproofofcorrectnessforHuffman'salgorithmshouldapplytothe(also)greedyalgorithmIdescribe,whichisbasicallyHuffman's,thoughnot
forencoding.
answeredJul1'14at18:03
editedJul1'14at18:40
share|improvethisanswer
Patrick87
10.7k1137
Don'tknowwhetherthiscountsasaproof,butitseemsplausibletome.+1tobias_kJul1'14at18:08
@Patrick87givemesometimetothinkacounterexampleGuruJul1'14at18:10
Sir,canwedoitinO(n)time?JerkyJul1'14at20:25
@AyushJainIthinkO(nlogn)isabetterguess.Youhavetosortthecoinsandkeeptheminsortedorder,maybeusingapriorityqueue.tobias_kJul1
1
'14at20:32
@AyushJainIfthecoinscanonlyassumearelativelysmallnumberofvaluesfromafiniteset,thenit'spossibletosortthembyvalueinO(n)usingany
1
ofthecommonlineartimesortingalgorithms.Thesewouldnotapplyifcoinscanassumeanynonnegativeintegervalue.Patrick87Jul1'14at20:59
addacomment|
LetC_sbetheoptimalcostofmergingS=[s_1,s_2,...,s_n].
ThenifPandQdifferentonlyinoneelement(i.e.p_i=q_i,exceptforexactlyonei),atindexj,andp_j<q_j.ThenwehavethatC_P<=C_Q.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 101/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Basically,PandQdifferonlyinasinglecoinwithPhavingthesmallerone.ThenoptimalmergeforPwillhavelowercostthanoptimalmergeforQ.
up
vote Thisprovesthat@Patrick87'sgreedyalgorithmiscorrect.
1
down btw,thisisbasicallyaUnaryHuffmanencoding!
vote
editedJul1'14at18:52 answeredJul1'14at18:29
share|improvethisanswer
MichaelPaulukonis BillGates
5,42021950 111
Couldyoupleaseenlargeabitonthe"UnaryHuffmanencoding"part?CodorJul1'14at18:36
@CodorYoucanthinkofthecoins'valuesasbeingtokenfrequenciesusedinHuffmanencoding.Forveryfrequenttokens,youwantashortcodepath.I
thinkBill'spointingoutthatthe"merging"canbethoughtofassortofmovinguptheHuffmantree:thenumberoftimesacoingetsmergedisitsdistance
2
fromtheroot.Therefore,theproofofcorrectnessforHuffman'salgorithmshouldapplytothe(also)greedyalgorithmIdescribe,whichisbasically
Huffman's,thoughnotforencoding.Patrick87Jul1'14at18:39
@Patrick87SoundsinteresingIhavetogiveitsomemorethought.CodorJul1'14at18:40
@Patrick87yourcommentshouldbeanswer.aksamDec30'14at18:56
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmoraskyourownquestion.
asked 1yearago
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 102/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
viewed 552times
active 1yearago
Lookingforajob?
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
Gettheweeklynewsletter!
Topquestionsand
answers
Important
announcements
Unanswered
questions
Signupforthenewsletter
Related
11
Algorithmformergingsetsthatshareatleast2elements
1
externalsorting:multiwaymerge
5
TimeComplexity/CostofExternalMergeSort
1
dynamicprogrammingproboemforminimumcost
0
Minimumcosttocutwoodenboard
3
Operationsonstacksofcoins
1
Minimumnumberofcoinsrequiredtogetavalue
0
MakesumKwithNcoins
3
TakeKelementsandmaximisetheminimumdistance
2
Maximisetheminimumdifference
HotNetworkQuestions
Paidcashforacar,butdealerwantstochangeprice
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
DoesaUSB3.0connectionrequireaUSB3.0cord?
Whatistheoriginofthepowericon?
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
HowtoprovemyGmailhasbeenhacked?
RollmyD&Dcharacter'sabilityscores
Drawarrowinamindmap
LeapyearcheckinJava
Alarmclockprinting
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 103/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Shouldmy(sequential)collectionstartatindex0orindex1?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Needhelprecreatingcrazycolors/materialfromexample
NineTallMenAreStandingTall
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
HowcouldaresurrectedJesusproveheisJesus?
Whyadding"incolour"whenreferringto"WizardofOz"?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Whatis`$?`?Isitavariable?
WhatdoesitmeanifanACmotorhastwovoltageratings?
Needtostartareligionwithapredefinedselfdestruct
Passfilenamefrombashtopython
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
mergingsortedarrays[duplicate]
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 104/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
PossibleDuplicates:
Mergingtwosortedlists
AlgorithmforNwaymerge
Givenksortedarrayseachoflengthn,constructasinglemergedandsortedarray.focusonrunningtimeandspacecomplexity.
upvote17downvotefavorite Source:Amazoninterviewquestion.
9 Anythoughts?thanks
algorithm
editedMar21'11at6:56 askedMar21'11at6:47
share|improvethisquestion
Aadith JoshMorrison
2,40382860 2,41284368
markedasduplicatebyNoelM,templatetypedef,marcog,codaddict,GravitonMar25'11at7:58
Thisquestionhasbeenaskedbeforeandalreadyhasananswer.Ifthoseanswersdonotfullyaddressyourquestion,pleaseaskanewquestion.
1 @NoelM:Notaduplicateofthat,thisoneisaboutmerging(possibly)morethantwosortedlists.NullSetMar21'11at7:12
Yeahyou'reright,sorry.IwasstillhalfasleepNoelMMar21'11at7:14
addacomment|
1Answer
activeoldestvotes
Makeaheapfromthefirstelementineacharray.Poptheheadelementfromtheheap,insertitintotheresultarray,andthentakethenextelementfromthe
arraytheheadoftheheapcamefrom,andinsertthatintotheheap.Repeatuntilyouconsumeallofthearrays.
upvote
21down answeredMar21'11at6:52
vote
accepted share|improvethisanswer editedMar21'11at7:00
NullSet
4,4141232
Isn'tthisextremelyinefficientsincetheconditionsdescribedintheOPdescribeamergesortthat'spartofthewaydone?Thinkaboutit.Youhavesome
3 numberofsortedarraysthatyou'regoingtomergeintoasortedarray.Youalreadyhavetheconditionsforamergesort.I'mnottryingtopickholesinyour
idea,it'sjustthatI'mjustdiggingdeeperintosortingalgorithmsandtryingtolearnasmuchasIcan.MichaelMcTiernanMar21'11at7:00
@MichaelThisbasicallyisamergesort.I'vejustextendedittomergingmorethantwosortedlists.Thepointoftheheapisthatitcanfindtheminimum
4
oftheupdatedsetofcandidatesinsublineartime,O(log(n)).Atleastthatwastheidea.NullSetMar21'11at7:05
@MichaelMcTiernan:No.Youmisunderstood.NullSetisnotproposingdumpingalltheinputarrayelementsontoaheapthatwouldindeedbevery
inefficient.WhatNullSetisproposingisbuildingaheapthatcontainsonlykelements:itincludesthefirst(minimal)elementfromeachsortedarray.Just
4
oneelementfromeacharray.Whenyouremovetheminimumelementfromtheheap(andsendittooutput),youaddthenextelementfromthesamearray
totheheapandrebuildtheheap.Thiswaythesizeoftheheapisalwaysonlyk.AnTMar21'11at7:15
Thisisbasicallythatschoolbookapproachtomergingtwosortedarrays,butextendedfromtwoarraystokarraysbyusingaheapforchoosingthe
1
minimumfromkelements.Inthisapproachthefactthatthesortingispartiallydoneisintensivelyusedbythisalgorithm.AnTMar21'11at7:19
notethatthissolutionisoptimal.assumeyoucoulddoitbetterthenO(nlogk(k))inthiscaseyouwouldbeabletospliteveryarrayintonsortedsub
4 arraysofsize1,andsortit,withabettercomplexitythenO(nlog(n)).sincesortingisprovenomega(n*logn),yougetacontradiction.amitMar22'11at
18:29
|show4morecomments
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmoraskyourownquestion.
asked 4yearsago
viewed 12995times
active 4yearsago
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 105/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Lookingforajob?
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
PolyglotDeveloper(ruby,javascript,clojure,etc.)
MavenHiveTechnologiesPvt
Bengaluru,India/relocation
rubyonrailsstartup
Linked
55
AlgorithmforNwaymerge
19
Mergingtwosortedlinkedlists
0
Howtoreducethecomplexityofmergingmultiplearraysusingheap?
Related
17
howtomergetwosortedintegerarrayinplaceusingO(n)timeandO(1)spacecost
240
Fastestsortoffixedlength6intarray
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
8
MergeSortTimeandSpaceComplexity
26
WhyiskwaymergeO(nk^2)?
2450
Pairsocksfromapileefficiently?
1
SpaceComplexityofmergesort
0
MergingnsortedarraysinJavascript
0
Mergeksortedarraysintoonesortedarray
1
Mergesortspaceandtimecomplexity
HotNetworkQuestions
ImageOpensasLayer0ratherthanBackground
WhyareUNIX/POSIXsystemcallnamingssoillegible?
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
RollmyD&Dcharacter'sabilityscores
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
FindingoutifawordisanAnagramofanother
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Clientwantsfontaslogo
Whatistheoriginofthisphotoofanunexplodedbomb?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 106/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Whyshouldakeybemadeexplicit?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
What'sanexpressionforacunninglyfakefriend?
Shouldmy(sequential)collectionstartatindex0orindex1?
WhatdoesitmeanifanACmotorhastwovoltageratings?
Passfilenamefrombashtopython
Whyadding"incolour"whenreferringto"WizardofOz"?
Patchingabinarywithdd
Troublewithterminatinga<apex:pageBlockSection>
Howtodrawsequenceofshapeswitharrowsandtext
WhydosomepeoplerefertoLinuxasGNU/Linux?
morehotquestions
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
PassingBinaryTreeonanetworkwithminimumspace
IrecentlycameacrossaninterviewquestionaskedbyAmazon:
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 107/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Givenabinarytreetobepassedthroughanetwork.Howtopassthistreeinminimumspace?
Ok,my2approachestoabovequestionare:
1. Wecanstoretheinorderoftreeinanarrayalongwithpreorder(orpostorderorlevelorder)inanotherarrayandthenpassthe2arraysintothe
network.Thisconsumesalotofspace.Sorejectingit,Icameupwithothersolution.
2. Wewillpasseachnodeofthetreelevelwisealongwithsomeinformationaboutit'sleftandrightchild.
Method2
AdditionalInformationalongwithnodes:
ifleftchild==NULL&&rightchild==NULLpass00alongwithnode
ifleftchild!=NULL&&rightchild==NULLpass10alongwithnode
ifleftchild==NULL&&rightchild!=NULLpass01alongwithnode
ifleftchild!=NULL&&rightchild!=NULLpass11alongwithnode
Letuslookatanexamplefor2ndmethod
upvote3 enterimagedescriptionhere
downvote
favorite
LevelWise
1. Passnode(2)and11
2. Passnode(7)and11
3. Passnode(5)and11
4. Passnode(2)and00
5. Passnode(6)and11
6. Passnode(9)and10
7. Passnode(5)and00
8. Passnode(11)and00
9. Passnode(4)and00
IfIamcorrect,theninthisway,youcandoreconstructionofthetreeontheothersideofthenetworkalsobycheckingtheadditionalinformationeasily
and(pardonmeifIamwrongthen)youareusinglessmemorybecauseyouareonlypassingnode'svalueandadditionalinformationatatimeinsteadof
passingthewholetree.
Ok,nowIhave2questions:
1. IsmyMethod2correctorarethereanyexceptionalcasesforthatwhichImayhavemissed.
2. Isthereanymoreefficientwayotherthanthe2describedtosendthetreeontothenetwork?
algorithmnetworkingdatastructurestreebinarytree
askedJul13'14at21:39
editedJul14'14at12:29
share|improvethisquestion
Jerky
973624
3 possibleduplicateofEfficientArrayStorageforBinaryTreeJasonMArcherJul14'14at2:28
addacomment|
1Answer
activeoldestvotes
Thisismoreofakindofquestionyouarenotexpectedtocomeupwithanexactsolution.Alluneedistoreasonoutsoundly.
Abetterandefficientapproachforpassingthebinarytreetoanetworkwouldbetosenditspreordertraversalalone.Sinceumighthavereadthat
usingapreorertraversalalone(ifwehavetheentireinfoofatree)issufficenttocreateatree.Youcanpasstheentirebinarytreeviaasingle
preordertraversal.
Foreg.ifurtreeis
/\
23
Thenifuwanttosendthistreetoanetworkdoitspreordertraversalas
upvote 12##3##...storeitanarrayandsenditviapacketspreferablypacketswitching.
1down
vote whatIhavedoneisthatforeverynullleftorrightchild(i.eifitsleftorrightchildorbothisnotpresent),Ihaveputa'#'sentinel.Nowtheuseron
theothersideofthenetworkwoulddecodeiteasilyusingastackbasedapproachwhichumighthavelearntinyourbasicdatastructurecourse.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 108/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ThesolutionugaveisalsocorrectandIdontthinkthereisanycornercaseforitbutitalsoisnotveryspaceefficient
1.First,whetherusendatreelevelbylevelorin2arraysasusaidabove,uwillbepassingthemaspacketsonanetworkandnotasentire
arrays(sosendingisnotabigconcernwhensizeofasinglepackethasalimit.Ucansenditviamultiplepackets).Butforgettingtheinfoabouta
nodeanditschildren,uwouldrequireadditonalspacetostoreuranswerwhichisanoverhead..
2.uwouldbedoingalevelordertraversalwhichonanaverageismorespaceconsumingthanastackbasedo(height)spaceappraoch.
BTW,useemtobepreparingforamazon.Allthebest.
answeredJul14'14at18:59
share|improvethisanswer
bud
214
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmnetworkingdatastructures
treebinarytreeoraskyourownquestion.
asked 12monthsago
viewed 507times
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 109/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
active 12monthsago
Lookingforajob?
ChiefSoftwareArchitectJava$100K
Crossover
Bengaluru,India/remote
eclipsenetbeans
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Linked
13
EfficientArrayStorageforBinaryTree
Related
4
Wanttosavebinarytreetodiskfor20questionsgame
8
Howtoconvertabinarytreetobinarysearchtreeinplace,i.e.,wecannotuseanyextraspace
9
Removingduplicatesubtreesfrombinarytree
1
Completebinarytreedefinitions
4
Cstandardbinarytrees
3
Whyarethesetreesthesameasorderedtreesbutdifferentasbinarytrees
1
VerticalSuminagivenBinaryTree
1
Printbottomviewofabinarytree
1
Createabinarytree(butnotBST)
0
minimumheightofabinarytree?
HotNetworkQuestions
Multiplypurefunctionwithscalar
Alarmclockprinting
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Ciertasconjugacionesverbalesnoconvencionales
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
ImageOpensasLayer0ratherthanBackground
zero,zerosorzeroes?
Derivativeofadefiniteintegralissue
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
Whyadding"incolour"whenreferringto"WizardofOz"?
Nicelytypesettingverbatimtext
Whycan'tanonabeliangroupbe75%abelian?
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
Paidcashforacar,butdealerwantstochangeprice
Antiferromagneticordering
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
FiveAnglesinaStar
HowtoprovemyGmailhasbeenhacked?
Passfilenamefrombashtopython
Whatis`$?`?Isitavariable?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
PythonLabelExpression?ArcGIS10.3.1
HowdoIupgradefromGPLv2toGPLv3?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 110/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
7. Game InformationSystems 5. Mathematica 6. PersonalFinance 6. Arqade(gaming) 5. MathOverflow Overflow
Development 6. Electrical 6. Salesforce &Money 7. Bicycles 6. more(7) Careers
8. TeX Engineering 7. more(14) 7. Academia 8. Roleplaying
LaTeX 7. AndroidEnthusiasts 8. more(10) Games
8. InformationSecurity 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
printallnodesatadistanceof'x'fromagivennodeinBST
Thedetailedquestionistofindallthenodeswithdistancex(i.e.numberofedges=x)fromagivennode.
IwasaskedinanAmazonInterviewtoday,
voidfindNodeWithDistanceX(structnode*root,structnode*qnode,intvalue)
{
//rootisrootNode,qnodeisquestionnodefromwhichdistancetobecalculated,valueisthe
//distancetobecalculated
//findingdistancebetweenrootandqnode
intdistance=findDistancefromRoot(root,qnode);
if(distance>value)
{
traverseDistancedown(root,distancevalue);
}
if(distance==value){
printf("%d",root>value);
upvote1downvotefavorite }
//Traverseandfindallnodeswithdistancevaluefrom'qnode'downthetree
traverseDistancedown(qnode,value);
NowIncaseoffindingthedistance"value"fromqnode.
IdidnotgettheanswerhowtotraverseuptheTreeandsatisfytheconditionofdistancewithvalue.
Althoughmanycasesariseshere.
ItriedbacktrackingfromqnodebuttonoavailIwasunabletoimpresshimandunabletowritetheCode.
AnyDiscussionregardingimplementingthetraversalupthetreewillbehelpfultome.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 111/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
algorithmdatastructurestreebinarysearchtree
editedMar23'14at15:21 askedMar22'14at19:34
share|improvethisquestion
JimMischel Hitesh
77.6k566158 246
1 breadthfirstsearch?NiklasB.Mar22'14at19:57
1 Bytheway,pleaseformatyourcode...IhopethisisnottheversionyoupresentedintheinterviewNiklasB.Mar22'14at20:16
addacomment|
2Answers
activeoldestvotes
Thesimplestwayiswithadepthfirstsearch,keepingtrackofthedistanceasyougoalong.It'sasimplepreordertraversalstartingatthe"questionnode".
voidnodesAtDistance(structnode*qnode,intrequestedDistance,intcurrentDistance)
{
if(qnode==null)return;
if(currentDistance==requestedDistance)
{
//outputqnode
//andthenreturnbecausechildrenarefurtheraway
return;
}
//visitleftandthenright
nodesAtDistance(qnode>left,requestedDistance,currentDistance+1);
nodesAtDistance(qnode>right,requestedDistance,currentDistance+1);
}
Soifyoucallthiswith:
upvote1
downvote nodesAtDistance(myNode,5,0);
Itwilloutputallnodesthatare5levelsbelowmyNode.
Now,ifIweretowritethisasanAPIfunction,Iwouldprovideanoverloadthatdoesn'trequiretheclienttopassthatcurrentDistanceparameter.Becauseif
somebodyweretowritenodesAtDistance(myNode,5,1),you'dgetthingsatdistance4.So,createthisoverload:
voidnodesAtDistance(node*qnode,intrequestedDistance)
{
nodesAtDistance(qnode,requestedDistance,0);
}
Makethatfunctionpubliclyvisible,andmaketheotheroneprivate.
answeredMar23'14at15:33
editedMar24'14at14:09
share|improvethisanswer
JimMischel
77.6k566158
addacomment|
trythiscode,althoughthiscodechecksonlyforchildrennodesanddoesnotgobacktocheckonancestorsnodesatgivendistance
#include<stdio.h>
#include<malloc.h>
structtreenode
{
unsignedintdata;
structtreenode*left;
structtreenode*right;
};
structtreenode*treeptr,*sourcenode,*quesnode,*quesleftnode,*quesrightnode,*root=NULL;
structnode*treeptrinsert_node(unsignedinttreedata)
{
treeptr=(structnode*)(malloc(sizeof(treenode)));
treeptr>data=nodevalue;
treeptr>left=NULL;
treeptr>right=NULL;
returntreeptr;
}
printnodesdistancek(structtreenode*quesnode,unsignedcharreqdist)
{
unsignedcharcurdist=0;
do
{
if(quesnode==null)
return;
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 112/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
quesleftnode=quesnode>left;
if(curdist==reqdist)
{
printf("%d",quesleftnode>data);
upvote0downvote }
else
{
quesnode=quesnode>left;
}
quesrightnode=quesnode>right;
if(curdist==reqdist)
{
printf("%d",quesrightnode>data);
}
else
{
quesnode=quesnode>right;
}
}while(quesnode!=NULL);
//mainfunction
voidmain(void)
{
//createtree
*root=insert_node(1);
root>left=insert_node(1);
root>right=insert_node(2);
root>left>left=insert_node(2);
root>left>right=insert_node(3);
root>right>left=insert_node(3);
root>right>right=insert_node(4);
sourcenode=root>left;
printnodesdistancek(sourcenode,1);
answeredApr20'14at10:56
editedApr20'14at18:26
share|improvethisanswer
Nanobrains
217
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 113/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdatastructurestreebinary
searchtreeoraskyourownquestion.
asked 1yearago
viewed 349times
active 1yearago
Lookingforajob?
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Related
5
FindswappednodesinaBST
0
TraversaltoprinttwoBSTsorderedusingrecursion.Useofextramemorylikearraysisnotallowed
0
ReplaceBSTnodeswiththesumofnodesgreaterthanorequaltothenode
1
FindthedistanceofanodetotherootinBST
0
BSTfromPreorderbyjustinsertingthenodesinsameorder
0
Isthereatricktosolvebinarytreeproblemswith`size`or`height`?
0
Givenabinarysearchtreeandakey,HowtofindfirstMtreenodeswhichvaluesareclosesttothatkey?
2
Givenasetofpoints,findtheonethathasthesmallestManhattandistancefromaquerypoint
1
NumberofbinarytreesandBSTswithnoden
0
GivenaBST,andanodeinBST,makethatnode,asnewrootofthetree
HotNetworkQuestions
Uncorrectedsamplestandarddeviationincorrelationcoefficient
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
HowcouldaresurrectedJesusproveheisJesus?
Jumpingcarwithtoomanyamps?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
What'sthebestwaytoinvestformakingregulardonations?
Multiplypurefunctionwithscalar
Howtogetearlyentryintomystictheurge?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
HowtoprovemyGmailhasbeenhacked?
LeapyearcheckinJava
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 114/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
RollmyD&Dcharacter'sabilityscores
Derivativeofadefiniteintegralissue
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
40Numbersin9Bytes
Needtostartareligionwithapredefinedselfdestruct
Functionsthataretheirowninversion.
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
FindingoutifawordisanAnagramofanother
Whatwereshoesolesmadefrominpreviousages?
What'sanexpressionforacunninglyfakefriend?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
RearrangingarraywithO(1)extramemoryinfasterthanO(n^2)time
SupposeIhavethefollowingarray:
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 115/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
1,4,5,2,3
Ineedtorearrangeitto
5,1,4,2,3
Thereisonlyonextraspaceoneint.
Ifiguredonesolutiontosolveit.ButitisO(n^2)complexity.
Cananyoneofferafastersolution?
Thanks
Edited:sorry,notrotatingarray.
upvote3down Ineedtochangeoriginalarraytoresultarray.Theordercanbearbitrary.IjustneedtomakeA>B.Bisbeentoldtome.
votefavorite
thanks
Edited2"
Makeitclearer.ArrayBisnotfixed.Weneedtofindageneralsolutionforthis.
Updated:
Thankyouall.Seemslikethisisabrainteaserquestion.haha:D
MyfriendbeenaskedbyAmazoninterviewerforthis.LOL
algorithm
askedApr3'12at23:02
editedApr4'12at0:25
share|improvethisquestion
AndersLind
1,0211838
Whatisthetransformationthere?It'snotanykindofsortingthatIcansee.Howdoyougetfromtheoriginaltotheoutput?(Iunderstandthe
1
spaceremoval,justtheorderingIdon't.)CorbinApr3'12at23:04
Areyourotatingthearray?ShahbazApr3'12at23:05
Asmyunderstanding,needtoachievecertainaddrstorecertainvaluebasedonrequirement.AndersLindApr3'12at23:06
Ithinkyoucan'tgetbetterthanO(n^2)SaeedAmiriApr3'12at23:17
2 IfBisknown,thenthere'snoworkinvolved,soofcoursethisisO(1).OliverCharlesworthApr3'12at23:38
|show2morecomments
4Answers
activeoldestvotes
ThissolutionworksusingO(1)space.
>>>defarrayswap(source,dest):
...foriinrange(len(dest)):
...source[source.index(dest[i])],source[i]=source[i],source[source.index(dest[i])]
...
>>>a=[1,4,5,2,3]
>>>b=[5,1,4,2,3]
>>>arrayswap(a,b)
upvote1downvote >>>a
accepted [5,1,4,2,3]
Withoutusingpython'stuplepacking,thevalueofoneofsource[i]orsource[source.index(dest[i])]couldbestoredinanint.
answeredApr3'12at23:48
share|improvethisanswer
fwenom
745
1 bysource.index(dest[i])youmeanalinearsearch?ThatwouldgiveO(n^2)performanceShahbazApr3'12at23:50
Ah,Ididn'treadthefullproblem.JustreadthepartaboutO(1)space.Well,atleastitisaworkingsolutionforotherstoseeandimprove.Too
badIcan'tjustdoa,b=b,afwenomApr3'12at23:51
addacomment|
Itseemstomethatthisisjustaspecialcaseofsortingthearray,wherethesortorderisratherarbitrary.So,anoptimalalgotithmwouldhavetimecomplexity
O(nlogn),andusingonethatdoesinplacesorting(attheexpenseofnotbeingastablesort)wouldhavespacecomplexityO(1).Aninplacemergesortwould
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 116/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
upvote fitthebill,aswouldaninplacequicksortifaverageO(nlogn)isOK.
2down
vote answeredApr3'12at23:21
share|improvethisanswer
MPD
2,54721837
1 Indeed,O(1)spaceletsyouperformaswap(a,b)operation.ninjageckoApr3'12at23:32
@ninjageckoyoucanevenswap(a,b)withO(0)spaceShahbazApr3'12at23:44
1 @ninjagecko,readuponthexorswapMPDApr3'12at23:48
@Esailija,0isO(0)becausethereexistsac>0(say1)where0<c*0forallinputsizesn>0.Notethatwearetalkingaboutmemory,nottime.
1
ShahbazApr3'12at23:59
@ninjagecko,that'snotentirelytrue.Evenifa+boverflows,theunderflowfromabfixesit.Afterall,additionandsubtractionarecongruentmodulo2^32
1 (if32bit)andintheendthenumberswouldberight.Still,that'sanotherreasonforpeopletochoosexortootheroperators.(P.S.BugFix:inmyfirst
comment,a$b=b$a(samewith#)doesn'tneedtohold)ShahbazApr4'12at8:39
|show10morecomments
Itseemslikeyouarejustmovingthefirstthreeelementstotheleft(withawraparound).
So,ignoretheindex3and4.
inttemp=array[0]
array[0]=array[1]
upvote0downvote array[1]=array[2]
array[2]=temp
answeredApr3'12at23:21
share|improvethisanswer
Justin
2,81821131
addacomment|
Youcanjustdo:
temp=arr[0];
arr[0]=arr[2];
arr[2]=arr[4];
arr[4]=arr[1];
arr[1]=arr[3];
arr[3]=temp;
Edit:
Torearrangearrayatobeasarrayb,youcanjustdolikethis:
for(vari=0;i<a.length;i++){
for(varj=i+1;a[i]!=b[i];j++){
vartemp=a[i];
upvote1 a[i]=a[j];
downvote a[j]=temp;
}
Demo:http://jsfiddle.net/Guffa/5sKdM/
I'mnotsurewhatthebigOisonthisone,butwiththeexampledataitdoes7comparisonsand2swaps,sothatisdefinitelybetterthanO(n2).
Also,I'mnotsureexactlywhatcountsasan"extraspace",soIdon'tknowifthisfulfillstherequirementoftheoneextraspace,butifitdoesn't,neitherdoes
thecurrentlyacceptedanswer...
answeredApr3'12at23:07
editedApr4'12at6:24
share|improvethisanswer
Guffa
372k47322612
4 Ifthisisindeedtheintendedanswer,thatwouldmakeitthesilliestinterviewquestionIheardtodate:):):)dasblinkenlightApr3'12at23:10
sorry,clarifiedmyquestion.notrotatingarrayAndersLindApr3'12at23:10
ThisisaspecialcaseofthecoderequiredtoimplementthePostScriptrollcommand,whichtakestwoargumentsthenumberofelementsfromthe
1
topofthestacktoroll,andthenumberofpositionsforward(back)torollthem.DRVicApr3'12at23:10
@AndersLind:Updatedmyanswerreflectingyourupdate.:)GuffaApr4'12at6:07
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 117/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmoraskyourownquestion.
asked 3yearsago
viewed 372times
active 3yearsago
Lookingforajob?
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Gettheweeklynewsletter!
Topquestionsand
answers
Important
announcements
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 118/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Unanswered
questions
Signupforthenewsletter
Related
26
HowtofindpythagoreantripletsinanarrayfasterthanO(N^2)?
25
findiftwoarrayscontainthesamesetofintegerswithoutextraspaceandfasterthanNlogN
2
MaximumXORvaluefasterthanjustusingXOR
4
RemoveallzerosfromarrayO(n),noextramemory
0
RearrangeArraypositiveandnegativeoneitherside
231
Whyisifasterthani++inloops?
15
Searchingtwoarraysformatches,noextramemory
11
ifhugearrayisfasterthanhashmapforlookup?
10
FindtripletsinbetterthanlineartimesuchthatA[n1]>=A[n]<=A[n+1]
3
Givenanpositiveintegerarray,rearrangethearraysothatthesumofproductofadjacentelementscanbemaximized
HotNetworkQuestions
Needhelprecreatingcrazycolors/materialfromexample
Derivativeofadefiniteintegralissue
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Jumpingcarwithtoomanyamps?
Paidcashforacar,butdealerwantstochangeprice
Whydotheymanifestasrings?
Passfilenamefrombashtopython
HowtodealwithaGMwhodoesnottelluseverything?
Whycan'tanonabeliangroupbe75%abelian?
LeapyearcheckinJava
Justifyingsuboptimalresearchqualitybylackofsupervision
Thetwopronunciationsof
CanIflywithagoldbar?
Troublewithterminatinga<apex:pageBlockSection>
NineTallMenAreStandingTall
Whyweren'ttheWeasleysapartoftheOriginalOrder?
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
Drawarrowinamindmap
Whydosocksstink?
HowdoIfacilitateafirsttimeAgileretrospective?
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
ALN*NTicTacToeGame
Whatwereshoesolesmadefrominpreviousages?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 119/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Reversealternateelementsandappendtoendofthelist
Givenalinkedlistasa>x>b>y>c>z,weneedtoreversealternateelementandappendtoendoflist.Thatis,outputitasa>b>c>z>y>x.
IhaveanO(n)solutionbutittakesextramemory,wetake2listsandfillitwithalternateelementsrespectively,sothetwolistsareabcandxyzand
thenwewillreversethesecondlistandappendittothetailoffirstsothatitbecomesabczyx.
upvote1down Myquestioniscanwedoitinplace?Oristhereanyotheralgorithmforthesame?
votefavorite
algorithmpointerslanguageagnosticlinkedlist
askedFeb7'14at8:11
share|improvethisquestion
h4ck3d
1,66331744
addacomment|
4Answers
activeoldestvotes
Thebasicidea:
Storex.
Makeapointtob.
Makeypointtothestoredelement(x).
Makebpointtoc.
etc.
Attheend,makethelastelementatanoddpositionpointtothestoredelement.
Pseudocode:(simplifiedendoflistcheckforreadability)
current=startOfList
stored=NULL
while!endOfList
upvote3downvoteaccepted temp=current.next
current.next=current.next.next
temp.next=stored
stored=temp
current=current.next
current.next=stored
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 120/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Complexity:
O(n)time,O(1)space.
answeredFeb7'14at8:22
editedFeb7'14at11:24
share|improvethisanswer
Dukeling
33.2k83169
addacomment|
Thisisarecentquestionfromamazoninterview,theIdealooksgoodandthereseemstobenotrickinit.
answeredFeb9'14at18:48
upvote0downvote
share|improvethisanswer
SetuPoddar
318
addacomment|
Javacodewithcomments:
staticvoidchange(Noden)
{
if(n==null)
return;
Nodecurrent=n;
Nodenext=null,prev=null;
while(current!=null&¤t.next!=null)
{
//Oneofthealternatenodewhichistobereversed.
Nodetemp=current.next;
current.next=temp.next;
//Reversethealternatenodebychangingitsnextpointer.
temp.next=next;
upvote0downvote next=temp;
//Thisnodewillbeusedinthefinalstep
//outsidethelooptoattachreversednodes.
prev=current;
current=current.next;
}
//Ifthereareoddnumberofnodesinthelinkedlist.
if(current!=null)
prev=current;
//Attachthereversedlisttotheunreversedlist.
prev.next=next;
answeredFeb11'14at17:12
share|improvethisanswer
ShirishMishra
615
addacomment|
heretheccodewhichdon'tusesanyextraspacefordoingthis..enjoyandhavefunincaseofanydoubtfeelfreetoask
#include<stdio.h>
#include<stdlib.h>
intn;
structlink
{
intval;
structlink*next;
};
voidshow(structlink*);
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 121/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
voidaddatbeg(structlink**p,intnum)
{
structlink*temp,*help;
help=*p;
temp=(structlink*)malloc(sizeof(structlink));
temp>val=num;
temp>next=NULL;
if(help==NULL)
{
*p=temp;
}
else
{
temp>next=help;
*p=temp;
}
n++;
show(*p);
}
voidrevapp(structlink**p)
{
structlink*temp,*help,*q,*r;
r=NULL;
temp=*p;
help=*p;
while(temp>next!=NULL)
{
temp=temp>next;
q=r;//thisportionwillrevrsetheevenpositionnumbers
r=temp;
temp=temp>next;
//formakingaconnectionbetweenoddplacenumbers
if(help>next>next!=NULL)
{
help>next=temp;
help=help>next;
r>next=q;
upvote0downvote }
else
{
r>next=q;
help>next=r;
show(*p);
return;
}
}
voidshow(structlink*q)
{
structlink*temp=q;
printf("\t");
while(q!=NULL)
{
printf("%d>",q>val);
q=q>next;
if(q==temp)
{
printf("NULL\n");
return;
}
}
printf("NULL\n");
}
intmain()
{
n=0;
structlink*p;
p=NULL;
//youcantakeuserdefinedinputbuthereiamsolvingitonpredefinedlist
addatbeg(&p,8);
addatbeg(&p,7);
addatbeg(&p,6);
addatbeg(&p,5);
addatbeg(&p,4);
addatbeg(&p,3);
addatbeg(&p,2);
addatbeg(&p,1);
revapp(&p);
return0;
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 122/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
}`
answeredSep30'14at9:38
share|improvethisanswer
abhishekkumarsrivastava
33
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmpointerslanguageagnostic
linkedlistoraskyourownquestion.
asked 1yearago
viewed 709times
active 9monthsago
Lookingforajob?
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 123/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
javaj2ee
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
Related
0
Howtoeliminateduplicatesfromalinkedlistofunicodecharacters,withoutusinganyextramemory
9
Printasinglylinkedlistbackwards,inconstantspaceandlineartime
0
Sortingalinkedlistwithalternateelementssortedandreversesorted
0
whatistheapproachtosolvecircularlinkedlist?
0
FindelementsinmiddlethirdofLinkedListusingonly3pointers?
2450
Pairsocksfromapileefficiently?
0
Reverseandmergealinkedlist
0
DoublyLinkedListusing3arrays
0
Afunctionimplementationtocutaportionofalinklistandappendittotheendofthelist
4
Algorithm:Removeduplicateelementsfromlinkedlist
HotNetworkQuestions
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
Patchingabinarywithdd
Passfilenamefrombashtopython
Whatisatemporarysolutionforadamagedcarbody?
Drawinganarrayofnodesusingtheforeachconstruct
Needtostartareligionwithapredefinedselfdestruct
Antiferromagneticordering
ThenthTernary
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
WhoinventedStarTreksideburnsandwhy?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Ciertasconjugacionesverbalesnoconvencionales
Whyadding"incolour"whenreferringto"WizardofOz"?
Paidcashforacar,butdealerwantstochangeprice
HowdoIfacilitateafirsttimeAgileretrospective?
LeapyearcheckinJava
What'sthebestwaytoinvestformakingregulardonations?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
Using"using"twiceinterpreteddifferentlybydifferentcompilers
ALN*NTicTacToeGame
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
Doblockingcreatureshealbacktofullbetweenphases?
Whatistheoriginofthisphotoofanunexplodedbomb?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia Games
8. InformationSecurity
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 124/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
LaTeX 8. more(10) 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Smallestnumberthatcannotbeformedfromsumofnumbersfromarray
ThisproblemwasaskedtomeinAmazoninterview
Givenaarrayofpositiveintegers,youhavetofindthesmallestpositiveintegerthatcannotbeformedfromthesumofnumbersfromarray.
Example:
Array:[413231]
result=11{Since11wassmallestpositivenumberwhichcannotbeformedfromthegivenarrayelements}
Whatididwas:
upvote13down
1. sortedthearray
votefavorite
2. calculatedtheprefixsum
8
3. Treversethesumarrayandcheckifnextelementislessthan1greaterthansumi.e.A[j]<=(sum+1).Ifnotsothenanswerwouldbesum+1
Butthiswasnlog(n)solution.
InterviewerwasnotsatisfiedwiththisandaskedasolutioninlessthanO(nlogn)time.
algorithmdatastructuresdynamicprogrammingsubsetsum
editedJan12'14at21:59 askedJan12'14at17:19
share|improvethisquestion
templatetypedef user3187810
157k35389625 6816
AreyousayingthattheintervieweraskedforaO(logn)solution?That'sobviouslynotpossiblebecauseyouhavetolookateacharrayvalue
1
once,whichwouldtakeatleastO(n).interjayJan12'14at17:23
Probablyneedtobemorespecifichere:Smallestintegergreaterthanzerowhichcannotbecreatedbysumminganycombinationofthe
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 125/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
3 elementsofthearray,perhaps?DavidOJan12'14at17:24
1 Arethearrayelementsallpositiveintegers?Cantherebeduplicates?interjayJan12'14at17:29
1 Doestheproblem'sspecguaranteeamaximumpossibleintegervaluesubstantiallylessthanINT_MAX?DavidOJan12'14at17:35
Isn'tthiscoincidentlyverysimilartothisquestionthatwasaskedyesterday?stackoverflow.com/questions/21060873/user1990169Jan
2
12'14at17:41
|show14morecomments
3Answers
activeoldestvotes
Considerallintegersininterval[2i..2i+11].Andsupposeallintegersbelow2icanbeformedfromsumofnumbersfromgivenarray.Alsosupposethatwe
alreadyknowC,whichissumofallnumbersbelow2i.IfC>=2i+11,everynumberinthisintervalmayberepresentedassumofgivennumbers.Otherwise
wecouldcheckifinterval[2i..C+1]containsanynumberfromgivenarray.Andifthereisnosuchnumber,C+1iswhatwesearchedfor.
Hereisasketchofanalgorithm:
1. Foreachinputnumber,determinetowhichintervalitbelongs,andupdatecorrespondingsum:S[int_log(x)]+=x.
2. ComputeprefixsumforarrayS:foreachi:C[i]=C[i1]+S[i].
3. FilterarrayCtokeeponlyentrieswithvalueslowerthannextpowerof2.
4. Scaninputarrayoncemoreandnoticewhichoftheintervals[2i..C+1]containatleastoneinputnumber:i=int_log(x)1;B[i]|=(x<=C[i]+
1).
5. Findfirstintervalthatisnotfilteredoutonstep#3andcorrespondingelementofB[]notsetonstep#4.
Ifitisnotobviouswhywecanapplystep3,hereistheproof.Chooseanynumberbetween2iandC,thensequentiallysubtractfromitallthenumbersbelow2i
indecreasingorder.Eventuallywegeteithersomenumberlessthanthelastsubtractednumberorzero.Iftheresultiszero,justaddtogetherallthesubtracted
numbersandwehavetherepresentationofchosennumber.Iftheresultisnonzeroandlessthanthelastsubtractednumber,thisresultisalsolessthan2i,soit
is"representable"andnoneofthesubtractednumbersareusedforitsrepresentation.Whenweaddthesesubtractednumbersback,wehavetherepresentation
ofchosennumber.Thisalsosuggeststhatinsteadoffilteringintervalsonebyonewecouldskipseveralintervalsatoncebyjumpingdirectlytoint_logofC.
Timecomplexityisdeterminedbyfunctionint_log(),whichisintegerlogarithmorindexofthehighestsetbitinthenumber.Ifourinstructionsetcontains
integerlogarithmoranyitsequivalent(countleadingzeros,ortrickswithfloatingpointnumbers),thencomplexityisO(n).Otherwisewecouldusesomebit
hackingtoimplementint_log()inO(loglogU)andobtainO(n*loglogU)timecomplexity.(HereUislargestnumberinthearray).
upvote
4down Ifstep1(inadditiontoupdatingthesum)willalsoupdateminimumvalueingivenrange,step4isnotneededanymore.WecouldjustcompareC[i]to
vote Min[i+1].Thismeansweneedonlysinglepassoverinputarray.Orwecouldapplythisalgorithmnottoarraybuttoastreamofnumbers.
accepted
Severalexamples:
Input:[413231][1239][1129]
int_log:2311001130013
int_log:012301230123
S:1541315092209
C:1610231661524413
filtered(C):nnnnnnnnnnnn
numberin
[2^i..C+1]:2422
C+1:1175
FormultiprecisioninputnumbersthisapproachneedsO(n*logM)timeandO(logM)space.WhereMislargestnumberinthearray.Thesametimeis
neededjusttoreadallthenumbers(andintheworstcaseweneedeverybitofthem).
StillthisresultmaybeimprovedtoO(n*logR)whereRisthevaluefoundbythisalgorithm(actually,theoutputsensitivevariantofit).Theonly
modificationneededforthisoptimizationisinsteadofprocessingwholenumbersatonce,processthemdigitbydigit:firstpassprocessestheloworderbitsof
eachnumber(likebits0..63),secondpassnextbits(like64..127),etc.Wecouldignoreallhigherorderbitsafterresultisfound.Alsothisdecreasesspace
requirementstoO(K)numbers,whereKisnumberofbitsinmachineword.
answeredJan12'14at20:24
editedJan12at17:54
share|improvethisanswer
EvgenyKluev
17.6k62654
Canyoupleaseexplainhowthisworksfor{1239}and{1129}user3187810Jan13'14at7:02
OK.Severalexamplesadded.EvgenyKluevJan13'14at7:37
@EvgenyKluevI'mlookingatyourexamplesIcan'tfigureouthowyour"S:"lineisbeingcalculated.Inyourdescriptionyoumentionprefixsum,butthat
iscertainlynotprefixsum.JonathanMeeJan9at15:21
@JonathanMee:actually,"C"isprefixsum,not"S"."S[i]"issumofvaluesfrominputarrayhavingintegerlogarithmequalto"i".And"C[i]"issumof
valueshavingintegerlogarithmlessorequalto"i".EvgenyKluevJan9at16:10
@EvgenyKluevThanksfortheexplanationInowunderstandCandS.ButI'mstuckagainonStep3.Idon'tunderstandwhatyoumeanby"nextpowerof
2".JonathanMeeJan9at16:28
|show9morecomments
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 126/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
There'sabeautifulalgorithmforsolvingthisproblemintimeO(n+Sort),whereSortistheamountoftimerequiredtosorttheinputarray.
Theideabehindthealgorithmistosortthearrayandthenaskthefollowingquestion:whatisthesmallestpositiveintegeryoucannotmakeusingthefirstk
elementsofthearray?Youthenscanforwardthroughthearrayfromlefttoright,updatingyouranswertothisquestion,untilyoufindthesmallestnumberyou
can'tmake.
Here'showitworks.Initially,thesmallestnumberyoucan'tmakeis1.Then,goingfromlefttoright,dothefollowing:
Ifthecurrentnumberisbiggerthanthesmallestnumberyoucan'tmakesofar,thenyouknowthesmallestnumberyoucan'tmakeit'stheoneyou'vegot
recorded,andyou'redone.
Otherwise,thecurrentnumberissmallerthanthesmallestnumberyoucan'tmake.Theclaimisthatyoucanindeedmakethisnumber.Rightnow,you
knowthesmallestnumberyoucan'tmakewiththefirstkelementsofthearray(callitcandidate)andarenowlookingatvalueA[k].Thenumbercandidate
A[k]thereforemustbesomenumberthatyoucanindeedmakewiththefirstkelementsofthearray,sinceotherwisecandidateA[k]wouldbeasmaller
numberthanthesmallestnumberyouallegedlycan'tmakewiththefirstknumbersinthearray.Moreover,youcanmakeanynumberintherangecandidate
tocandidate+A[k],inclusive,becauseyoucanstartwithanynumberintherangefrom1toA[k],inclusive,andthenaddcandidate1toit.Therefore,
setcandidatetocandidate+A[k]andincrementk.
Inpseudocode:
Sort(A)
candidate=1
forifrom1tolength(A):
ifA[i]>candidate:returncandidate
else:candidate=candidate+A[i]
up returncandidate
vote
22 Here'satestrunon[4,13,2,1,3].Sortthearraytoget[1,2,3,4,13].Then,setcandidateto1.Wethendothefollowing:
down
vote A[1]=1,candidate=1:
A[1]candidate,sosetcandidate=candidate+A[1]=2
A[2]=2,candidate=2:
A[2]candidate,sosetcandidate=candidate+A[2]=4
A[3]=3,candidate=4:
A[3]candidate,sosetcandidate=candidate+A[3]=7
A[4]=4,candidate=7:
A[4]candidate,sosetcandidate=candidate+A[4]=11
A[5]=13,candidate=11:
A[4]>candidate,soreturncandidate(11).
Sotheansweris11.
TheruntimehereisO(n+Sort)becauseoutsideofsorting,theruntimeisO(n).YoucanclearlysortinO(nlogn)timeusingheapsort,andifyouknowsome
upperboundonthenumbersyoucansortintimeO(nlogU)(whereUisthemaximumpossiblenumber)byusingradixsort.IfUisafixedconstant,(say,109),
thenradixsortrunsintimeO(n)andthisentirealgorithmthenrunsintimeO(n)aswell.
Hopethishelps!
answeredJan12'14at17:52
editedJan12'14at18:10
share|improvethisanswer
templatetypedef
157k35389625
Itshouldbecandidate=candidate+A[i]intheelse,withoutthe1.ThisisexactlythesamealgorithmasgivenbyOP,buttheexplanationisveryhelpful.
1
interjayJan12'14at18:00
thisgoestonlognsolution..iknewedthisonebutcouldyouprovideanythingbetterthanthisone?user3187810Jan12'14at18:00
@user3187810ThissolutionisprettyfastitrunsinnoworsethanO(nlogn)timeandpossiblyalotbetterifyoucansorttheintegersusingsomethinglike
1
radixsort.templatetypedefJan12'14at18:02
@interjay:Iupdatedtheanswer.Ididn'trealizewhenIwaswritingthisthatitendedupbeingidenticaltotheOP'sanswer.NowthatIrealizethis,Ithinkthe
1 answerisstillusefulinthatitprovidesajustificationfortheanswerandalsoshowshowtospeeditup(namely,improvingthesortingstep).Ifyouthinkthis
isn'tnecessary,though,Icandeletethisanswer.templatetypedefJan12'14at18:04
@user3187810Iftheintegershavesomefixedupperbound(say,10^9),youcansortthemintimeO(n)byusingcountingsortorradixsort.Thatwouldthen
3
dropthetotalruntimetoO(n).templatetypedefJan12'14at18:10
|show3morecomments
Usebitvectorstoaccomplishthisinlineartime.
Startwithanemptybitvectorb.Thenforeachelementkinyourarray,dothis:
b=b|b>>k|k
Tobeclear,thei'thelementissetto1torepresentthenumberi,and|kissettingthekthelementto1.
Afteryoufinishprocessingthearray,thefirstzeroinbisyouranswer.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 127/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
E.g.,(hereIstartwithanindex1fromtheleftsideofthebitvector)
upvote
5down 1. b=0
vote 2. process4:b=b|b>>4|0001=0001
3. process13:b=b|b>>13|0000000000001=00010000000010001
4. process2:b=b|b>>2|01=0101010000001010101
5. process3:b=b|b>>3|001=0111111010001011111101
6. process1:b=b|b>>1|1=11111111110011111111111
Firstzero:position11.
editedApr20at12:25 answeredJan12'14at20:50
share|improvethisanswer
aka.nice DaveGalvin
3,6371923 955410
2 NotethatthisislineartimeIFthebitvectoroperationsareconstanttime,whichtheymightnotbe.DaveGalvinJan12'14at21:34
Tothebestofmyknowledge,therearen'tanycomputersthatsupportbitwiseoperationsonarbitrarywidthnumbersinconstanttime.Thisisdefinitelya
coolidea,butIdon'tthinkit'sreallyO(n).templatetypedefJan12'14at21:58
@templatetypedef:Fairpoint.OPansweredincommentsthattheintegerswereguaranteedtobeintherangeof[1,10^9],soasufficientlylargebitvectorto
occupythatentirespacecouldbereservedinconstanttimeatthestart.Evenwithoutthatallowance,doublingreservedsizeeverytimeallocatedspacewas
exceededshouldconstrainyoutoO(lgn)allocations.ConspicuousCompilerJan15'14at8:54
@DaveGalvinIs>>ashift?Causethat'sashiftrightnotashiftleft.Evenifitisashiftleft,Imustnotbeunderstandingsomething,causeinyourstep3:
1
1|8192|1doesnotequal8209.JonathanMeeJan9at14:59
@JonathanMeeassaidinanswer,index1isatleft...Ifyouwanttoconvertthatwithlowbitatrightlikewithintegerarithmetic(andyouhavelarge
integers),itissomethinglikeSmalltalkcode:(#(413231)inject:0into:[:b:k|bbitOr:(b<<kbitOr:(1<<(k1)))])bitInvertlowBit11aka.niceApr
20at10:07
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 128/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmdatastructuresdynamic
programmingsubsetsumoraskyourownquestion.
asked 1yearago
viewed 3168times
active 2monthsago
Lookingforajob?
SeniorTechnicalConsultant/DeveloperInnovation
iSpace(aConnollyiHea
Hyderabad,India/remote
scalaakka
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
ApplicationDeveloper,Hyderabad
ThoughtWorksTechnologies
Hyderabad,India
rubyonrails.net
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Linked
0
Similartosubsetsum
2
Minimumsumthatcantbeobtainedfromaset
2
Allpossiblenumbersformedfromadditionofgivendigits
Related
6
Isthisvariantofthesubsetsumproblemeasiertosolve?
3
Findinggreatestsumofelementsofarraywhichisdivisiblebyagivennumber
2450
Pairsocksfromapileefficiently?
5
Selectcombinationofelementsfromarraywhosesumissmallestpossiblepositivenumber
3
Findingnumberofpermutationsof'p'numbersthatsumtoagivennumber'n'
5
maximumsumofasubsetofsizeKwithsumlessthanM
3
Subsetsumforlargesums
1
Definingaspecialcaseofasubsetsumwithcomplications
1
Findingthemaximumsumthatcanbeformedfromaset,bypartitioningitintotwosubset
0
Unabletofindwhat'swrongwithmycodeforsolvespojCWC15
HotNetworkQuestions
Doblockingcreatureshealbacktofullbetweenphases?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Ciertasconjugacionesverbalesnoconvencionales
Whyweren'ttheWeasleysapartoftheOriginalOrder?
ALN*NTicTacToeGame
Whatwereshoesolesmadefrominpreviousages?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
WhydosomepeoplerefertoLinuxasGNU/Linux?
What'sthebestwaytoinvestformakingregulardonations?
Needhelprecreatingcrazycolors/materialfromexample
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 129/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Isthereawordforpeopleincapableofthinking?
Whycan'tanonabeliangroupbe75%abelian?
What'sanexpressionforacunninglyfakefriend?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
DoesCIDRreally"doaway"withIPaddressclasses?
Whydotheymanifestasrings?
Troublewithterminatinga<apex:pageBlockSection>
CanIwriteapaperoutofasimpleidea
howcanItaketotalminutesfromtime?
ThenthTernary
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Solutiontofindingpositionof1insortedarrayof0and1
IgotacallfromAmazontoattendoneoftheirinterviewandgivenatesttowritemostefficientsolutiontothebelowproblem.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 130/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Tofindsmallestpositionof1insortedarrayof0and1.e.g.inarray0000001111outputshouldbe6.
Itriedbinary_searchonthisbutthatdoesnotutilizepropertythatarrayhasonly0and1.Canyougivemesomebettersolution.
upvote0downvote ThanksNirajRathi
favorite
arraysalgorithm
askedSep16'13at7:02
editedSep16'13at8:26
share|improvethisquestion
anonymous
620515
1 Anyspecificprogramminglanguage?user1907906Sep16'13at7:03
Whyistheoutput1for0000001111?Where'stheposition1inthis"array"?Countingfrom0fromtheleft,thesmallestpositionis6.Where
4
did1comefrom?AnTSep16'13at7:05
1 Canyouexplainwhatyoumeanbysmallestposition?Tomeitseemsthatthesmallestpositionis6Smac89Sep16'13at7:05
Ifyou'recountingfromtherightandit'ssorted,theanswerwillalwaysbeeither1oranotfounderrorofsomesort.pandubearSep16'13
1
at7:08
3 Iamfairlycertainthatbinarysearchistheoptimalsolution.MarcClaesenSep16'13at8:37
|show5morecomments
2Answers
activeoldestvotes
Youcouldusethefactthatthevaluesare0and1towriteastandardbinarysearchinamorecompactway:
intfirstOne(int[]arr){
int[]a=newint[2];
a[0]=0;
a[1]=arr.length;
while(a[1]a[0]>1){
intm=(a[1]+a[0])/2;
a[arr[m]]=m;
}
upvote5down
voteaccepted returna[1];
}
Becauseoftheuseofthearraya,wehavetheinvariantthatarr[a[0]]=0andarr[a[1]]=1.Iftheloopends,a[0]anda[1]pointtotwoconsecutive
arrayelements,soa[1]isthefirst1.NotethatIignoredspecialcases(all0,all1,oranemptyinput).
answeredSep16'13at9:56
share|improvethisanswer
VincentvanderWeele
8,47611340
addacomment|
sameasbinarytrythis..
while
{
ifarray[array.length/2]==1
{
ifarray[array.length/21]==0
return
array=1sthalfofarray
}
up else
{
vote2 ifarray[array.length/2+1]==0
down return
vote array=2ndhalfofarray
}
}
ItmightbeyoulookingforIfthereisanyideabetterthanthisiamreallyintrestedtolearn
answeredSep16'13at7:11
share|improvethisanswer
AntoVinish
40028
ItriedthesimilarapproachbutwhatkeptmethinkingisthatIamnotatallusingpropertyofarraythatitissortedbinaryarray.Ithinksinceitisarray,so
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 131/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
elementswillbeatconsecutivelocation.SothinkofitatmemoryareapartofwhichiscompletelyzeroandotherhalfhasLSBsetto1.Somaybewecan
usethistocomeupwithefficientsolution.memcmpisnotthatefficientasitisdoneoutsideprocessorcache.anonymousSep16'13at8:32
@NIRAJRATHIIdon'tthinkbinarycanbeimprovedhere.ThearrayisoftheformAAAAAAAAAAAAABBBBBandyouneedtofindtheborder
betweenAandB,whichcanbeanywhereinthearray.Binaryreallycan'tbeimprovedherebecausethereisnoextrainformationtohelpyoufindthat
borderinafasterway.DanielDaranasSep16'13at8:35
zerodoesn'tmeannomemoryforthat...both1and0takessamesizeinmemoryAntoVinishSep16'13at9:11
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedarraysalgorithmoraskyourown
question.
asked 1yearago
viewed 334times
active 1yearago
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 132/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Lookingforajob?
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
114PeopleChatting
JavaScript
14hoursagoGemtastic
Gemtastic:
Suman
Caprica
Awal
Mr_Green:
ivarni:
ASR:
14 Lama:
Six:Garg:
14 14 14
PHP
13hoursagoPeeHaa
PeeHaa:
Ronald
WP_boss:
Sebastian
Trowski:
kelunik:
Leri:
13 Ulysses
13 Bergmann:
13 14 15
Related
36
ArrayHomeworkQuestion
43
Sortinganalmostsortedarray(elementsmisplacedbynomorethank)
63
Findtherowrepresentingthesmallestintegerinrowwisesortedmatrix
4
Algorithmtofindmostcommonelementsindifferentarrays
1668
Removespecificelementfromanarray?
14
Findinganelementinpartiallysortedarray
2
findanelementininfinitesortedarray
8
Findthenumberofcoupleswiththesamedifferenceinasortedarray
256
Writeaprogramtofind100largestnumbersoutofanarrayof1billionnumbers
0
Howtofindanalmostsortedarray?
HotNetworkQuestions
Whycan'tanonabeliangroupbe75%abelian?
DoesCIDRreally"doaway"withIPaddressclasses?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
HowdoIfacilitateafirsttimeAgileretrospective?
Isturninggraphitecarbonintodiamondindustriallydoable?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Whatisatemporarysolutionforadamagedcarbody?
HowcouldaresurrectedJesusproveheisJesus?
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
RollmyD&Dcharacter'sabilityscores
Howtogetearlyentryintomystictheurge?
Antiferromagneticordering
Using"using"twiceinterpreteddifferentlybydifferentcompilers
ThenthTernary
Whydotheymanifestasrings?
FiveAnglesinaStar
WhoinventedStarTreksideburnsandwhy?
Whatistheoriginofthisphotoofanunexplodedbomb?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
ALN*NTicTacToeGame
DoesaUSB3.0connectionrequireaUSB3.0cord?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 133/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Createnumbersequenceoflengthxwithonlydifferenceof1bitinsuccessive
numbers
WasaskedthisAmazonTelephonicInterviewRound1
SoforLength=1
01(01)
Length=2
00011110(0,1,3,2)
upvote0downvotefavorite
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 134/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
1 andsoon
writefunctionforlengthxthatreturnsnumbersindigit(base10)form
amazonbitmanipulationnumbersequence
askedMay20'14at14:21
editedMay20'14at14:29
share|improvethisquestion
rishabhmonga
63
addacomment|
2Answers
activeoldestvotes
That'scalledgraycode,thereareseveraldifferentkinds,someofwhichareeasiertoconstructthanothers.Thewikipediaarticleshowsavery
simplewaytoconvertfrombinarytograycode:
unsignedintbinaryToGray(unsignedintnum)
{
return(num>>1)^num;
}
upvote3downvote
accepted Usingthat,youonlyhavetoiterateoverallnumbersofacertainsize,putthemthroughthatfunction,andprintthemhoweveryouwant.
answeredMay20'14at15:14
share|improvethisanswer
harold
21k22765
addacomment|
Thisisonewaytodoit:
intnval=(int)Math.Pow(2,n);
intdivisor=nval/2;
for(inti=0;i<nval;i++)
{
intnb=(int)(i%divisor);
if(nb==2)Console.WriteLine(i+1);
upvote0downvote elseif(nb==3)Console.WriteLine(i1);
elseConsole.WriteLine(i);
}
answeredMay20'14at14:55
editedMay20'14at15:08
share|improvethisanswer
mrida
5611410
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 135/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedamazonbitmanipulationnumber
sequenceoraskyourownquestion.
asked 1yearago
viewed 107times
active 1yearago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Related
442
Howtocountthenumberofsetbitsina32bitinteger?
6
Getlengthofbitsusedinint
7
Numberofbitstorepresentanumber
10
Extractbitsequencesofarbitrarylengthfrombyte[]arrayefficiently
0
HomeworkaboutbitsequenceinC
0
JavaThreadiwanttogeneratenumbersinsequenceeg:1,2,3,4soon(therewillbe2threadsonly)
2
countingthedifferenceinbitswhencomparingtwonumbersinLua
0
howtocreatetwonumbersequences
5
Createamaskthatmarksthemostsignificantsetbit,usingonlybitwiseoperators
0
Whydosomenumbersequencesreturn000000insteadofanewnumber?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 136/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
HotNetworkQuestions
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Paidcashforacar,butdealerwantstochangeprice
howcanItaketotalminutesfromtime?
Wordfor"animals,includinghumans"?
Troublewithterminatinga<apex:pageBlockSection>
DoesCIDRreally"doaway"withIPaddressclasses?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Needhelprecreatingcrazycolors/materialfromexample
ALN*NTicTacToeGame
CanIflywithagoldbar?
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Whatistheoriginofthepowericon?
Needtostartareligionwithapredefinedselfdestruct
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
HowtoprovemyGmailhasbeenhacked?
Whatistheoriginofthisphotoofanunexplodedbomb?
DoesaUSB3.0connectionrequireaUSB3.0cord?
Justifyingsuboptimalresearchqualitybylackofsupervision
Antiferromagneticordering
NineTallMenAreStandingTall
Whyadding"incolour"whenreferringto"WizardofOz"?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
Packagetodonotes:HowcanIchangethetextcolor?
40Numbersin9Bytes
morehotquestions
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 137/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
AmazonInterviewaboutSuccessprobability[duplicate]
PossibleDuplicate:
Failurerateofasystem
Ifasystemhasa10%independentchanceoffailinginanygivenhour,whatarethechancesofitfailinginagiven2hourperiodornhoursperiod?Note:
10%failureprobabilityin1hourhasnothingtodowith10%ofthetime.It'sjustthatasystemhasa10%independentchanceoffailinginanygiven
upvote1 hour
downvote
favorite probability
askedDec1'12at6:09
editedDec3'12at21:38
share|improvethisquestion
sammy123
13
markedasduplicatebyMattBall,MichaelPetrotta,DonalFellows,evilone,AtanasKorchevDec1'12at
8:37
Thisquestionhasbeenaskedbeforeandalreadyhasananswer.Ifthoseanswersdonotfullyaddressyourquestion,pleaseaskanewquestion.
1 Thisquestionisprobablyabetterfitformath.stackexchange.comcegfaultDec1'12at6:12
sorryaboutthat..!!sammy123Dec1'12at6:15
1 Thismighthelpstackoverflow.com/a/6819375/1791606QoopDec1'12at6:17
@QoopYa,Icheckedthatbutinthatquestion,failingprobabilityis10%ofthetimebutinthisquestion,failingprobabilityof10%isnot10%of
thetime,it'sjustrelatedtothesystem.IhopeyouunderstandwhatImean.Thanksforyourhelp.Iappreciatethat.sammy123Dec1'12at6:22
addacomment|
1Answer
activeoldestvotes
LetPfailbetheprobabilitythatthesystemfailsinanygivenhour.
ThenPnofail,theprobabilitythatthesystemdoesnotfailinanygivenhour,is1Pfail.
Thechanceofitnotfailingin2hoursis(Pnofail)2,sinceitmustindependentlynotfailineachofthosehours,andthejointprobabilityoftwo
independenteventsistheproductoftheprobabilityofeachevent(thatis,P(AB)=P(A)*P(B)).
Moregenerally,then,thechanceofitnotfailinginnhoursis(Pnofail)n.
upvote3 Thechanceofitfailinginnhoursis1(chanceofnotfailinginnhours).
downvote
Youshouldbeabletoworkitoutfromthere.
answeredDec1'12at6:19
editedDec1'12at6:39
share|improvethisanswer
MattBall
192k39343426
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedprobabilityoraskyourownquestion.
asked 2yearsago
viewed 477times
active 2yearsago
Lookingforajob?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 138/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Linked
0
Failurerateofasystem
Related
359
CosmicRays:whatistheprobabilitytheywillaffectaprogram?
3
RandomizedAlgorithmProbabilityMaximization
1
estimatingtheprobabilityof3peoplesharingabirthday
30
Aninterviewquestion:AboutProbability
1
Probabilityofevent
70
Whatistheprobabilitythatthearraywillremainthesame?
1
HowdoIcalculatetheprobablesuccessrateinagame:x+random(12)=>y
1
ProbabilityCoinTossing
1
Probabilityofstaterepresentation
4
Calculatingprobabilitiesoverapopulation
HotNetworkQuestions
WhatdoesitmeanifanACmotorhastwovoltageratings?
Multiplypurefunctionwithscalar
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
Nicelytypesettingverbatimtext
Doblockingcreatureshealbacktofullbetweenphases?
NineTallMenAreStandingTall
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
SixMusicalFriends
WhydosomepeoplerefertoLinuxasGNU/Linux?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Whatistheoriginofthepowericon?
Antiferromagneticordering
MementoVivereMomentumMori
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Clientwantsfontaslogo
Justifyingsuboptimalresearchqualitybylackofsupervision
ImageOpensasLayer0ratherthanBackground
Jumpingcarwithtoomanyamps?
Whatwereshoesolesmadefrominpreviousages?
Whyshouldakeybemadeexplicit?
Alarmclockprinting
Packagetodonotes:HowcanIchangethetextcolor?
morehotquestions
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
AMAZONInterviewQuestion
GivenanNarraysofsizeKeach..eachoftheseKelementsintheNarraysaresorted,eachoftheseN*Kelementsareunique.Chooseasingleelement
fromeachoftheNarrays,fromthechosensubsetofNelements.Subtracttheminimumandmaximumelement.Now,thisdifferenceshouldbeleast
possibleMinimum..Hopetheproblemisclear:):)
Sample:
N=3,K=3
upvote18 N=1:6,16,67
downvote N=2:11,17,68
N=3:10,15,100
favorite
24
hereif16,17,15arechosen..wegettheminimumdifferenceas1715=2.
amazon
editedMay23'11at8:05 askedMay23'11at7:48
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 140/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
share|improvethisquestion
SachinShanbhag ManjunathManoharan
25.2k54579 1,92431330
2 whathaveyoutriedsofar?ManojRMay23'11at8:05
thisisactuallyprettydifficultquestionforaninterview,especiallyifitwasa30or45minonsiteorphoneinterview.goodforAMAZON:)
zviadmMay25'11at18:02
6 Youactuallydon'taskaquestion...I'msurprisedeveryonejustassumedyouwantedbigOnotation.RussellAsherSep4'12at23:15
What'sthequestion?Howtopicktherightnumberswhichhavearequireconstraint(i.e.theirdifferencebetheminimumpossible?)Lorenzo
1
DemattFeb28'13at15:58
1 After3years,Istilldon'tgetthequestionMatiCiceroOct28'14at12:41
addacomment|
7Answers
activeoldestvotes
IcanthinkofO(N*K*N)(editedaftercorrectlypointedoutbyzivo,notagoodsolutionnow:()solution.
1.TakeNpointerinitiallypointingtoinitialelementeachofNarrays.
6,16,67
^
11,17,68
^
10,15,100
^
2.FindoutthehighestandlowestelementamongthecurrentpointerO(k)(6and11)andfindthedifferencebetweenthem.(5)
3.Incrementthepointerwhichispointingtolowestelementby1inthatarray.
6,16,67
^
11,17,68
^
10,15,100(difference:5)
^
4.Keeprepeatingstep2and3andstoretheminimumdifference.
6,16,67
^
11,17,68
^
10,15,100(difference:5)
^
6,16,67
^
11,17,68
^
10,15,100(difference:2)
^
Abovewillbetherequiredsolution.
6,16,67
^
upvote9 11,17,68
downvote ^
accepted 10,15,100(difference:84)
^
6,16,67
^
11,17,68
^
10,15,100(difference:83)
^
Andsoon......
EDIT:
Itscomplexitycanbereducedbyusingaheap(assuggestedbyUri).Ithoughtofitbutfacedaproblem:Eachtimeanelementisextractedfromheap,its
arraynumberhastobefoundoutinordertoincrementthecorrespondingpointerforthatarray.Anefficientwaytofindarraynumbercandefinitely
reducethecomplexitytoO(K*Nlog(K*N)).Onenaivewayistouseadatastructurelikethis
Struct
{
intelement;
intarraynumer;
}
andreconstructtheinitialdatalike
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 141/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
6|0,16|0,67|0
11|1,17|1,68|1
10|2,15|2,100|2
Initiallykeepthecurrentmaxforfirstcolumnandinsertthepointedelementsinheap.Noweachtimeanelementisextracted,itsarraynumbercanbefound
out,pointerinthatarrayisincremented,thenewlypointedelementcanbecomparedtocurrentmaxandmaxpointercanbeadjustedaccordingly.
editedMar30'12at16:37 answeredMay25'11at19:04
share|improvethisanswer
VijayDev Terminal
7,424144985 1,1081124
thisisactuallyNKNsolution.Ifiamnotmistaken.becauseyouchangpointersn*ktimesandeachtimeyouneedO(N)operationszviadmMay25
'11at19:11
@zvio:Right!!Thanksforpointingitout.Ioverlookedit.TerminalMay25'11at19:20
MaybeyoucanoptimizetoNKlog(N),ifyoukeeptheNpointersinaheap,whichwillfindtheminimumelement.Theextractminimum,andinsert
newelementarebothlog(N)operations.Forthemaximumelement,youjustneedtokeepwhichpointeristhemaximumandcompareiteverytimeyou
advanceapointer.Nicesolution.UriMay25'11at21:21
@Uri:thanks!!ihaveupdatedthesolution.TerminalMay26'11at7:09
Interestingsolution.Couldweoptimizebyusingbinarysearchononearrayandincrementsontheother?karthikrSep26'14at1:23
addacomment|
Sohereisanalgorithmtodosolvethisproblemintwosteps:
Firststepistomergeallyourarraysintoonesortedarraywhichwouldlooklikethis:
combined_val[]whichholdsallnumbers
combined_ind[]whichholdsindexofwhicharraydidthisnumberoriginallybelongedto
thisstepcanbedoneeasilyinO(K*N*log(N))butithinkyoucandobetterthanthattoo(maybenot,youcanlookupvariantsofmergesortbecausetheydostep
similartothat)
Nowsecondstep:
itiseasiertojustputcodeinsteadofexplainingsohereisthepseduocode:
intcount[N]={0}
inthead=0;
intdiffcnt=0;
//mindiffisinitializedtooverallmaximumvalueoverallminimumvalue
intmindiff=combined_val[N*K1]combined_val[0];
for(inti=0;i<N*K;i++)
{
count[combined_ind[i]]++;
if(count[combined_ind[i]]==1){
//diffcntcountshowmanyarrayshaveatleastoneelementbetween
//indexesof"head"and"i".OncediffcntreachesNitwillstayNand
//notincreaseanymore
diffcnt++;
upvote }else{
4down while(count[combined_ind[head]]>1){
//Wetrytomoveheadindexasforwardaspossiblewhilekeepingdiffcntconstant.
vote //i.e.ifcount[combined_ind[head]]is1,thenifwewouldmoveheadforward
//diffcntwoulddecrease,thatissomethingwedontwanttodo.
count[combined_ind[head]];
head++;
}
}
if(diffcnt==N){
//i.e.wegotatleastoneelementfromallarrays
if(combined_val[i]combined_val[head]<mindiff){
mindiff=combined_val[i]combined_val[head];
//ifyouwanttosaveactualnumberstoo,youcansavethis(i.e.iandhead
//andthenextractdatafromthat)
}
}
}
theresultisinmindiff.
TheruningtimeofsecondstepisO(N*K).Thisisbecause"head"indexwillmoveonlyN*Ktimesmaximum.sotheinnerloopdoesnotmakethisquadratic,it
isstilllinear.
SototalalgorithmrunningtimeisO(N*K*log(N)),howeverthisisbecauseofmergingstep,ifyoucancomeupwithbettermergingstepyoucanprobably
bringitdowntoO(N*K).
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 142/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
answeredMay25'11at17:53
editedMay25'11at18:42
share|improvethisanswer
zviadm
81768
Hey..youhaveforgottentoaddthesnippetformindiffinitialization..IalsothinkIunderstoodbutamnotveryclear.couldyoualsoaddasmallcomment
inyourcode,especiallyinthehead++ManjunathManoharanMay25'11at18:25
mindiffisinitializedtolargestpossiblevaluewhichisoverallmaximumnumberoverallminimumnumber.Mainpointofthisalgorithmistofind
minimumandmaximumvalues.Index"i"pointstomaximumvalue.Index"head"pointstominimumvalue.Everytimeweincrease"i"wetrytomove
index"head"asfartheraspossiblewhilewestillkeepatleastoneelementfromeveryarray.zviadmMay25'11at18:44
Thisisabriliantsolution.Yourcommentaboutmyalgorithmbeingfalseisinplace.Idon'tthinkyoucandobetterthanO(NKlog(N)),atleastnotinthe
worsecase,atleastnotthe'N'parts,otherwise,inthespecialcaseofK=1you'llbeabletosortanarrayinatimebetterthanN*Log(N)UriMay25'11at
18:49
Thanks@Uri.Yourobservationmakessenseaboutthemergestep.ThusmergingarraystrulytakesO(N*K*log(N))inworstcasescenario.zviadm
May25'11at18:55
addacomment|
Thisproblemisformanagers
Youhave3developers(N1),3testers(N2)and3DBAs(N3)Choosethelessdivergentteamthatcanrunaprojectsuccessfully.
int[n]result;//whereresult[i]keepstheelementfrombucketN_i
int[n]latest;//wherelatest[i]keepsthelatestelementvisitedfrombucketN_i
Iterateelementsin(N_1+N_2+N_3)insortedorder
{
KeeptrackoflatestelementvisitedfromeachbucketN_ibyupdating'latest'array;
ifboundary(latest)<boundary(result)
upvote3downvote {
result=latest;
}
}
intboundary(int[]array)
{
returnMax(array)Min(array);
}
answeredNov25'12at0:03
share|improvethisanswer
random
312
addacomment|
I'veO(K*N*log(K)),withtypicalexecutionmuchless.Currentlycannotthinkanythingbetter.I'llexplainfirsttheeasiertodescribe(somewhatlonger
execution):
1. Foreachelementfinthefirstarray(loopthroughKelements)
2. Foreacharray,startingfromthesecondarray(loopthroughN1arrays)
3. Doabinarysearchonthearray,andfindelementclosesttof.Thisisyourelement(Log(K))
up
vote1 Thisalgorithmcanbeoptimized,ifforeacharray,youaddanewFloorIndex.Whenperformentthebinarysearch,searchbetween'Floor'to'K1'.InitiallyFloor
down indexis0,andforfirstelementyousearchthroughtheentirearrays.Onceyoufindanelementclosestto'f',updatetheFloorIndexwiththeindexofthat
vote element.Worsecaseisthesame(Floormaynotupdate,ifmaximumelementoffirstarrayissmallerthananyotherminimum),butaveragecasewillimprove.
answeredMay23'11at8:12
share|improvethisanswer
Uri
5,50722143
HeyNicesolution,Iwasthinkingofworkingonasolutionthatusesminheapandamaxheap..anysuggestionsonthatManjunathManoharanMay23
'11at8:22
thisalgorithmisnotcompleteorcorrect.Letssayyouchose10fromN=1.(firstarray)N=2:115N=3:516youwillchoose15and5soyourdifferenceis
1
10,butifyouchose15and16yourdifferencewouldbe6.zviadmMay25'11at17:01
@zviadmSamesolutionIcameupwithin~10secondsafterlookingattheproblem,andimmediatelyIstartedwonderingifitiscorrect...still,Ithinkitis
headingintherightdirectionLorenzoDemattFeb28'13at16:06
solutioniscorrect.onlyfindtheceilandfloorofminimumelementfoundsofar.andkeeptheonewhichisclosertotheminimum.1.takefirstelementfrom
firstarrayandconsideritasminimum.2.findceilandfloorofminimuminsecondarrayandchoosetheonewhichisclosertominimum.3.updatethe
minimum4.searchinsubsequentrows.5.dothisforallelemntsofrow1shiviJan4'14at4:41
addacomment|
Correctnessprooffortheacceptedanswer(Terminal'ssolution)
AssumethatthealgorithmfindsaseriesA=<A[1],A[2],...,A[N]>whichisn'ttheoptimalsolution(R).
ConsidertheindexjinR,suchthatitemR[j]isthefirstitemamongRthatthealgorithmexaminesandreplacesitwiththenextiteminitsrow.
up
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 143/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
vote LetA'denotethecandidatesolutionatthatphase(priortothereplacement).SinceR[j]=A'[j]istheminimumvalueofA',it'salsotheminimumofR.Now,
1 considerthemaximumvalueofR,R[m].IfA'[m]<R[m],thenRcanbeimprovedbyreplacingR[m]withA'[m],whichcontradictsthefactthatRisoptimal.
down Therefore,A'[m]=R[m].Inotherwords,RandA'sharethesamemaximumandminimum,thereforetheyareequivalent.Thiscompletestheproof:ifRisan
vote optimalsolution,thenthealgorithmisguaranteedtofindasolutionasgoodasR.
answeredFeb28'13at15:52
share|improvethisanswer
EyalSchneider
13k22040
addacomment|
foreveryelementin1starray
choosetheelementin2ndarraythatisclosesttotheelementin1starray
current_array=2;
do
{
upvote0downvote choosetheelementincurrent_array+1thatisclosesttotheelementincurrent_array
current_array++;
}while(current_array<n);
complexity:O(k^2*n)
answeredFeb28'13at15:05
share|improvethisanswer
user2120127
addacomment|
1. CreateaobjofNarrays.LetKbethenumberofitemsineachofN
2. YoucangeneratearandomarraypickingonerandomelementfromeachofNarrays.
3. Sortthegeneratedrandomarray
4. Findthedifferenceoflastfirsthttp://jsfiddle.net/enbdrekj/7/
ThatshowIunderstoodthisquestion.Timetakenroughly50mins
varArrObj={
n1:[6,16,67],
upvote0downvote n2:[11,17,68],
n3:[10,15,100],
n4:[12,18,101]
answeredApr9at10:35
share|improvethisanswer
SrikanthKondaparthy
615169
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 144/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedamazonoraskyourownquestion.
asked 4yearsago
viewed 25366times
active 3monthsago
Lookingforajob?
ChiefSoftwareArchitectJava$100K
Crossover
Bengaluru,India/remote
eclipsenetbeans
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
Related
5
BuildingAmazonAffiliateslinks
0
AmazonProductUploadsinInventorynotworking?
5
HowtoautomateAmazonAssociatesearningsreportdownload?
1
ProgramaticallybuyingfromAmazon
0
AmazonAWSManagementConsole
5
FilteringordeterminingwarehousedealsviaAmazonProductAdvertisingAPI?
0
AmazonProductAdvertisingAPI
0
AmazonCredentialsforXervmon
1
AmazonProductImport
0
AmazonDailyDealsAPI
HotNetworkQuestions
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 145/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
What'sthebestwaytoinvestformakingregulardonations?
DoesCIDRreally"doaway"withIPaddressclasses?
Whyshouldakeybemadeexplicit?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Whatis`$?`?Isitavariable?
Canmathbesubjective?
Drawinganarrayofnodesusingtheforeachconstruct
SixMusicalFriends
LeapyearcheckinJava
zero,zerosorzeroes?
ImageOpensasLayer0ratherthanBackground
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
NineTallMenAreStandingTall
Whatistheoriginofthepowericon?
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
WhydosomepeoplerefertoLinuxasGNU/Linux?
FiveAnglesinaStar
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Derivativeofadefiniteintegralissue
Whydotheymanifestasrings?
BenefitsofSETTRANSACTIONISOLATIONLEVELREADUNCOMMITTED
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
Howtoprotectaspaceelevatoragainstterrorism
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 146/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
MinimumvalueofmaximumvaluesinsubsegmentsinO(n)complexity
IinterviewedwithAmazonafewdaysago.Icouldnotansweroneofthequestionstheaskedmetotheirsatisfaction.Ihavetriedtogettheanswerafterthe
interviewbutIhavenotbeensuccessfulsofar.Hereisthequestion:
Youhaveanarrayofintegersofsizen.Youaregivenparameterkwherek<n.Foreachsegmentofconsecutiveelementsofsizekinthearrayyouneedto
calculatethemaximumvalue.Youonlyneedtoreturntheminimumvalueofthesemaximumvalues.
Forinstancegiven123112111andk=3theansweris1.
Thesegmentswouldbe123,231,311,112,121,211,111.
Themaximumvaluesineachsegmentare3,3,3,2,2,2,1.
upvote Theminimumofthesevaluesare1thustheansweris1.
10down
vote ThebestanswerIcameupwithisofcomplexityO(nlogk).WhatIdoistocreateabinarysearchtreewiththefirstkelements,getthemaximumvalueinthe
favorite treeandsaveitinvariableminOfMax,thenlooponeelementatatimewiththeremainingelementsinthearray,removethefirstelementintheprevioussegment
7 fromthebinarysearchtree,insertthelastelementofthenewsegmentinthetree,getthemaximumelementinthetreeandcompareitwithminOfMaxleavingin
minOfMaxtheminvalueofthetwo.
TheidealanswerneedstobeofcomplexityO(n).Thankyou.
arraysalgorithmdatastructuresbigo
editedMay5'13at15:08 askedDec14'11at3:37
share|improvethisquestion
templatetypedef DavidF
157k35389625 635
addacomment|
2Answers
activeoldestvotes
Thereisaverycleverwaytodothisthat'srelatedtothisearlierquestion.Theideaisthatit'spossibletobuildaqueuedatastructurethatsupportsenqueue,
dequeue,andfindmaxinamortizedO(1)time(therearemanywaystodothistwoareexplainedintheoriginalquestion).Onceyouhavethisdatastructure,
beginbyaddingthefirstkelementsfromthearrayintothequeueinO(k)time.SincethequeuesupportsO(1)findmax,youcanfindthemaximumofthesek
elementsinO(1)time.Then,continuouslydequeueanelementfromthequeueandenqueue(inO(1)time)thenextarrayelement.YoucanthenqueryinO(1)
whatthemaximumofeachofthesekelementsubarraysare.Ifyoutracktheminimumofthesevaluesthatyouseeoverthecourseofthearray,thenyouhave
upvote anO(n)time,O(k)spacealgorithmforfindingtheminimummaximumofthekelementsubarrays.
9down
vote Hopethishelps!
accepted
answeredDec14'11at4:11
share|improvethisanswer
templatetypedef
157k35389625
Nicesolution,butterribleinterviewquestion.Eitheryouarefamiliarwiththisdatastructure,andtheproblemistrivialoryouarenot,andtheproblemis
impossible.(Unlessyouwanttopretendyoucameupwithitduringtheinterview?)Iwonderwhetherthereisamoredirectapproach,orifthisisjusta
crappyinterviewquestion.NemoDec14'11at4:44
@NemoIonlyknewhowtosolvethisbecauseIknewabouttheminqueuedatastructure,whichIonlyknewaboutbecauseIspentfourhourstryingto
1 figureouthowtomakeitbeforeseeingthetwostackimplementationbasedoffoftheminstack,whichitselfisahardinterviewquestion.Ithinkthere
maybeaneasierwaytosolvethis,buthonestlyIhavenoideahowtoapproachthisproblemanyotherway.templatetypedefDec14'11at4:47
Ihavethoughtaboutitabit,andIdon'tseeit,either.Thefactthatyouonlywantonevalueattheend(notevenitslocation)istantalizing,butIjustdonot
seehowtoexploitit.NemoDec14'11at4:49
OKIthinkIfoundit:)NemoDec14'11at5:05
+1Nicesolution.TryingJul19'13at6:00
|show1morecomment
@templatetypedef'sanswerworks,butIthinkIhaveamoredirectapproach.
Startbycomputingthemaxforthefollowing(closed)intervals:
[k1,k1]
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 147/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
[k2,k1]
[k3,k1]
...
[0,k1]
Notethateachofthesecanbecomputedinconstanttimefromthepreceedingone.
Next,computethemaxfortheseintervals:
[k,k]
[k,k+1]
[k,k+2]
...
[k,2k1]
Nowtheseintervals:
[2k1,2k1]
upvote8 [2k2,2k1]
[2k3,2k1]
downvote ...
[k+1,2k1]
Nextyoudotheintervalsfrom2kto3k1("forwardsintervals"),thenfrom3k1downto2k+1("backwardsintervals").Andsoonuntilyoureachtheendof
thearray.
Putalloftheseintoabigtable.Notethateachentryinthistabletookconstanttimetocompute.Observethatthereareatmost2*nintervalsinthetable
(becauseeachelementappearsonceontherightsideofa"forwardsinterval"andonceontheleftsideofa"backwardsinterval").
Now,if[a,b]isanyintervalofwidthk,itmustcontainexactlyoneof0,k,2k,...
Sayitcontainsm*k.
Observethattheintervals[a,m*k1]and[m*k,b]arebothsomewhereinourtable.Sowecansimplylookupthemaxforeach,andthemaxofthosetwo
valuesisthemaxoftheinterval[a,b].
Soforanyintervalofwidthk,wecanuseourtabletogetitsmaximuminconstanttime.WecangeneratethetableinO(n)time.Resultfollows.
answeredDec14'11at5:05
share|improvethisanswer
Nemo
37.5k659103
+1Thisisabeautifulsolution.ThisremindsmeoftheO(n)/O(1)solutiontotherangeminimumqueryproblem.Though,Imustadmit,mysolution
2
usesonlyO(k)memory,whilethisusesO(n).:)templatetypedefDec14'11at5:23
@templatetypedefIwaswonderingifyouweregoingtopointthatout:)NemoDec14'11at5:53
@NemoThisparticularstrategyforsolvingthisproblemseemslikeitshouldbeaspecialcaseofamuchmoregeneraltechniqueforreasoningabout
rangesinarrays.Isthereanameforthistechnique?Canitbegeneralizedtootherproblems?templatetypedefDec14'11at6:06
@templatetypedefIfyousquint,it'sasegmenttreewithcarefullychosenparameters.ThespaceusagecanbereducedtoO(k)bycomputingthebig
1
tableincrementally.PerDec14'11at16:05
@NemoHiNemo.CouldyoupleasestatehowthistablelookslikeI.e.howmanyrowsandcolumnsitcontainsandsomesamplevaluesonitforthe
exampleIprovidedintheproblem?Thanks.DavidFDec15'11at18:46
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 148/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedarraysalgorithmdatastructuresbigo
oraskyourownquestion.
asked 3yearsago
viewed 1681times
active 2yearsago
Lookingforajob?
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Linked
51
Implementaqueueinwhichpush_rear(),pop_front()andget_min()areallconstanttimeoperations
16
Findingmaximumforeverywindowofsizekinanarray
9
Howtofindmaximumofeachsubarrayofsomefixedgivenlengthinagivenarray
2
Highestvalueoflastkvaluesinarray,betterthanO(n^2)
Related
30
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 149/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Givenanarray,canIfindinO(n)thelongestrange,whoseendpointsarethegreatestvaluesintherange?
1
BigOtimecomplexityofalgorithm
0
Timecomplexityforgeneratingbinaryheapfromunsortedarray
2450
Pairsocksfromapileefficiently?
4
Maximum/Minimumofallsubarrays/Windowsofsizek(MustReadtheAcceptedAnswer,NewMethod)
5
datastructureinterview:findmaxnumberinarray
1
Whatisthetimecomplexityofbelowalgorithm
1
AlgorithmforbetterBigOcomplexity
0
TimeComplexityforremovingthesmallestvalueinasortedarray
5
Fillinganarrayinsuchawaythateachelementequaltominimumsumoftwonumberssuchthat
HotNetworkQuestions
OptimalRopeBurning
RollmyD&Dcharacter'sabilityscores
Needtostartareligionwithapredefinedselfdestruct
Whatis`$?`?Isitavariable?
NineTallMenAreStandingTall
ThenthTernary
WhoinventedStarTreksideburnsandwhy?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
WhatdoesitmeanifanACmotorhastwovoltageratings?
Doblockingcreatureshealbacktofullbetweenphases?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
HowtodealwithaGMwhodoesnottelluseverything?
40Numbersin9Bytes
WhyareUNIX/POSIXsystemcallnamingssoillegible?
HowdoIupgradefromGPLv2toGPLv3?
ImageOpensasLayer0ratherthanBackground
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Troublewithterminatinga<apex:pageBlockSection>
Whyadding"incolour"whenreferringto"WizardofOz"?
Alarmclockprinting
Howtodrawsequenceofshapeswitharrowsandtext
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 150/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Findatargetvalueinanunsortedarrayofintegersbyperformingadditionsof
integers
Followingisaninterviewquestionaskedby'Amazon'tome.Istillhaven'tcomeupwithaoptimizedsolution.
ProblemStatement:
Givenanunsortedarrayofintegersn.Return'true'iftheadditionofanyintegersfromthatarraymatcheswiththetargetvalueelsereturnfalse.
Note:
1)'n'couldbe1000or10,000.
2)Targetvaluecouldbe'negative'
3)Itmaybeadditionofany'k'integers(notonlytwo),wherek<=n.
TestCondition:
upvote3down i/p:ArrayA[]={6,7,3,0,12,5,6,100}
votefavorite Target=8
3 o/p:TRUE
As,6+7+(5)=8
IfwetrytodoitlinearlyornormallyitwilltakeO(2^n)timecomplexity.
SoIamlookingforanymethodoralgorithmwhichwilloptimizedthisproblemmore.
Thankyouinadvance!
calgorithmoptimization
askedFeb1'13at3:40
editedFeb2'13at17:05
share|improvethisquestion
SRJ
4781727
2 "AdditionofanyTWOintegers"doyoumean?oranynumber?KarthikTFeb1'13at3:42
IfI'mhearingyouright,youwereaskedtosolvethesubsetsumproblem,whichisNPcomplete.Soyoucan'treasonablybeexpectedtodoalot
3
betterthanexponentialtimeorpseudopolynomialtime.nneonneoFeb1'13at3:43
1 Ifitisapairofintegers,IthinkyoumeanO(n^2)time,notO(2^n).HewWolffFeb1'13at3:59
It'ssadthatonlytwopeopleunderstandsuchaclearquestion.Everybodybesides@nneonneoandkasavbereiswayoff.Dopeoplereadquestions
3
anymore?Ordotheysimplythinktheyknowsomuchbetter?KonsolLabapenFeb1'13at17:20
1 @KarthikTNo.Itmaybetheadditionof'k'numbers,wherek<=nSRJFeb2'13at0:05
|show1morecomment
3Answers
activeoldestvotes
ThesubsetsumproblemisawellknownNPcompleteproblem.Here,I'mgoingtoassumethatyouarelookingforanysetofnumberstosumtothetarget(if
you'reactuallylookingforonlytwonumbers,there'safivelinesolutionusingacountinghashtablewhichrunsinO(n)time).
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 151/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Therearetwobasicapproaches.Thefirstisjusttotesteverypossiblesubsequence.Asyou'vealreadyobserved,thattakesO(2n)time(exponential),whichis
intractableifnis1000.
Thesecondistokeeptrackofwhatsumsareobtainablefromprefixesofthelist.Thisisaverysimpleapproach,andworkswelliftheintegersarebounded.By
wayofexample,iftheinputisnkbitintegers,ithascomputationalcomplexityO(2kn2)(pseudopolynomial):thebiggestthesumscangetis2kn,sothetable
hasatmost2kn2entries.Thisisatypicaldynamicprogrammingapproach,wherethesubproblemisT[s][k]=(A[1..k]hasasubsequencesummingtos),
andthefinalsolutionisgivenbyT[target][n].
Here'sasolutioninPythonimplementingthis:
defsubset_sum(A,target):
T={0}#T[s][0]=(TRUEiffs==0)
foriinA:
T|={x+iforxinT}
returntargetinT
Examples:
>>>subset_sum([5,6,7,1,0,12,5,6,100],13)
True
upvote >>>subset_sum([95,120,22,14491],13)
5down False
vote
accepted
Bonus:Ifyou'recurious,here'sasolutiontothepairsumproblem.ItrunsinO(n)timeandtellsyouifthearrayhastwonumberssummingtothetarget.
fromcollectionsimportCounter
defpair_sum(A,t):
C=Counter(A)
fork,vinC.iteritems():
ift==k+kandv>1:returnTrue#kisinthearraytwice
elift!=k+kandtkinC:returnTrue
returnFalse
Examples:
>>>pair_sum([3,3,3,4],13)
False
>>>pair_sum([3,3,3,10],13)
True
>>>pair_sum([7,7,2],14)
True
>>>pair_sum([7,14,2],14)
False
answeredFeb1'13at18:26
editedFeb1'13at18:32
share|improvethisanswer
nneonneo
77.9k1386162
Excellentanswer.NikBougalisFeb1'13at18:42
@nneonneoThanksforsuchawonderfulexplanation.SRJFeb2'13at0:10
addacomment|
Whataboutsortthearray,andforeachelementcalculatethepairnecessarytothetargetvalueandsearchforit?thatwouldmakethecostofsorting+
pluseachbinarysearch.
upvote0down answeredFeb1'13at3:52
vote
share|improvethisanswer
hamilton.lima
588415
SothatwouldbeO(nlogn)time.HewWolffFeb1'13at3:58
addacomment|
NOTEThisanswerisstillinformativesoI'mkeepingit,butafterOP'sedititislessrelevant.
HereishowIwouldsolveitinO(n)runtimecomplexityandO(n)spacecomplexityusingaconceptcalled'Hashing'.(Wherenisthesizeofthearray)
Let'scallthenumberI'dliketogetd
FirstIwouldcreatesomesortofHashTable(akeyvaluestore).HashMapshaveO(1)insert,getandcontains.Youcanreadaboutthemhere
ThenIwouldputeveryobjectinthecelldobjectinthehashmap.BeforeIcheckthenextnumberxI'dcheckifthehashmapcontainsavalueatcellx.Ifitdoes
we'vefoundourmatch.
up
vote Hereissomepseudocode(IthinkthisisbetterforageneralanswerthanCcode)
0
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 152/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
down CheckIfTwoNumbersComplementTo(d,arr)
vote map<newHashTable
foreachnumberxinArr
if(mapcontainsakeyforx)
returntrue
else
adddxtomapifitisnotalreadyinmap
returnfalse
answeredFeb1'13at3:46
editedMar21'13at1:45
share|improvethisanswer
BenjaminGruenbaum
77.3k22160246
Nice,butIbetyourhashtableisgoingtotakeupmorethanO(n)space.Togeteffectivelyconstanttimeoperations,you'llneedtoallocatespaceformany
hashbuckets,won'tyou?HewWolffFeb1'13at3:55
MyHashTablecanbeimplementedinexactlyO(n)space.Icansimplyallocateanarrayofsize[n]andusetheindexesdirectlyaskeys:)Ididnotwantto
specificallysuggestthatintheanswerbecauseIwantedtokeepthesolutionasgeneralaspossible.BenjaminGruenbaumFeb1'13at3:56
Thisworksonlyifthequestioniscorrectedtosay:"..iftheadditionof/two/integers..".Furthermore,exactlyO(n)doesn'tmakeanysense,didyoumean
exactlynspace?Butthenthatisplainfalse,givenyourownexample.Arrayallowsforduplicates,sosupposewewanttofindthesum1000,andwehavean
2
arrayofonethousand1s.Madcollisionwithyourschemehappens(andthealgorithmdoesn'tworkinthiscaseeither,sinceitisnolongeraboutsumming
twointegerstofindagivenvalue).mmgpFeb1'13at4:01
IassumedOPwastalkingaboutanytwointegers.Imeantnspaceandnsteps.TheminuteIgetaduplicateI'mdonesoIdon'tcareaboutduplicates
BenjaminGruenbaumFeb1'13at4:04
Again,IdonotunderstandwhyIshouldcareaboutduplicates,Idon'treallyhavetostore1amilliontimes,I'lleditmyanswertoclarifythoughthat'sagood
1
point.BenjaminGruenbaumFeb1'13at4:13
|show4morecomments
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 153/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Nottheansweryou'relookingfor?Browseotherquestionstaggedcalgorithmoptimizationoraskyour
ownquestion.
asked 2yearsago
viewed 1097times
active 2yearsago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
LeadiOSDevloper
NewsInShorts
Noida,India/relocation
iosobjectivec
Related
240
Fastestsortoffixedlength6intarray
5
Howtofindkthsmallestintegerinanunsortedarraywithoutsortingthearray?
4
GivenanarrayofsizeNIneedtofindtheminnumberofvaluesthatwillsumupwithinaminandmaxrange
11313
Whyisprocessingasortedarrayfasterthananunsortedarray?
2
Howtofind2numbersandtheirsuminanunsortedarray
1
Findingaspecificratioinanunsortedarray.Timecomplexity
1
Finddominantmodeofanunsortedarray
2
Givenatargetsumandasetofintegers,findtheclosestsubsetofnumbersthataddtothattarget
4
FindtheduplicateelementinanarrayofconsecutiveintegersinO(logn)time
1
Findsmallestintegerinarraywhichisadivisorofallpreviousintegers
HotNetworkQuestions
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
NineTallMenAreStandingTall
Alarmclockprinting
Justifyingsuboptimalresearchqualitybylackofsupervision
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
Patchingabinarywithdd
Howtodrawsequenceofshapeswitharrowsandtext
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
ALN*NTicTacToeGame
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 154/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
WhydosomepeoplerefertoLinuxasGNU/Linux?
Whatistheoriginofthisphotoofanunexplodedbomb?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
PythonLabelExpression?ArcGIS10.3.1
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
HowdoIfacilitateafirsttimeAgileretrospective?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Isturninggraphitecarbonintodiamondindustriallydoable?
Clientwantsfontaslogo
Whatisatemporarysolutionforadamagedcarbody?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
CanICultureBombfaraway?
Whydosocksstink?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Howtodesignstrategyandalgorithmforgoldboxgame
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 155/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Goldboxproblem(Approach)
Therearengoldboxesplacedinarow,eachhavingdifferentnumberofgoldcoins.2playersplayagame,wherethemotiveistocollectthemaximum
numberofgoldcoins.Eachplayercanseehowmanycoinsarepresentineachbox,butcangetaboxfromeitherendonly,onhisturn.Designastrategy
suchthatPlayer1wins(Assumingbothplayersplaysmartly)
Thisproblemwasaskedinanamazoninterview.Itriedthisapproach:
#include<stdio.h>
intmax(inta,intb){
returna>b?a:b;
}
intmaxCoins(intarr[],inti,intj,intturn){
if(i==j){
if(turn==1)returnarr[i];
elsereturn0;
}
if(turn){
upvote2 returnmax(arr[i]+maxCoins(arr,i+1,j,0),arr[j]+maxCoins(arr,i,j1,0));
downvote }else{
favorite if(arr[i]>arr[j])
returnmaxCoins(arr,i+1,j,1);
else
returnmaxCoins(arr,i,j1,1);
}
}
intmain(){
intarr[10]={6,7,4,1,10,5,4,9,20,8};//{2,3,4,5,6,7,8,9,10,11};
printf("%d\n",maxCoins(arr,0,9,1));
}
ButIthinkthisisnotright,asplayer2alsoplayssmartly.KindlyhelpwithwhatIammissing.
calgorithmdynamicprogramminggametheory
editedMar22'14at14:22 askedMar22'14at14:16
share|improvethisquestion
YuHao SanjayVerma
64.7k1485142 98113
1 SameproblemUnderstandingsolutiontofindingoptimalstrategyforgameinvolvingpickingpotsofgoldDukelingMar22'14at14:37
addacomment|
1Answer
activeoldestvotes
Igottothesolution,justwasclose.HereiswhatImissed:
"Theopponentintendstochoosethecoinwhichleavestheuserwithminimumvalue."
Hereisupdatedsolution:
#include<stdio.h>
intmax(inta,intb){
returna>b?a:b;
}
intmin(inta,intb){
returna<b?a:b;
}
intmaxCoins(intarr[],inti,intj,intturn){
inta,b;
if(i==j){
if(turn==1)returnarr[i];
elsereturn0;
}
if(turn){
upvote0downvoteaccepted
a=arr[i]+maxCoins(arr,i+1,j,0);
b=arr[j]+maxCoins(arr,i,j1,0);
returnmax(a,b);
}else{
returnmin(maxCoins(arr,i+1,j,1),maxCoins(arr,i,j1,1));
}
}
intmain(){
intarr[4]={8,15,3,7};//{6,7,4,1,10,5,4,9,20,8};//{2,3,4,5,6,7,8,9,10,11};
printf("%d\n",maxCoins(arr,0,3,1));
}
Thislinkdiscussesthestrategy:http://www.geeksforgeeks.org/dynamicprogrammingset31optimalstrategyforagame/
answeredMar22'14at14:25
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 156/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
editedMar22'14at15:40
share|improvethisanswer
SanjayVerma
98113
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedcalgorithmdynamicprogramming
gametheoryoraskyourownquestion.
asked 1yearago
viewed 360times
active 1yearago
Lookingforajob?
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareDevelopmentEngineerUI
AudienceScience
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 157/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Pune,India
htmlcss
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Linked
3
Understandingsolutiontofindingoptimalstrategyforgameinvolvingpickingpotsofgold
Related
6
Tryingtobuildalgorithmforoptimaltowerplacementinagame
7
Howtowinthisgame?
2
gametheoryalgorithms:howtoproceed
1
Algorithmforgamewithcoins
1
OptimalStrategyForCoinGame
0
StrategyforNimlikeGames
3
Understandingsolutiontofindingoptimalstrategyforgameinvolvingpickingpotsofgold
1252
Whatistheoptimalalgorithmforthegame2048?
3
Howtochooseawinningstrategyforthis24playergame,algorithmonly
2
optimalalgorithmstrategyfora2playergame
HotNetworkQuestions
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Antiferromagneticordering
DoesaUSB3.0connectionrequireaUSB3.0cord?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Whatisatemporarysolutionforadamagedcarbody?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
WhydosomepeoplerefertoLinuxasGNU/Linux?
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
Whycan'tanonabeliangroupbe75%abelian?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Howtodecidewhetherastoryisworthwriting?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
CanICultureBombfaraway?
Drawarrowinamindmap
Howtogetearlyentryintomystictheurge?
FiveAnglesinaStar
Howtoprotectaspaceelevatoragainstterrorism
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
RollmyD&Dcharacter'sabilityscores
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
SixMusicalFriends
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Matchsubstringwithinastringwithtoleranceof1charactermismatch
IwasgoingthroughsomeAmazoninterviewquestionsonCareerCup.com,andIcameacrossthisinterestingquestionwhichIhaven'tbeenabletofigure
outhowtodo.Ihavebeenthinkingonthissince2days.EitherIamtakingawayoffapproach,oritsagenuinelyhardfunctiontowrite.
Questionisasfollows:
WriteafunctioninCthatcanfindifastringisasubstringofanother.Notethatamismatchofonecharactershouldbeignored.
Amismatchcanbeanextracharacter:dogmatchesxxxdoogyyyy
Amismatchcanbeamissingcharacter:dogmatchesxxxdgyyyy
Amismatchcanbeadifferentcharacter:dogmatchesxxxdigyyyy
Thereturnvaluewasn'tmentionedinthequestion,soIassumethesignatureofthefunctioncanbesomethinglikethis:
char*MatchWithTolerance(constchar*str,constchar*substr);
upvote4 Ifthereisamatchwiththegivenrules,returnthepointertothebeginningofmatchedsubstringwithinthestring.Elsereturnnull.
downvote
favorite Bonus
8
Ifsomeonecanalsofigureoutagenericwayofmakingthetolerancetoninsteadof1,thenthatwouldbejustbrilliant.Inthatcasethesignaturewould
be:
char*MatchWithTolerance(constchar*str,constchar*substr,unsignedinttolerance=1);
Thankstoallthosewhowouldattemptthisandsharetheirsuccessfulsolution.
cstringamazon
askedJul24'10at17:52
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 159/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
share|improvethisquestion
bits
2,95462745
doesdogalsomatchxxxdogyyy?IVladJul24'10at17:58
YesitdoesMatch.bitsJul24'10at18:08
(removedasetofcommentsthatwereunrelatedtothequestion)MarcGravellJul25'10at15:18
addacomment|
5Answers
activeoldestvotes
Thisseemstowork,letmeknowifyoufindanyerrorsandI'lltrytofixthem:
intfindHelper(constchar*str,constchar*substr,intmustMatch=0)
{
if(*substr=='\0')
return1;
if(*str=='\0')
return0;
if(*str==*substr)
returnfindHelper(str+1,substr+1,mustMatch);
else
{
if(mustMatch)
return0;
if(*(str+1)==*substr)
returnfindHelper(str+1,substr,1);
elseif(*str==*(substr+1))
returnfindHelper(str,substr+1,1);
elseif(*(str+1)==*(substr+1))
returnfindHelper(str+1,substr+1,1);
elseif(*(substr+1)=='\0')
return1;
else
upvote4down return0;
voteaccepted }
}
intfind(constchar*str,constchar*substr)
{
intok=0;
while(*str!='\0')
ok|=findHelper(str++,substr,0);
returnok;
}
intmain()
{
printf("%d\n",find("xxxdoogyyyy","dog"));
printf("%d\n",find("xxxdgyyyy","dog"));
printf("%d\n",find("xxxdigyyyy","dog"));
}
Basically,Imakesureonlyonecharactercandiffer,andrunthefunctionthatdoesthisforeverysuffixofthehaystack.
answeredJul24'10at18:52
share|improvethisanswer
IVlad
26.5k844121
+1!!Thatworksbrilliantly.Iamsurewecanmakethisreturnpointertothebeginningofthematchedstring.AndThiscanbemadegenerictoo.
Thanksalot!IfIcomeacrossanyunmatchingscenarios,Iwillreplyback.bitsJul24'10at19:17
addacomment|
Didyoufindthisquestioninteresting?Tryournewsletter
Signupforournewsletterandgetourtopnewquestionsdeliveredtoyourinbox(seeanexample).
emailaddress Subscribe
Success!Pleaseclickthelinkintheconfirmationemailtoactivateyour Subscribed!
ThisisrelatedtoaclassicalproblemofIT,referredtoas
subscription.
Levenshteindistance.SeeWikibooksforabunchof
up implementationsindifferentlanguages.
vote
4 answeredJul24'10at19:47
down
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 160/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
vote
share|improvethisanswer
Pumbaa80
40.6k96092
+1fornotwritingcodethat'sclearlygoingtobeplagiarized
andsubmitashisown.StefanKendallJul24'10at20:14
No,thishasnothingtodowiththelevenshteindistanceas
farasIcansee.Thisasksforsubstringmatchingwhere1
characterisallowednottomatch.Howdoyouproposewe
usethelevenshteindistanceforthis?IVladJul24'10at
20:31
Ishouldhavebeenalittleclearer.TheLevenshtein
implementationsdonotsolvetheoriginalproblem.But,
lookingatthealgorithmyou'llrealizethatonlyaslight
changeisneededtoachievefuzzysubstringmatching.
Again,theinternetshasanimplementationready:
ginstrom.com/scribbles/2007/12/01/Pumbaa80Jul24
'10at20:54
@StefanWhyareyoupickingonmeineverydamn
comment?Iamnotsubmittingthiscodeanywhere!You
didn'tevenreadmyquestionproperly.Iwrote,thatIwas
goingthroughinterviewquestionsandfoundthis
interesting.AndItriedtosolveit,butfailedsomehow.Why
doyouthinkthatIamplanningtoplagiarizethis?This
1
meansyoudon'tevenunderstandhowinterviewsinreal
worlstakeplace.Nocompanywouldaskyoutowritethat
bigafunctiononphone.Theywillonlyaskyoutowrite
suchacodeonface2faceinterview,whereyouclearly
cannotcopypastefromStackOverflow.bitsJul24'10at
23:47
@PumbaaThanksforyourinputs.Iappreciateit.+1bits
Jul24'10at23:57
|show3morecomments
Thisisslightlydifferentthantheearliersolution,butIwasintriguedbytheproblemandwantedtogiveitashot.Obviouslyoptimizeifdesired,Ijust
wantedasolution.
char*match(char*str,char*substr,inttolerance)
{
if(!*substr)returnstr;
if(!*str)returnNULL;
while(*str)
{
char*str_p;
char*substr_p;
char*matches_missing;
char*matches_mismatched;
str_p=str;
substr_p=substr;
while(*str_p&&*substr_p&&*str_p==*substr_p)
{
str_p++;
substr_p++;
}
if(!*substr_p)returnstr;
upvote2down if(!tolerance)
vote {
str++;
continue;
}
if(strlen(substr_p)<=tolerance)returnstr;
/*missedduetoamissingletter*/
matches_missing=match(str_p,substr_p+1,tolerance1);
if(matches_missing==str_p)returnstr;
/*missedduetoamismatchofletters*/
matches_mismatched=match(str_p+1,substr_p+1,tolerance1);
if(matches_mismatched==str_p+1)returnstr;
str++;
}
returnNULL;
}
answeredJul24'10at19:28
editedJul24'10at19:36
share|improvethisanswer
BrandonHorsley
4,3511223
+1foractuallyattemptingtheproblem.IVladJul24'10at20:27
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 161/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Ihaven'ttriedoutyoursolutionyet,butNonrecursiveapproachissupposedlyverydifficult.+1forAttempting.bitsJul24'10at23:20
addacomment|
Istheproblemtodothisefficiently?
Thenaivesolutionistoloopovereverysubstringofsizesubstrinstr,fromlefttoright,andreturntrueifthecurrentsubstringifonlyoneofthe
charactersisdifferentinacomparison.
Letn=sizeofstrLetm=sizeofsubstr
upvote0down
vote ThereareO(n)substringsinstr,andthematchingsteptakestimeO(m).Ergo,thenaivesolutionrunsintimeO(n*m)
answeredJul24'10at18:24
share|improvethisanswer
StefanKendall
31.5k38143301
Iguess,efficiencywouldn'tbetheprimarythingtheyaretestinginthequestion.StillIwouldsay,letstrytodoitinO(n*m).bitsJul24'10at
18:28
ThatsolutionISO(n*m)StefanKendallJul24'10at18:52
1ThisapproachisnotevenclosetotheactualsolutionpostedbyIVlad.bitsJul24'10at23:40
addacomment|
Witharbitaryno.oftolerancelevels.
WorkedforallthetestcasesIcouldthinkof.Looselybasedon|/|ad'ssolution.
#include<stdio.h>
#include<string.h>
report(intx,char*str,char*sstr,int[]t){
if(x)
printf("%sisasubstringof%sforatolerance[%d]\n",sstr,str[i],t[i]);
else
printf("%sisNOTasubstringof%sforatolerance[%d]\n",sstr,str[i],t[i]);
}
intfind_with_tolerance(char*str,char*sstr,inttol){
if((*sstr)=='\0')//endofsubstring,andmatch
return1;
if((*str)=='\0')//endofstring
if(tol>=strlen(sstr))//buttolsavestheday
return1;
else//there'snothingeventhepoortolcando
return0;
if(*sstr==*str){//currentcharmatch,smooth
returnfind_with_tolerance(str+1,sstr+1,tol);
}else{
if(tol<=0)//that'sit.nomorepatience
return0;
for(inti=1;i<=tol;i++){
if(*(str+i)==*sstr)//insertioanofaforeigncharacter
returnfind_with_tolerance(str+i+1,sstr+1,toli);
if(*str==*(sstr+i))//dealwithdletion
upvote0downvote returnfind_with_tolerance(str+1,sstr+i+1,toli);
if(*(str+i)==*(sstr+i))//dealwithriplacement
returnfind_with_tolerance(str+i+1,sstr+i+1,toli);
if(*(sstr+i)=='\0')//substrends,thankstotol&thisloop
return1;
}
return0;//whenallfails
}
}
intfind(char*str,char*sstr,inttol){
intw=0;
while(*str!='\0')
w|=find_with_tolerance(str++,sstr,tol);
return(w)?1:0;
}
intmain(){
constintn=3;//nooftestcases
char*sstr="dog";//thesubstr
char*str[n]={"doox",//thosecases
"xxxxxd",
"xxdogxx"};
intt[]={1,1,0};//tolerancelevelsforthosecases
for(inti=0;i<n;i++){
report(find(*(str+i),sstr,t[i]),*(str+i),sstr,t[i]);
}
return0;
}
answeredJul27'10at16:41
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 162/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
editedApr7'14at12:35
share|improvethisanswer
ignoramous
5917
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedcstringamazonoraskyourown
question.
asked 4yearsago
viewed 3770times
active 1yearago
Lookingforajob?
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Geek(s)
myglamm.com
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 163/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Mumbai,India/relocation
javaios
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Linked
7
Stringsimilarityalgorithms?
Related
660
startsWith()andendsWith()functionsinPHP
5
removealloccurencesofacharacterinCstringExampleneeded
7
Howtofindapositionofasubstringwithinastringwithfuzzymatch
1
Reversinganunboundedstringwithoutcheckingfornullcharacter
0
Howtohashstringsinpythontomatchwithin1character?
0
Howtocomparestringspartly(toreturnthenumberofcharactersthatwerematched)?
10
Findlengthofsmallestwindowthatcontainsallthecharactersofastringinanotherstring
1
Afunctiontoremovecharactersinastringfromanotherstring
3
Manipulatingstringsofmultibytecharacters
1
HowtoreplaceacharacterinastringinC?
HotNetworkQuestions
Doblockingcreatureshealbacktofullbetweenphases?
Isthereawordforpeopleincapableofthinking?
MementoVivereMomentumMori
Howtoprotectaspaceelevatoragainstterrorism
Whyshouldakeybemadeexplicit?
40Numbersin9Bytes
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
Patchingabinarywithdd
Antiferromagneticordering
HowdoIfacilitateafirsttimeAgileretrospective?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
ALN*NTicTacToeGame
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Clientwantsfontaslogo
PythonLabelExpression?ArcGIS10.3.1
Alarmclockprinting
NineTallMenAreStandingTall
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
Howtodrawsequenceofshapeswitharrowsandtext
Whatistheoriginofthepowericon?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Derivativeofadefiniteintegralissue
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
modifieddepthfirsttraversaloftree
Igotthisquestioninaninterviewwithamazon.Iwasaskedtoperformadepthfirsttraversalofatree,withoutusingrecursionorstack.Icouldusea
parentpointerforeachnode,asapartofthestructure,butnothingelseotherthanthat.(forex,a"visited"variable"oranything).Pleasesuggestmean
algorithm.
upvote8
downvote cdatastructures
favorite askedAug8'10at18:02
2
editedAug8'10at18:12
share|improvethisquestion
Aryabhatta
wordwiz
7017
addacomment|
5Answers
activeoldestvotes
Theparentpointerisactuallyallyouneed.Thetrickistoconsumethetreeasyoutraverseit.
Uglypseudocode:
cur=treeroot;
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 165/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
while(1){//Gettobottomoftree
if(cur.hasLeft){
cur=left;
}elseif(cur.hasRight){
cur=right;
}else{
break;
}
//curisnowthebottomnode
while(1){
doStuff(cur);//outputcur,performoponit,whatever
if(!cur.hasParent){//Donewithtraversal
break;
}
prev=cur;//Sowecantellwhichwaywecameuptotheparent.
cur=cur.parent;
if(cur.hasLeft&&cur.left==prev){//Deleteleftchild;it'sdone
cur.hasLeft=false;
}elseif(cur.hasRight&&cur.right==prev){//Deleterightchild;it'sdone
//Note:"else"notdesirableifanodeshouldnotbeabletohavethesamechildintwospots
cur.hasRight=false;
upvote5 }
downvote if(cur.hasLeft){//Goallthewaytothebottomoftheleftchild
accepted cur=cur.left;
while(1){
if(cur.hasLeft){
cur=cur.left;
}elseif(cur.hasRight){
cur=cur.right;
}else{
break;
}
}
}elseif(cur.hasRight){//Goallthewaytothebottomoftherightchild
cur=cur.right;
while(1){
if(cur.hasLeft){
cur=cur.left;
}elseif(cur.hasRight){
cur=cur.right;
}else{
break;
}
}
}
}
answeredAug8'10at18:16
editedAug8'10at18:22
share|improvethisanswer
Borealid
40.4k66293
Wheredoesthequestionsayitisabinarytree?OrthatyoucandestroythetreeorthatthereareflagslikehasRight/hasLeft?AryabhattaAug8'10at
18:58
@Moron:thissolutionextendsfinetoarbitrarynumbersofchildren,solongasthereisadefinedtraversalorder.Thequestiondoesn'tsayyoucan
destroythetree.Italsodoesn'tsayyoucan't.hasRight/hasLeftisshorthandfor.left==NULL,orwhatever.Ifyoudon'thaveawaytotellifanodehas
aleftchild,youcannottraversethetreesafely.BorealidAug8'10at19:14
Frankly,ifsomeonegaveasolutiontotraversethetreewhichdestroysit,Iwouldgivethemahardlookingover)Ofcourse,Iprobablywouldn'tbe
askingsuchastupidquestioninthefirstplace.AryabhattaAug8'10at20:16
thanks.thiscodeseemstobeworkingfine.andtheinterviewerdidmentionthaticouldassumethetreetobebinary.sorryfornotbeingspecificabout
thatpart.nyes,ididgivetheinterviewerasternlook,sincehekeptmodifyingthequestiontillheendedupwidthisnicudntansweranymore.istill
wannaknwthough,ificouldperformthis,withouthavingtodestroythetree.wordwizAug9'10at7:49
Inmyopinion,destructionofthetreecountsasthe"oranything"inforex,a"visited"variable"oranything.R..Aug11'10at7:54
addacomment|
up Fora'hacky'solutionyoucanusethefactthatpointersareusually4bytealigned(i.e,lasttwobitsare0)andusethosetwobitsasyourvisitedflag.
vote1
down editedAug8'10at18:13 answeredAug8'10at18:07
vote share|improvethisanswer Aryabhatta
Clever,butifsomeonepresentedthatinaninterviewI'dgivethemaprettyhardlookingover.BorealidAug8'10at18:20
@Bore:Iwouldgivethesamelooktosomeoneaskingsuchasillyquestion)AryabhattaAug8'10at18:44
@moron:inevahadanideaicoulduseapointerthatway.couldyoupleaseelaboratehowicanimplementthis?wordwizAug9'10at7:51
@word:Basicallyforanode,sayyouusedtheparentpointertostorethevisitedflag,thenyoucoulddosomethinglike:intvisited=(node>parent)
&0x01orsetvisitedflaglikenode>parent=node>parent|0x01.HereyouareusingthelastbitasthevisitedflagandsettingitusingbitwiseORand
1
retreivingitusingbitwiseAND.Iwouldnotrecommendthisinproductioncodethough,onlyinresponsetosomesmartalecinterviewer.AryabhattaAug
9'10at14:34
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 166/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Hereismypropositionforabinarytree.ThelanguageisC#.It'saprivatemethodofabinarTreeclassthatholdsints
privateNodeDFS(intvalue)
{
Nodecurrent=this.root;
if(current.data==value)returncurrent;
while(true)
{
//godownleftasfaraspossible
while(current.leftChild!=null)
{
current=current.leftChild;
if(current.data==value)returncurrent;
}
//leftChildisnull,butmaybeIcangorightfromhere
while(current.leftChild==null&¤t.rightChild!=null)
{
current=current.rightChild;
if(current.data==value)returncurrent;
}
if(current.leftChild==null&¤t.rightChild==null)
{
//Ok,Igottoaleaf.NowIhavetogetbacktothelast"crossroads"
//Iwentdownleftfrom,buttherewasalsodownrightoption
while(current.parent!=null&&
(current==current.parent.rightChild||
current.parent.rightChild==null))
{
current=current.parent;
}
if(current.parent==null)returnnull;
//OkIfI'mhere,thatmeansIfoundthecrossroadsmentionedbefore
//I'llgodownrightonceandthenIshouldtrydownleftagain
current=current.parent.rightChild;
if(current.data==value)returncurrent;
}
}
}
Ifit'snotabinarytree,thenthingsgetmorecomplicatedofcourse,butthelogicissimilar.Godowntotheleaftakingthefirstpossiblechildateachlevel.Once
youreachaleafyougoup.Everytimeyoulookupataparentyoucheckifthechildyouaresupposedtocomefromwasthelastinparent'slist.Ifnot,youtake
nextchildandgodownagain.Ifyes,yougoupandcheckthefollowingparent.Ifyougetbacktotherootyousearchedthewholetree.
EDIT
Oksearchandtraversalsaredistinctthings,mybad.Hereissomemodifiedcodefortraversals
preorder:
publicvoidpreorderTraversal()
{
Nodecurrent=this.root;
Console.WriteLine("item:{0}",current.data);
while(true)
{
while(current.leftChild!=null)
{
current=current.leftChild;
Console.WriteLine("item:{0}",current.data);
}
while(current.leftChild==null&¤t.rightChild!=null)
{
current=current.rightChild;
Console.WriteLine("item:{0}",current.data);
}
if(current.leftChild==null&¤t.rightChild==null)
{
while(current.parent!=null&&
(current==current.parent.rightChild||
current.parent.rightChild==null))
{
current=current.parent;
}
if(current.parent==null)
{
return;
}
else
{
current=current.parent.rightChild;
Console.WriteLine("item:{0}",current.data);
}
}
up }
}
vote1
down inorder:
vote
publicvoidinorderTraversal()
{
Nodecurrent=this.root;
while(true)
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 167/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
{
while(current.leftChild!=null)
{
current=current.leftChild;
}
Console.WriteLine("item:{0}",current.data);
while(current.leftChild==null&¤t.rightChild!=null)
{
current=current.rightChild;
Console.WriteLine("item:{0}",current.data);
}
if(current.leftChild==null&¤t.rightChild==null)
{
while(current.parent!=null&&
(current==current.parent.rightChild||
current.parent.rightChild==null))
{
current=current.parent;
if(current.rightChild==null)
{
Console.WriteLine("item:{0}",current.data);
}
}
if(current.parent==null)
{
return;
}
else
{
Console.WriteLine("item:{0}",current.parent.data);
current=current.parent.rightChild;
}
}
}
}
postorder:
publicvoidpostorderTraversal()
{
Nodecurrent=this.root;
while(true)
{
while(true)
{
if(current.leftChild!=null)
{
current=current.leftChild;
}
elseif(current.rightChild!=null)
{
current=current.rightChild;
}
else
{
break;
}
}
while(current.parent!=null&&
(current==current.parent.rightChild||
current.parent.rightChild==null))
{
Console.WriteLine("item:{0}",current.data);
current=current.parent;
}
Console.WriteLine("item:{0}",current.data);
if(current.parent==null)
{
return;
}
else
{
current=current.parent.rightChild;
}
}
}
answeredAug8'10at19:03
editedAug9'10at17:32
share|improvethisanswer
MaciejHehl
5,24011021
itisabinarytree,butitsnotasearchingopeartion.iwasaskedtotraversethetree.icouldntreallyget,whatthis"value"thingisallabout.wordwizAug
9'10at7:55
@wordwizOkmybad.Ireaddepthfirstandthattriggeredsearchinmyheadinstantly.FortraversalI'dratherexpectpre,postorinorder.Changingmy
codetogetpreordertraversalistrivial.Justreplacechecksifvaluewasfoundwithsomeactionperformedoneveryvisit.Inorderandpostordertraversals
requiremorechanges.MaciejHehlAug9'10at16:06
addacomment|
Ifyouhaveaparentpointer,thenyoucanunwindupthetreewithoutastack.Theonlyotherproblemduringunwindis"doIneedtovisittheother
child(ren)?"Thiscanbeansweredsimplybycomparingpointervaluestoworkoutifyou'vejustreturnedfromtheleftchildortherightchild(orgeneraliseto
Nchildren).
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 168/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
EDIT
Pseudocode(untested):
p_last=NULL;
p=p_head;
descend=true;
while(NULL!=p)
{
p_tmp=p;
if(descend)
{
//...Nodeprocessinghere...
if(0==p>num_children)
{
//Nochildren,sounwind
p=p_parent;
descend=false;
}
else
{
//Visitfirstchild
upvote0 p=p>child[0];
}
down }
vote else
{
//Findthechildwejustvisited
for(i=0;i<p>num_children;i++)
{
if(p_last==p>child[i])
{
break;
}
}
if(i==num_children1)
{
//Processedlastchild,sounwind
p=p_parent;
}
else
{
//Visitnextchild
p=p>p_child[i+1];
descend=true;
}
}
p_last=p_tmp;
}
answeredAug8'10at18:07
editedAug8'10at19:29
share|improvethisanswer
OliverCharlesworth
163k15298460
Showsomecode?I'mnotsurethisactuallyworks,becausevisitingtherightchildrequiresstorageoutsideofthetree.BorealidAug8'10at18:19
Can'tbebotheredtothinkofthecode!Everytimeyoucomebackuptoanode,comparetheaddressofthechildyoujustcamefromwiththepointerfor
therightchild.Ifthey'reequal,thencontinuetounwind,otherwisevisittherightchild.SonotsurewhatyoumeanOliverCharlesworthAug8'10at
18:31
Thiscodedoesn'twork.Somenodeswon'tgetvisitedifthetreestructurecontainssomenodeswhichonlyhaverightchildreninsomeplaces.Also,you
don'tmarkwhereanodeishandledimportant,sinceyourcodeisalmostatopdowntraversal.BorealidAug8'10at18:55
Thequestionjustsaystree.Whyareyouassumingbinarytree?AryabhattaAug8'10at18:59
@Borealid:fairpoint,butasIsaid,"untested!".Idon'tthinkitbreakstheprinciple(butI'lltrytofixit).OliverCharlesworthAug8'10at19:02
|show10morecomments
ThisshowshowI'ddoitinC.Itdemonstratesbothpreorderandpostordertraversal,andisgeneralisedfor0..Nchildrenofeachnode.
structnode{
structnode*parent;
structnode*child[NCHILD];
};
voiddfs(structnode*head,void(*visit_preorder)(structnode*n),void(*visit_postorder)(structnode*n))
{
structnode*current=head;
structnode*prev=head;
while(current)
{
inti;
/*preordertraversal*/
if(prev==current>parent)
visit_preorder(current);
/*Findfirstchildtovisit*/
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 169/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
for(i=NCHILD;i>0;i)
{
if(prev==current>child[i1])
break;
upvote0downvote }
while(i<NCHILD&¤t>child[i]==NULL)
i++;
prev=current;
if(i<NCHILD)
{
/*Descendtocurrent>child[i]*/
current=current>child[i];
}
else
{
/*Postordertraversal*/
visit_postorder(current);
/*Ascendbacktoparent*/
current=current>parent;
}
}
}
answeredAug9'10at1:49
share|improvethisanswer
caf
131k10152286
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 170/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Nottheansweryou'relookingfor?Browseotherquestionstaggedcdatastructuresoraskyourown
question.
asked 4yearsago
viewed 2164times
active 4yearsago
Lookingforajob?
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
iOSDeveloper
hedgehoglab
Hyderabad,India
iosobjectivec
Linked
0
Traversingarbitrarilylargebinarytreeinorder
1
Do4bytealignedpointersuseanypadding?
Related
11
TraversetreewithoutrecursionandstackinC
6
Levelorderinsertionintoabinarytree?
2
UnderstandingWikipediacodeforagenericdepthfirsttreesearch?
0
Depthfirstiterativedeepeningalgorithmtoprintabinarytreebreadthfirst
1
Traversingageneraltreerecursivelyindepthfirstc
1
DataStructureRepresentationofSpecificTreeforDepthFirstSearchinPython
0
Recursivebreadthfirsttraversalofbinarytree
1
Veryspecifictreetraversalmethod
0
Traversalintree/linkedliststructure
0
Binarytreemirror()howdoesthiswork?
HotNetworkQuestions
Troublewithterminatinga<apex:pageBlockSection>
40Numbersin9Bytes
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 171/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Drawarrowinamindmap
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Whyshouldakeybemadeexplicit?
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
Canmathbesubjective?
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
Doblockingcreatureshealbacktofullbetweenphases?
PythonLabelExpression?ArcGIS10.3.1
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Shouldmy(sequential)collectionstartatindex0orindex1?
Jumpingcarwithtoomanyamps?
Whydosocksstink?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Whatwereshoesolesmadefrominpreviousages?
NineTallMenAreStandingTall
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Whatisatemporarysolutionforadamagedcarbody?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Whyadding"incolour"whenreferringto"WizardofOz"?
DoesCIDRreally"doaway"withIPaddressclasses?
RollmyD&Dcharacter'sabilityscores
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 172/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
wanttoknowaboutinformativewebsiteormaterialonALGORITHMSrelated
topics[closed]
Withtheproblemandsuggestedsolution?suchas:forvarious/graphnetworkbasedproblems,comparisonadvancedsortingalgorithm,dynamic
algorithmforvariousproblemsandoptimisedbstreesandtheirimplementationforsolvingvariousproblems..
upvote1down calgorithmsearchdictionarypseudocode
votefavorite editedNov30'11at11:14 askedNov30'11at10:36
share|improvethisquestion
niko userKP
3,843154784 21
closedasnotarealquestionbyJoachimPileborg,dmckee,OliverCharlesworth,AlexeyFrunze,Jakub
KoneckiNov30'11at14:46
It'sdifficulttotellwhatisbeingaskedhere.Thisquestionisambiguous,vague,incomplete,overlybroad,orrhetoricalandcannotbereasonablyansweredinitscurrent
form.Forhelpclarifyingthisquestionsothatitcanbereopened,visitthehelpcenter.Ifthisquestioncanberewordedtofittherulesinthehelpcenter,pleaseeditthe
question.
HaveyoutriedsearchingWikipediaforanyalgorithmyouarecuriousabout?Theyareusuallyverygood,ifsometimesalittletheoretical.
JoachimPileborgNov30'11at10:40
searchedsomeofthembutnotthatapproriateintermsofprob.&solutionuserKPNov30'11at10:45
SeethisSOquestionforbooks:stackoverflow.com/questions/302270/.ProjectEuler&Topcoderaresomeofthepopularwebsitestosharpen
yourskillsanother.anon.cowardNov30'11at11:02
addacomment|
3Answers
activeoldestvotes
CheckouttheAlgorithmDesignManualbyStevenSkiena.Thefirsthalfisatutorialwith"warstories"interspersedthroughout(reallifeproblemsand
solutions),whilethesecondhalfisacomprehensivereferenceofvariousproblems,knownalgorithms,andtheirimplementations.
It'shelpfulwhetheryou'retryingtoprepareforjobinterviews,learnalgorithms,orjustasareference.
OnAmazon:http://www.amazon.com/AlgorithmDesignManualSteveSkiena/dp/0387948600
upvote3
downvote There'sanonlinePDFversion.
answeredNov30'11at10:41
editedNov30'11at10:48
share|improvethisanswer
DavidHu
2,052921
addacomment|
AlsochecktheTopCodercompetitions.Inadditiontolettingyouparticipateandsolvethepuzzlestheypropose,youcanalsohavealookatotherpeople's
solutions.It'salsoafunwaytogetinvolvedinthecommunity.
upvote0 answeredNov30'11at10:45
downvote
share|improvethisanswer
Miquel
8,14012358
addacomment|
Thiscourseonalgorithmsofadunicanalsohelp
answeredNov30'11at11:22
upvote0downvote
share|improvethisanswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 173/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Raza
658523
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedcalgorithmsearchdictionary
pseudocodeoraskyourownquestion.
asked 3yearsago
viewed 102times
active 3yearsago
Lookingforajob?
UIDeveloperataprofitableSaaSstartup
Recruiterbox
Bengaluru,India/relocation
htmlcss
InfrastructureEngineer
KCG
JerseyCity,NJ/relocation
shelllinux
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Related
9
Whatissearch.twitter.com'strendingtopicsalgorithm?
4
WebsiteSearchAlgorithm
1
Doyouknowofanysearchalgorithmsforsearchingthroughsourcecode?
240
Fastestsortoffixedlength6intarray
3
QuestionaboutHeapSortalgorithm
615
Ukkonen'ssuffixtreealgorithminplainEnglish?
1
quizaboutbitrelatedtopics
0
MaterialandInformationtoimprovealgorithmicknowledge
3
Algorithmforadiversifiedsort
1
Knapsacksavetimeandmemory
HotNetworkQuestions
DoesaUSB3.0connectionrequireaUSB3.0cord?
40Numbersin9Bytes
Antiferromagneticordering
CanIflywithagoldbar?
CanICultureBombfaraway?
RollmyD&Dcharacter'sabilityscores
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
zero,zerosorzeroes?
Alarmclockprinting
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Whatwereshoesolesmadefrominpreviousages?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
FindingoutifawordisanAnagramofanother
Multiplypurefunctionwithscalar
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 174/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Needhelprecreatingcrazycolors/materialfromexample
HowcouldaresurrectedJesusproveheisJesus?
Clientwantsfontaslogo
Howtodrawsequenceofshapeswitharrowsandtext
Nicelytypesettingverbatimtext
morehotquestions
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
AnybodyKnowstheLogicToFindOutaNumberisPerfectSquareornot?
[duplicate]
PossibleDuplicate:
Fastestwaytodetermineifaninteger'ssquarerootisaninteger
DoesAnybodyKnowstheLogicToFindOutaNumberisPerfectSquareornot?(OtherthanNewtonsMethodorSyntheticDivisionMethod)
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 175/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ForEg:4,16,36,64arePerfectSquares.
Iwillbegivingtheinputas441,logicshouldsaywhetheritsaPerfectSquareornot.
upvote2downvote
favorite ItwasaquestionaskedinAmazonInterview.
5
Iwouldliketodoitwithoutanybuiltinfunctions
c#
askedJun30'11at12:36
share|improvethisquestion
Dotnet
4,3631371154
markedasduplicatebyDanielHilgarth,RobertHarveyJun30'11at16:53
Thisquestionhasbeenaskedbeforeandalreadyhasananswer.Ifthoseanswersdonotfullyaddressyourquestion,pleaseaskanewquestion.
4 What'sagoodalgorithmtodetermineifaninputisaperfectsquare?PaoloMorettiJun30'11at12:40
Ifthetrickwereontheinputitselfthen,Becauseof441hasoneintherightthennowayitcouldbeaPerfectSquares.JalalAldeenSaa'd
1
Jun30'11at12:40
@Jalal:What,like81isn't?:)regularfryJun30'11at12:51
@Jalal441=21^2.Atleastcheck...Besides,takeanynumberthatendswith1,eg,52941,multiplyitbyitself,andyougetasquarethat
endswith1.KobiJun30'11at12:52
@regularfry:@Kobi:Ithoughtthatwasjustfor2tothepowern.JalalAldeenSaa'dJun30'11at12:54
addacomment|
3Answers
activeoldestvotes
NoMath.Sqrt,notevenmultiplication:
staticboolIsSquare(intn)
{
inti=1;
for(;;)
{
if(n<0)
returnfalse;
if(n==0)
upvote7downvoteaccepted returntrue;
n=i;
i+=2;
}
}
answeredJun30'11at12:58
share|improvethisanswer
Henrik
18k42471
Nowtryitwithoutadditionormultiplication:)KibbeeJun30'11at13:15
1 Havetosay,Ireallylikethisalgorithm.KibbeeJun30'11at13:18
1 Eventhoughfromaquickbenchmark,itseemsthatusingmultiplicationisfaster.KibbeeJun30'11at13:26
Amazingalgorithm,hatsoffdude.iregretwhyihatemaths:)AnoopJul21'11at5:48
IwishIcouldofferyoubountyofMillions..reallyappreciated...PilotJan29'14at13:11
addacomment|
ThefirstquestionIwouldasktheintervieweris,"Whataretheproblemconstraints?"Thatis,howbigcantheinputnumberbe?Ifit'ssmallenough,then
youcouldjustprecalculatealltheperfectsqauresandstoretheminadictionary:
IDictionary<long,bool>squares=newDictionary<long,bool>;
for(longi=1;i*i<=MAX_NUM;++i){
squares[i*i]=true;
}
upvote3
downvote Then,tofindoutifanumberxisaperfectsquare,youjustchecksquares[x]toseeifit'strue.
answeredJun30'11at12:42
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 176/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
share|improvethisanswer
dcp
29.6k778109
addacomment|
Somethingalongthelinesofthiswouldwork.
publicBooleanIsSquare(doubleinput)
{
doubleroot,product;
BooleanisSquare,isGTInput;
root=1;
product=0;
isSquare=false;
isGTInput=false;
while(!isSquare&&!isGTInput)
{
product=root*root;
upvote0down if(product==input)
vote isSquare=true;
elseif(product>input)
isGTInput=true;
root+=1;
}
returnisSquare;
answeredJun30'11at12:46
editedJun30'11at13:10
share|improvethisanswer
Kibbee
39.9k24110155
willthiscomeunderasperiaskedDotnetJun30'11at12:55
Sorry,Idon'tunderstandwhatyou'reasking.KibbeeJun30'11at13:00
Asyouusedroot*rootwillthiscomeunderasperiaskedDotnetJun30'11at13:03
Idon'tthinkmultiplicationwouldcountasa"builtinfunction".Ifyoucan'tusemultiplicationoperators,it'sprobablyimpossible.KibbeeJun
30'11at13:08
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedc#oraskyourownquestion.
asked 4yearsago
viewed 3630times
active 4yearsago
Lookingforajob?
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
SoftwareEngineer/Sr.SoftwareEngineerJava
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 177/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Linked
685
Fastestwaytodetermineifaninteger'ssquarerootisaninteger
29
What'sagoodalgorithmtodetermineifaninputisaperfectsquare?
Related
5
Findingperfectnumbers(optimization)
6
ShortestwaytocheckperfectSquare?
1
AnybodyknowsPayPalAPI(C#)forupdatingorderstatusandaddingtrackingnumber?
5
HowcanIfindoutthenumberofperiodsinastringwithC#
2
formulaforfindingasquareofanumber
1
FindingoutwhetheranumberisapalindromeornotinC#
0
Discountweekendsandfindoutthenumberofweekdaysfromadate?
3
Howtofindoutnumberofinstallmentsbetweentwodates?
0
Doesanybodyknowwhythislineofc#codingisgivingmeanerror?
1
FindoutYouTubeUserIDifIknowdisplayname
HotNetworkQuestions
HowcanIcheckifmyfunctionprint/echo'ssomething?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Whyshouldakeybemadeexplicit?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Troublewithterminatinga<apex:pageBlockSection>
zero,zerosorzeroes?
Wordfor"animals,includinghumans"?
SixMusicalFriends
ThenthTernary
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Whydosocksstink?
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
ALN*NTicTacToeGame
PythonLabelExpression?ArcGIS10.3.1
Derivativeofadefiniteintegralissue
Thetwopronunciationsof
Whatisatemporarysolutionforadamagedcarbody?
Jumpingcarwithtoomanyamps?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
LeapyearcheckinJava
Whyadding"incolour"whenreferringto"WizardofOz"?
Whatwereshoesolesmadefrominpreviousages?
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Invertingalistofnumbersandskipothers[closed]
Givenalistandanumberk,invertfirstkelementsandleavenextkelements.Repeatthisthroughoutthelist.ByinvertingImean,changingthesign
ofthenumber.
ThiswasanInterviewquestionatAmazon,thatIcamacrossonawebsite,andIwastryingtoapproachitjustbythinkingonhowtosolveit,sureI
wouldalsoliketoknowthefastestalgorithmforsolvingitandyourideas.
upvote0down IthoughtaboutpartitioningthearrayintotheKSteps,theninvert,skip.Thenmergethearrayslikeinmergesorting.
votefavorite
c++algorithm
askedOct5'13at13:34
share|improvethisquestion
AhmedSaleh
7591039
closedasofftopicbystefan,Mat,EdChum,SteveBarnes,gltsOct5'13at17:47
Thisquestionappearstobeofftopic.Theuserswhovotedtoclosegavethisspecificreason:
"Questionsaskingforcodemustdemonstrateaminimalunderstandingoftheproblembeingsolved.Includeattemptedsolutions,whytheydidn'twork,and
theexpectedresults.Seealso:StackOverflowquestionchecklist"stefan,Mat,EdChum,SteveBarnes
Ifthisquestioncanberewordedtofittherulesinthehelpcenter,pleaseeditthequestion.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 179/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Whatinvertmean??hasan83Oct5'13at13:35
changethesignofthenumberAhmedSalehOct5'13at13:36
@iccthedralwhatotherapproachestosolveit:)?inbettercomplexity?AhmedSalehOct5'13at13:37
addacomment|
2Answers
activeoldestvotes
for(inti=0;i<size;i+=k*2)
for(intj=0;j<k&&i+j<size;j++)
arr[i+j]=arr[i+j];
ifyouaresurethatarraysizeismultipleof2*korequaltox*2*kk,then:
for(inti=0;i<size;i+=k*2)
upvote2downvoteaccepted for(intj=0;j<k;j++)
arr[i+j]=arr[i+j];
answeredOct5'13at13:38
editedOct5'13at13:43
share|improvethisanswer
hasan83
6,81631332
Dothinkthatthereissimplerthanthis?hasan83Oct5'13at13:40
Whymultiplicationratherthanunarynegation?pjsOct5'13at13:41
Ihaveverifiedthissolutionanditworks.MaximeOct5'13at13:42
Likethisone?hasan83Oct5'13at13:43
Thisisabruteforcesolution,Iwouldliketogetabettercomplexity.AhmedSalehOct5'13at13:44
|show7morecomments
Complexityofhasan'ssolution:
Becauseyousaidyouthinkthathasan'ssolutionisO(N^2),I'dliketoexplainwhyyouarewrong.So,hehassuggested:
for(inti=0;i<size;i+=k*2)
for(intj=0;j<k&&i+j<size;j++)
arr[i+j]=arr[i+j];
upvote2
downvote Thenumberofiterationsforthefirstloopissize/(k*2)andthenumberofiterationsforthesecondloopisk.Hense,thetotalnumberofiterationsis
size/2.Whichisalsothenumberofelementsinthearraythatshouldbemodified.Youcan'tdobetterthanthat.
answeredOct5'13at13:56
share|improvethisanswer
Maxime
4,555837
Youcandobetterthanthat.ThecomplexityisO(1)onaquantumcomputer.aboaboOct5'13at14:21
IassumedaVonNeumannmachineorsimilar:).YoucanalsodobetterwithaFPGAandafixedsize.MaximeOct5'13at17:20
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedc++algorithmoraskyourown
question.
asked 1yearago
viewed 116times
active 1yearago
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 180/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Lookingforajob?
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Related
4270
TheDefinitiveC++BookGuideandList
7
O(logn)algorithmtofindtheelementhavingrankiinunionofpresortedlists
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
2
Unionofinvertedlists
4
C++:Fastestwaytosortalistofnumberandtheirindex
3
Arrangearrayof+veandvenumberwithorderintact
3
Whichnumbersinanunorderedlistcanberepresentedasasumof3othernumbersinthelist?
3
Algorithmtowriteuniquenumbersfromarray
2
Insertionintoaskiplist
1
findinganelementinanarray(havingDUPLICATES)rotatedunknownnumberoftimesinO(logn)time
HotNetworkQuestions
HowcanIcheckifmyfunctionprint/echo'ssomething?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Howtogetearlyentryintomystictheurge?
Howtodecidewhetherastoryisworthwriting?
Whydotheymanifestasrings?
Derivativeofadefiniteintegralissue
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
FiveAnglesinaStar
Antiferromagneticordering
Needtostartareligionwithapredefinedselfdestruct
SixMusicalFriends
Uncorrectedsamplestandarddeviationincorrelationcoefficient
Whyweren'ttheWeasleysapartoftheOriginalOrder?
40Numbersin9Bytes
Jumpingcarwithtoomanyamps?
CanIflywithagoldbar?
Whatistheoriginofthisphotoofanunexplodedbomb?
DoesCIDRreally"doaway"withIPaddressclasses?
Whatwereshoesolesmadefrominpreviousages?
HowtodealwithaGMwhodoesnottelluseverything?
Clientwantsfontaslogo
Paidcashforacar,butdealerwantstochangeprice
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Ciertasconjugacionesverbalesnoconvencionales
morehotquestions
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Science Other
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 181/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Culture/Recreation
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
The2lowestnumbersofanarray
Thequestionissimple(theanswertooprobably):HowcanIfindthe2lowestnumbersofanarray?
for(i=1;i<=n;i++){
if(v[i]<maxim)
maxim=v[i];
}
cout<<maxim;
upvote2down
votefavorite thisistheonlythingthatcomestomindtomebutitonlyshowsmethelowestnumber,notthe2lowestnumbers
2
c++arrays
askedMay24at13:02
share|improvethisquestion
griffinwish
246
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 182/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
geeksforgeeks.org/KamleshAryaMay24at13:05
Theeasyapproachistosortthearrayandthencanaccessthelowestnitemsfairlyeasy.Youcouldalsointroduceanextravariabletostorethe
2ndlowestnumber.martijnn2008May24at13:05
sortingthearraytakeskindalotoflinecodesandhowcouldiintroduceasecondvariablegriffinwishMay24at13:07
Callingstd::sortcanbedoneinasingleline,sothatisevenlesscode:)cplusplus.com/articles/NhA0RXSzThatsecondvariableisexactlywhat
@KamleshAryahasproposedwithhislink(seethecommentabove).martijnn2008May24at13:09
NotethatC/C++arraysare0indexbased,Soyourloopshouldbefor(inti=0;i<n;i++).Jarod42May24at13:17
|show1morecomment
6Answers
activeoldestvotes
Anothersimplewaywouldbe..
intv[]={33,11,22,3};
intsecmaxim=INT_MAX1;
intmaxim=INT_MAX;
for(inti=0;i<4;i++){
if(v[i]<maxim)
{
secmaxim=maxim;
upvote2downvote maxim=v[i];
}
accepted elseif(v[i]<secmaxim&&v[i]!=maxim)
secmaxim=v[i];
}
cout<<maxim<<secmaxim;
answeredMay24at13:16
editedMay24at13:50
share|improvethisanswer
HadeS
1,115217
brilliant!easyandlogicalgriffinwishMay24at13:16
Ok@OliverCharlesworthontoit..HadeSMay24at13:17
@griffinwish:Thismethodisalsofasterthansorting.Asabeginneryoumaynotcareaboutthatyet,butintimeyouwill.BetaMay
3
24at13:20
@OliverCharlesworthcodeformattingdone..HadeSMay24at13:23
1 Anygoodreasonforpunishment(downvote)..HadeSMay24at13:45
|show9morecomments
Ifyourarraymaybechanged,youcanusestd::partial_sort:
std::partial_sort(v,v+2,v+n);
Then,v[0]andv[1]arethetwosmallestvaluesofv.
Ifchangingthearrayisnotintended,orshouldbeavoided,std::partial_sort_copyisyourfriend.Introduceanewarrayoftwoelementsintowhich
theminimashouldbewritten:
intminima[2];
upvote4down std::partial_sort_copy(v,v+n,minima,minima+2);
vote
(Pleasechangethetypeofthearrayminimaaccordingly.Idon'tknowthetypeofyourarrayv.)
Tomakethesefunctionsavailable,youhavetoincludethefollowingfile:
#include<algorithm>
answeredMay24at13:05
editedMay24at13:10
share|improvethisanswer
leemes
22.6k751109
Iamnotfamiliarwithwhatstd::meansandnotevenfamiliarwiththat(function?)partial_sort_copygriffinwishMay24at13:09
use"usingnamespacestd"afterheader,ifyoudon'twanttousingstd::.BaTmaNMay24at13:11
Yesitisafunction.std::means,thatitispartoftheC++standardlibrary,whichhasalotofusefulbuildingblocks.leemesMay24at13:11
@griffinwishwouldn'titbetterifyoustartwithbasicslikehelloworld?sam2090May24at13:12
@martijnn2008Nope.STListhepredecessorofwhatisnowpartofthestandardlibrary.Itisthenameofadifferentlibrary.leemesMay24at
13:12
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 183/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
|show4morecomments
HowtofindtheksmallestelementsofanarrayinC++.
Naivemethod:Callstd::sortlookatfirstkelements.RunningtimeO(nlogn).
Interviewquestionmethod:Loopthrougharray,usingastd::set(orstd::push_heapandpop_heap)withkelementstokeeptrackofthelowestk.Runningtime
O(nlogk).Alsodoesnotmodifythearray,returnstheresultsinorder,andonlyusesO(k)additionalspace.
Bestmethod:#include<algorithm>.std::nth_element(&a[0],&a[k],&a[n]).Lookatfirstkelements.RunningtimeO(n),whichisoptimal.
up
vote2 [Update]
down
vote IfeellikeIshouldexplainwhatImeanby"interviewquestionmethod".Ifyouareactuallyaskedthisquestioninaninterview,youareprobablyatGoogleor
Amazonorsomeotherbigdatayaddayaddaenvironment,andtheinterviewersaidsomethinglike,"Ihave100billionintegersondiskandIwanttoknowthe
smallest1000ofthem."Inthatcontext,solutionsthatmodifythearrayorthatrequireO(n)additionalspaceareprobablynotthebestidea.
answeredMay24at13:21
editedMay24at16:28
share|improvethisanswer
Nemo
37.5k659103
addacomment|
Youcanusestd::sort()tosorttheelements
Hereisasmallexampletodisplayhowsortworks?
#include<iostream>
#include<array>
#include<algorithm>
intmain(){
std::array<int,5>arr{5,3,24,9,7};
std::sort(arr.begin(),arr.end());
std::cout<<arr[0]<<std::endl<<arr[1];
return0;
}
upvote0downvote
Incodeabove,std::sortwillsortthearrayarrinascendingorder.<algorithm>isheaderisrequiredforusingsort.
Theoutputwouldbe
Hereislinktotheworkingversionofcodeabove.
editedMay24at13:21 answeredMay24at13:16
share|improvethisanswer
BillLynch sam2090
43.4k854100 33818
wow...sortedthearraythatquickly?griffinwishMay24at13:19
@griffinwishonelineofcodeandyoucanseethemagic:)sam2090May24at13:20
Thisisunnecessarilyinefficient.juanchopanzaMay24at13:29
@juanchopanzaAgreedthatitsO(nlog(n))butOPdidn'taskforfastestsoIpostedanalternatesolution:)sam2090May24at13:33
addacomment|
Withoutchangingtheorderofthearray,
#include<iostream>
#include<vector>
#include<algorithm>
intmain()
{
std::vector<int>v{9,8,7,6,5,1,2,3,4};
intsmallest=*std::min_element(v.begin(),v.end());
intsecond_smallest=*std::min_element(v.begin(),v.end(),[&smallest](inti,intj){returni<j&&i>=smallest;});
std::cout<<"smallest:"<<smallest<<std::endl;
upvote0downvote std::cout<<"secondsmallest:"<<second_smallest<<std::endl;
}
Output:
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 184/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
smallest:1
secondsmallest:2
answeredMay24at13:51
share|improvethisanswer
AchillesRasquinha
12718
addacomment|
Adaptedfrom@leemesanswer(usingmoremodernsyntax),seehisanswerforanexplanation.
constautotopVals=2;
std::array<int,topVals>minima;
upvote1downvote std::partial_sort_copy(std::begin(v),std::end(v),minima.begin(),minima.end());
answeredMay24at13:21
editedMay24at16:03
share|improvethisanswer
WesleyShillingford
1194
Thisisnotananswer.juanchopanzaMay24at13:27
Iknow...itwouldhavebeenacommentto@leemesanswer,butIdon'thaveenoughreputation....WesleyShillingfordMay24at13:29
Thatdoesn'tmatter.Itdoesn'tchangethefactthatthisisn'tananswer.juanchopanzaMay24at13:30
Fine...it'sananswernow...WesleyShillingfordMay24at13:41
Again,std::nth_elementismoreappropriate(andfaster)forthisquestion.NemoMay24at13:57
|show4morecomments
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 185/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedc++arraysoraskyourownquestion.
asked 1monthago
viewed 135times
active 1monthago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
iOSDeveloper
hedgehoglab
Hyderabad,India
iosobjectivec
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Related
1668
Removespecificelementfromanarray?
1
ReturnArraypositionoflowestnumber(notnegative)
11313
Whyisprocessingasortedarrayfasterthananunsortedarray?
1
Searchlargearrayforlowestnumber
1
Troublefindinghighest/lowestelementinarrayC++
1
Javaarraylowestnumberandaveragenotcomputingcorrectly
4
Howtowriteaphpfunctionthattheinputisarrayandthefunctionfindsthelowestnumber
2
Getthelowestlistcountinarray
0
JS:findlowest/highestnumberfromarraywithinaspecificrange
HotNetworkQuestions
Thetwopronunciationsof
Isthereawordforpeopleincapableofthinking?
Derivativeofadefiniteintegralissue
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
Shouldmy(sequential)collectionstartatindex0orindex1?
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Needtostartareligionwithapredefinedselfdestruct
Alarmclockprinting
HowdoIfacilitateafirsttimeAgileretrospective?
PythonLabelExpression?ArcGIS10.3.1
Removestaticobjectsfromanimagesequence
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
zero,zerosorzeroes?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Whyadding"incolour"whenreferringto"WizardofOz"?
Passfilenamefrombashtopython
WhoinventedStarTreksideburnsandwhy?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
FiveAnglesinaStar
CanICultureBombfaraway?
Nicelytypesettingverbatimtext
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 186/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
LeapyearcheckinJava
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Googlesearchsuggestionimplementation
InarecentamazoninterviewIwasaskedtoimplementGoogle"suggestion"feature.Whenauserenters"AenifferAninston",Googlesuggests"Didyou
meanJenifferAninston".Itriedtosolveitbyusinghashingbutcouldnotcoverthecornercases.Pleaseletmeknowyourthoughtonthis.
upvote3
downvote datastructures
favorite askedAug14'13at8:26
3
share|improvethisquestion
user2032118
5910
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 187/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
1Answer
activeoldestvotes
Thereare4mostcommontypesoferros
1. Omittedletter:"stck"insteadof"stack"
2. Onelettertypo:"styck"insteadof"stack"
3. Extraletter:"starck"insteadof"stack"
4. Adjacentlettersswapped:"satck"insteadof"stack"
BTW,wecanswapnotadjacentlettersbutanylettersbutthisisnotcommontypo.
Initialstatetypedword.RunBFS/DFSfrominitialvertex.Depthofsearchisyourownchoice.Rememberthatincreasingdepthofsearchleadstodramatically
increasingnumberof"probablecorrections".Ithinkdepth~45isagoodstart.
Aftergenerating"probablecorrections"searcheachgeneratedwordcandidateinadictionarybinarysearchinsorteddictionaryorsearchinatriewhichpopulated
withyourdictionary.
TrieisfasterbutbinarysearchallowssearchinginRandomAccessFilewithoutloadingdictionarytoRAM.Youhavetoloadonlyprecomputedintegerarray[].
Array[i]givesyounumberofbytestoskipforaccesingithword.WordsinRandomAccesFileshouldbewritteninasortedorder.IfyouhaveenoughRAMto
storedictionaryusetrie.
Beforesuggestingcorrectionschecktypedwordifitisinadictionary,providenothing.
UPDATE
GeneratecorrectionsshouldbedonebyBFSwhenItriedDFS,entrieslike"Jeniffer"showed"editdistance=3".DFSdoesn'tworks,sinceitmakealotofchanges
whichcanbedoneinonestepforexample,Jniffer>nJiffer>enJiffer>eJniffer>JenifferinsteadofJniffer>Jeniffer.
SamplecodeforgeneratingcorrectionsbyBFS
staticclassPair
{
privateStringword;
privatebytedist;
//distisbytebecausedist<=128.
//Moreover,dist<=6inrealapplication
publicPair(Stringword,bytedist)
{
this.word=word;
this.dist=dist;
}
publicStringgetWord()
{
returnword;
}
publicintgetDist()
{
returndist;
}
}
publicstaticvoidmain(String[]args)throwsException
{
HashSet<String>usedWords;
HashSet<String>dict;
ArrayList<String>corrections;
ArrayDeque<Pair>states;
usedWords=newHashSet<String>();
corrections=newArrayList<String>();
dict=newHashSet<String>();
states=newArrayDeque<Pair>();
//populatedictionary.Inrealusageshouldbepopulatedfrompreparedfile.
dict.add("Jeniffer");
dict.add("Jeniffert");//depth2test
usedWords.add("Jniffer");
states.add(newPair("Jniffer",(byte)0));
while(!states.isEmpty())
up {
vote Pairhead=states.pollFirst();
2 //System.out.println(head.getWord()+""+head.getDist());
if(head.getDist()<=2)
down {
vote //checkingreacheddepth.
//4isthefirstdepthwherewedon'tgenerateanything
//swapadjacentletters
for(inti=0;i<head.getWord().length()1;i++)
{
//swapithandi+1thletters
StringnewWord=head.getWord().substring(0,i)+head.getWord().charAt(i+1)+head.getWord().charAt(i)+head.getWord().substring(i+2);
//evenifi==curWord.length()2andtheni+2==curWord.length
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 188/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
//substring(i+2)doesn'tthrowexceptionandreturnsemptystring
//thesameforsubstring(0,i)wheni==0
if(!usedWords.contains(newWord))
{
usedWords.add(newWord);
if(dict.contains(newWord))
{
corrections.add(newWord);
}
states.addLast(newPair(newWord,(byte)(head.getDist()+1)));
}
}
//insertletters
for(inti=0;i<=head.getWord().length();i++)
for(charch='a';ch<='z';ch++)
{
StringnewWord=head.getWord().substring(0,i)+ch+head.getWord().substring(i);
if(!usedWords.contains(newWord))
{
usedWords.add(newWord);
if(dict.contains(newWord))
{
corrections.add(newWord);
}
states.addLast(newPair(newWord,(byte)(head.getDist()+1)));
}
}
}
}
for(Stringcorrection:corrections)
{
System.out.println("Didyoumean"+correction+"?");
}
usedWords.clear();
corrections.clear();
//helperdatastructuresmustbeclearedaftereachgenerateCorrectionscallmustbeemptyforthefutureusage.
WordsinadictionaryJeniffer,Jeniffert.Jeniffertisjustfortesting)
Output:
DidyoumeanJeniffer?
DidyoumeanJeniffert?
Important!
Ichoosedepthofgenerating=2.Inrealapplicationdepthshouldbe46,butasnumberofcombinationsgrowsexponentially,Idon'tgosodeep.Therearesome
optomizationsdevotedtoreducenumberofbranchesinasearchingtreebutIdon'tthinkmuchaboutthem.Iwroteonlymainidea.
Also,IusedHashSetforstoringdictionaryandforlabelingusedwords.ItseemsHashSet'sconstantistoolargewhenitcontaintmillionobjects.Maybeyoushould
usetriebothforwordinadictionarycheckingandforiswordlabeledchecking.
Ididn'timplementeraselettersandchangelettersoperationsbecauseIwanttoshowonlymainidea.
answeredAug14'13at10:37
editedAug15'13at5:54
share|improvethisanswer
Baurzhan
9171419
Thanksfortheexplanation.ButIcouldnotunderstandthe"generatingprobablecorrection"part.Ithinkyouaretalkingaboutallpossiblecombinations.For
exampleifsomeonetypes"JnifferAninston",whatwillbetheprobablecorrectionsandhowitwillmaptooriginalword"JenifferAninston"user2032118
Aug14'13at18:38
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 189/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggeddatastructuresoraskyourown
question.
asked 1yearago
viewed 697times
active 1yearago
Lookingforajob?
SeniorTechnicalConsultant/DeveloperInnovation
iSpace(aConnollyiHea
Hyderabad,India/remote
scalaakka
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Related
43
Implementinghash/isEqual:/isEqualTo:forObjectiveCcollections
38
Practicalusesofdifferentdatastructures
25
SearchinganumberinarotatedsortedArray
71
Algorithmtofindtop10searchterms
126
Howtoimplementaqueuewiththreestacks?
1
Suffixarrayimplementation
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 190/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
1
Collisionresolutiontechniqueincustomhasmapimplementation
0
SuggestDataStructurewhichimplementthis
0
Implementationofat9dictionaryusingtrie
4
storingthedataineffectivedatastructuresothatsearchwouldbefast
HotNetworkQuestions
ALN*NTicTacToeGame
HowtoprovemyGmailhasbeenhacked?
Whycan'tanonabeliangroupbe75%abelian?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
RollmyD&Dcharacter'sabilityscores
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Howtogetearlyentryintomystictheurge?
HowcanIcheckifmyfunctionprint/echo'ssomething?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Whyshouldakeybemadeexplicit?
Whatisatemporarysolutionforadamagedcarbody?
Whatistheoriginofthisphotoofanunexplodedbomb?
WhatdoesitmeanifanACmotorhastwovoltageratings?
Functionsthataretheirowninversion.
Whatistheoriginofthepowericon?
40Numbersin9Bytes
Whydosocksstink?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
MementoVivereMomentumMori
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Whydotheymanifestasrings?
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 191/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
SQLQueryforStudentmarkfunctionality
GotthisasaninterviewquestionfromAmazontotestbasicSQLskillsandIkindoffloppedit.Considerthefollowingtables:
StudentStid,Stname,Details
SubjectSubid,Subname
MarksStid,Subid,mark
Writeaquerytoprintthelistofnamesofstudentswhohavescoredthemaximummarkineachsubject.
ThewronganswerwhichIgavewas:
selectA.StnamefromAasStudent,Bas
(selectStid,Subid,max(mark)fromMarksgroupbySubid)whereA.Stid=B.Stid
upvote0 IwasthinkingyoucanhaveatableBinwhichyoucangetthetopmarksaloneandmatchitwiththenamesinthestudenttableA.Butturnsoutmy
downvote "groupby"iswrong.
favorite
OnemorevariationofthequestionwhichIfeltwascanbeaskedisthat,ifthereismorethanonestudenthavingthehighestmarkinasubject,eventheir
namesshouldbeincluded.
Canyoupleasehelpsolvethesequeries.Theyseemtobesimple,butIamnotabletogetahangofit.
Thanks!
sqldatabase
askedMay13'12at7:19
editedMay13'12at8:56
share|improvethisquestion
Maverickgugu
1993520
IamnotabletotagitasAmazoninterviewquestionorinterviewquestionasbothseemtobea"DONOTUSE"tagsforsomecleanupprocessin
StackOverflow.@Mods:Feelfreetoeditifanyinconsistenciesinquestionortagging.Iwilldeletethiscommentoncerectified.Thanks.
MaverickguguMay13'12at7:21
addacomment|
5Answers
activeoldestvotes
Youjusthavetopartitiontheproblemintosomebitesizedstepsandsolveeachonebyone
First,getthemaximumscoreineachsubject:
selectSubjectID,max(MarkRate)
fromMark
groupbySubjectID;
ThenquerywhoarethosethathasSubjectIDwithmaxMarkRate:
selectSubjectID,MarkRate,StudentID
fromMark
where(SubjectID,MarkRate)
in
(
selectSubjectID,max(MarkRate)
fromMark
groupbySubjectID
)
orderbySubjectID,StudentID;
ThenobtaintheStudent'sname,insteadofdisplayingjusttheStudentID:
selectSubjectName,MarkRate,StudentName
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 192/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
fromMark
joinStudentusing(StudentID)
joinSubjectusing(SubjectID)
where(SubjectID,MarkRate)
in
(
selectSubjectID,max(MarkRate)
fromMark
groupbySubjectID
)
orderbySubjectName,StudentName
Databasevendors'artificialdifferencesasidewithregardstojoiningandcorrelatingresults,thebasicstepisthesamefirst,partitiontheprobleminabitesized
parts,andthenintegratethemasyousolvedeachoneofthem,soitwon'tbeasconfusing.
Sampledata:
CREATETABLEStudent
(StudentIDint,StudentNamevarchar(6),Detailsvarchar(1));
INSERTINTOStudent
(StudentID,StudentName,Details)
VALUES
(1,'John','X'),
(2,'Paul','X'),
(3,'George','X'),
(4,'Paul','X');
CREATETABLESubject
(SubjectIDvarchar(1),SubjectNamevarchar(7));
INSERTINTOSubject
(SubjectID,SubjectName)
VALUES
('M','Math'),
('E','English'),
('H','History');
CREATETABLEMark
(StudentIDint,SubjectIDvarchar(1),MarkRateint);
INSERTINTOMark
(StudentID,SubjectID,MarkRate)
VALUES
(1,'M',90),
(1,'E',100),
(2,'M',95),
up (2,'E',70),
vote3 (3,'E',95),
down (3,'H',98),
(4,'H',90),
vote (4,'E',100);
Livetesthere:http://www.sqlfiddle.com/#!1/08728/3
INtupletestisstillajoinbyanyothername:
Convertthis..
selectSubjectName,MarkRate,StudentName
fromMark
joinStudentusing(StudentID)
joinSubjectusing(SubjectID)
where(SubjectID,MarkRate)
in
(
selectSubjectID,max(MarkRate)
fromMark
groupbySubjectID
)
orderbySubjectName,StudentName
..toJOIN:
selectSubjectName,MarkRate,StudentName
fromMark
joinStudentusing(StudentID)
joinSubjectusing(SubjectID)
join
(
selectSubjectID,max(MarkRate)asMarkRate
fromMark
groupbySubjectID
)asxusing(SubjectID,MarkRate)
orderbySubjectName,StudentName
Contrastthiscodewiththecodeimmediateit.SeehowJOINonindependentquerylooklikeanINconstruct?Theyalmostlookthesame,andINwasjust
replacedwithJOINkeywordandthereplacedINkeywordwithJOINisinfactlonger,youneedtoaliastheindependentquery'scolumnresult(max(MarkRate)AS
MarkRate)andalsothesubqueryitself(asx).Anyway,thisarejustmatterofstyle,IpreferINclause,astheintentisclearer.UsingJOINsmerelytoreflectthe
datarelationship.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 193/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Anyway,here'sthequerythatworksonalldatabasesthatdoesn'tsupporttupletest(IN):
selectsb.SubjectName,m.MarkRate,st.StudentName
fromMarkasm
joinStudentasstonst.StudentID=m.StudentID
joinSubjectassbonsb.SubjectID=m.SubjectID
join
(
selectSubjectID,max(MarkRate)asMaxMarkRate
fromMark
groupbySubjectID
)asxonm.SubjectID=x.SubjectIDANDm.MarkRate=x.MaxMarkRate
orderbysb.SubjectName,st.StudentName
Livetest:http://www.sqlfiddle.com/#!1/08728/4
answeredMay13'12at7:52
editedMay13'12at11:58
share|improvethisanswer
MichaelBuen
23k14580
addacomment|
MyattemptI'dstartwiththemaxmarkandbuildfromthere
Schema:
CREATETABLEStudent(
StudentIdint,
Namenvarchar(30),
Detailsnvarchar(30)
)
CREATETABLESubject(
SubjectIdint,
Namenvarchar(30)
)
CREATETABLEMarks(
StudentIdint,
SubjectIdint,
Markint
)
Data:
INSERTINTOStudent(StudentId,Name,Details)
VALUES(1,'Alfred','AA'),(2,'Betty','BB'),(3,'Chris','CC')
INSERTINTOSubject(SubjectId,Name)
VALUES(1,'Maths'),(2,'Science'),(3,'English')
INSERTINTOMarks(StudentId,SubjectId,Mark)
VALUES
(1,1,61),(1,2,75),(1,3,87),
(2,1,82),(2,2,64),(2,3,77),
(3,1,82),(3,2,83),(3,3,67)
GO
Myquerywouldhavebeen:
upvote2downvote ;WITHMaxMarksAS(
SELECTSubjectId,MAX(Mark)asMaxMark
FROMMarks
GROUPBYSubjectId
)
SELECTs.Nameas[StudentName],sub.NameAS[SubjectName],m.Mark
FROMMaxMarksmm
INNERJOINMarksm
ONm.SubjectId=mm.SubjectId
ANDm.Mark=mm.MaxMark
INNERJOINStudents
ONs.StudentId=m.StudentId
INNERJOINSubjectsub
ONsub.SubjectId=mm.SubjectId
SQLFiddleExample
1. Findthemaxmarkforeachsubject
2. JoinMarks,StudentandSubjecttofindtherelevantdetailsofthathighestmark
Thisalsotakecareofduplicatestudentswiththehighestmark
Results:
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 194/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
STUDENTNAMESUBJECTNAMEMARK
AlfredEnglish87
BettyMaths82
ChrisMaths82
ChrisScience83
answeredMay13'12at7:24
editedMay13'12at7:53
share|improvethisanswer
Paddy
1,2961722
addacomment|
Iwouldhavesaid:
selects.stname,s2.subname,highmarks.mark
fromstudentss
joinmarksmons.stid=m.stid
joinSubjects2onm.subid=s2.subid
join(selectsubid,max(mark)asmark
frommarksgroupbysubid)ashighmarks
onhighmarks.subid=m.subidandhighmarks.mark=m.mark
orderbysubname,stname;
SQLFiddlehere:http://sqlfiddle.com/#!2/5ef84/3
upvote Thisisa:
2down
vote selectonthestudentstabletogetthepossiblestudents
ajointothemarkstabletomatchupstudentstomarks,
ajointothesubjectstabletoresolvesubjectidsintonames.
ajointoaderivedtableofthemaximummarksineachsubject.
Onlythestudentsthatgetmaximummarkswillmeetallthreejoinconditions.Thislistsallstudentswhogotthatmaximummark,soifthereareties,bothget
listed.
answeredMay13'12at7:43
editedMay13'12at8:00
share|improvethisanswer
MikeRyan
2,009916
Thanks@Ryan.Thisqueryisprettyconciseandnice..but,mayIknowwhetherthethirdconditionwhereyoujointhesubjectstabletoresolveittotheir
namesisjusttoprintthesubjectnameintheoutput?MaverickguguMay13'12at8:40
Andonemoredoubt,iswhythe"orderby"..Didyouaddthatwithanymotive?Because,Iamgettingthesameoutput.MaverickguguMay13'12at
8:51
Botharetomaketheresultmorereadable.Youdon'tactuallysaywhetherornotyouwanttoresolvethesubid'stothesubjectnames.Butsincethetableis
supplied,andyouhavetodisplayeitherthesubidorthesubname,Itookitasimplied.Andtheorderbyistomaketheoutputnice.(Usuallythecasew/
orderby.)InanyrealsituationI'dask.MikeRyanMay13'12at14:08
addacomment|
Ilikethesimplesolutionusingwindowsfunctions:
selectt.*
from(selectstudent.*,su.subname,max(mark)over(partitionbysubid)asmaxmark
frommarksmjoin
studentsst
onm.stid=st.stidjoin
subjectsu
onm.subid=su.subid
)t
wheret.mark=maxmark
Or,alternatively:
upvote0downvote selectt.*
from(selectstudent.*,su.subname,rank(mark)over(partitionbysubidorderbymarkdesc)asmarkseqnum
frommarksmjoin
studentsst
onm.stid=st.stidjoin
subjectsu
onm.subid=su.subid
)t
wheremarkseqnum=1
answeredMay13'12at13:47
share|improvethisanswer
GordonLinoff
311k1779132
addacomment|
Justforfun,considerthedifferentquestiononewouldgetwithaveryliteralinterpretationoftheOP'sdescription:"Writeaquerytoprintthelistofnamesof
studentswhohavescoredthemaximummarkineachsubject."
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 195/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Thosewho'veansweredherehavewrittenqueriestolistastudentifheorshescoredthemaximummarkinanyonesubject,butnotnecessarilyinallsubjects.
SincethequestionposedbytheOPdoesnotaskforsubjectnamesintheoutput,thisisaplausibleinterpretation.
Tolistthenamesofstudents(ifany)whohavescoredthemaximummarkinallsubjects(excludingsubjectswithnomarks,sincearguablythereisthenno
maximummarkthen),Ithinkthisworks,usingcolumnnamesfromMichael'sSQLFiddle,whichI'veadaptedhere.
selectStudentName
fromStudent
wherenotexists(
select*fromSubject
whereexists(
select*fromMarkasM1
upvote0 whereM1.SubjectID=Subject.SubjectID
andM1.StudentID<>Student.StudentID
down andnotexists(
vote select*fromMarkasM2
whereM2.StudentID=Student.StudentID
andM2.SubjectID=M1.SubjectID
andM2.MarkRate>=M1.MarkRate
)
)
)
Inotherwords,selectastudentX'snameifthereisnosubjectinwhichsomeone'smarkforthatsubjectisnotmatchedorexceededbysomemarkbelongingto
Xforthesamesubject.(Thisqueryreturnsastudent'snameifthestudenthasreceivedmorethanonemarkinasubject,solongasoneofthosemarksisthe
highestforthesubject.)
answeredMay14'12at0:18
editedMay14'12at3:17
share|improvethisanswer
SteveKass
5,030515
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 196/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedsqldatabaseoraskyourownquestion.
asked 3yearsago
viewed 12373times
active 3yearsago
Lookingforajob?
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
PolyglotDeveloper(ruby,javascript,clojure,etc.)
MavenHiveTechnologiesPvt
Bengaluru,India/relocation
rubyonrailsstartup
Related
632
SQLInsertintovalues(SELECTFROM)
2790
HowcanIpreventSQLinjectioninPHP?
1155
Addacolumn,withadefaultvalue,toanexistingtableinSQLServer
0
Howtowritecorrectquerytofindstudentsnotcurrentlyinacourse
2
Classwise,studentnamewhohasmaxaggregateofmarks
3
SQLquerytoarrangemarksofstudentsindescendingorder
0
selectqueryfornamesofstudentwithmarksatleast60intwosubjects
1
PseudocodeforSQLquery
1
howtogeneratestudentsmarkledgerfrom3tablesStudent,Mark,Subject
0
SQLstudentsmarkquery
HotNetworkQuestions
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
FindingoutifawordisanAnagramofanother
Derivativeofadefiniteintegralissue
ALN*NTicTacToeGame
howcanItaketotalminutesfromtime?
zero,zerosorzeroes?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 197/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Passfilenamefrombashtopython
LeapyearcheckinJava
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
FiveAnglesinaStar
ImageOpensasLayer0ratherthanBackground
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
HowcouldaresurrectedJesusproveheisJesus?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Whyshouldakeybemadeexplicit?
Justifyingsuboptimalresearchqualitybylackofsupervision
HowtodealwithaGMwhodoesnottelluseverything?
Nicelytypesettingverbatimtext
What'sanexpressionforacunninglyfakefriend?
Howtodecidewhetherastoryisworthwriting?
NineTallMenAreStandingTall
CanIflywithagoldbar?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Whatarebestpracticesforcollecting,maintainingandensuringaccuracyofa
hugedataset?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 198/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Iamposingthisquestionlookingforpracticaladviceonhowtodesignasystem.
Siteslikeamazon.comandpandorahaveandmaintainhugedatasetstoruntheircorebusiness.Forexample,amazon(andeveryothermajorecommerce
site)hasmillionsofproductsforsale,imagesofthoseproducts,pricing,specifications,etc.etc.etc.
Ignoringthedatacominginfrom3rdpartysellersandtheusergeneratedcontentallthat"stuff"hadtocomefromsomewhereandismaintainedby
someone.It'salsoincrediblydetailedandaccurate.How?Howdotheydoit?Istherejustanarmyofdataentryclerksorhavetheydevisedsystemsto
handlethegruntwork?
Mycompanyisinasimilarsituation.Wemaintainahuge(10ofmillionsofrecords)catalogofautomotivepartsandthecarstheyfit.We'vebeenatitfora
whilenowandhavecomeupwithanumberofprogramsandprocessestokeepourcataloggrowingandaccuratehowever,itseemsliketogrowthe
upvote8 catalogtoxitemsweneedtogrowtheteamtoy.
downvote
favorite IneedtofiguresomewaystoincreasetheefficiencyofthedatateamandhopefullyIcanlearnfromtheworkofothers.Anysuggestionsareappreciated,
1 morethoughwouldbelinkstocontentIcouldspendsomeserioustimereading.
THANKS!
Kyle
databasedata
askedDec22'10at1:38
share|improvethisquestion
KyleWest
4,84854684
addacomment|
7Answers
activeoldestvotes
Usevisitors.
1. Evenifyouhaveonepersonperitem,therewillbewrongrecords,andcustomerswillfindit.So,letthemmarkitemsas"inappropiate"andmakea
shortcomment.Butdon'tforget,they'renotyouremployees,don'taskthemtoomuchseeFacebook's"like"button,it'seasytouse,andrequiresnottoo
muchenergyfromtheuser.Goodperformance/price.IftherewouldbeamandatoryfieldinFacebook,whichasks"whydoyoulikeit?",nooneshould
upvote5 usethatfunction.
down
vote 2. Visitorsalsohelpsyouimpliciteway:theyvisititempages,andusesearchfunction(Imeanbothinternalsearchengineandexternalones,likeGoogle).
accepted Youcangaininformationfromvisitors'activity,say,setuptheorderofthemostvisiteditems,thenyoushouldconcentratemorehumanforcesonthe
+125 topofthelist,andlessforthe"longtail".
answeredJan1'11at14:52
share|improvethisanswer
ern0
2,3661229
addacomment|
Sincethisismoreaboutmanagingtheteam/code/dataratherthanimplementationandsinceyoumentionedAmazonIthinkyou'llfindthisuseful:
http://highscalability.com/amazonarchitecture.
Inparticular,clickthelinktoWernerVogelsinterview.
upvote3down
vote answeredDec22'10at1:50
share|improvethisanswer
slebetman
35.3k55076
thanks,Iamcheckingitoutnow.KyleWestDec22'10at2:12
addacomment|
Builditrightinthefirstplace.Ensurethatyouuseeveryintegritycheckingmethodavailableinthedatabaseyou'reusing,asappropriatetowhatyou're
storing.Betterthatanuploadfailthanbaddatagetsilentlyintroduced.
Then,figureoutwhatyou'regoingtodointermsofyourownintegritychecking.DBintegritychecksareagoodstart,butrarelyareallyouneed.Thatwill
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 199/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
alsoforceyoutothink,fromthebeginning,aboutwhattypeofdatayou'reworkingwith,howyouneedtostoreit,andhowtorecognizeandflagorrejectbad
orquestionabledata.
upvote3 Ican'ttellyoutheamountofpainI'veseenfromtryingtorework(orjustdaytodayworkwith)oldsystemsfullofgarbagedata.Doingitrightandtestingit
down thoroughlyupfrontmayseemlikeapain,anditcanbe,buttherewardishavingasystemthatforthemostparthumsalongandneedslittletonointervention.
vote
Asforalink,ifthere'sanyonewho'shadtothinkaboutanddesignforscalability,it'sGoogle.Youmightfindthisinstructive,it'sgotsomegoodthingstokeep
inmind:http://highscalability.com/googlearchitecture
answeredDec22'10at2:15
share|improvethisanswer
ToddAllen
318317
addacomment|
MasterDataManagementisanotheralternativetowhathasbeenproposed.HereisMicrosoft'sarticle"TheWhat,Why,andHowofMasterData
Management".Datastewardsaregiventherights/responsibilitytomaintaintheaccuracyofthedatafortheenterprise.
Themainabilitytoscalecomesfromaligningthetechnologywiththebusinesssothatthedatapersonnelarenottheonlypeoplewhocanmanagethe
upvote2 information.Toolsandprocesses/proceduresenablebusinessownerstohelpmanageenterprisedata.
downvote
answeredJan3'11at22:25
editedJan3'11at22:35
share|improvethisanswer
Suirtimed
6151416
addacomment|
Sharedatewithyoursuppliers.Thenthedataisenteredonce.
Ifitisimportantitshouldbedoneonce,elsenotatall.
upvote1down
vote answeredJan1'11at0:01
share|improvethisanswer
richard
2,4262730
Ifwedidthis,we'dbeoutofbusiness.We'reinthebusinessofmanagingtheirdata(andsendingittoeveryoneelsesoitisonlydoneonce).
KyleWestJan4'11at7:24
addacomment|
Iwouldinvestheavilyindatamining.Getasmanyfeedsaspossibleabouttheproductsyouaretryingtosell.Getfeedsaboutthevehicle'sdirectlyfrom
vendors,aswellasfromautomotiverepaircompanieslikeMitchellandHaynes.
Onceyouknowthepartsthatyouneed,crosscorrelatethosepartnumberswithpartnumbersthatareavailableontheinterenet.AlsoCrosscorrelatethosepart
numberswithimages,reviews,andarticles.Attempttoaggregateasmuchinformationaspossibleinonepage,andeventuallyallowthatpagetobeindexedby
google.
Basedontheresultsofyourdataaggregation,assignaseriesofweightstoeachproducts.Basedonthevalueofyourweightseitherpassontheresultstoan
employeeandhavethemnegotiatepricewithsuppliers,createapageasisandlinktothesources(assumingyouwouldreceiveacommission),or,don'tsellthe
part.
upvote
1down Onceyouhaveenoughproductsinoneplace,youcanthensupportotherpeoplewhowouldliketoaddadditionalproductstoyourwebsite.Thebreadthof
vote resourcesavailableonAmazonisinalargepartduetosupportingthirdpartysellersandallowingthosesellerstolistonAmazon'swebsite.
Especiallyintheautoindustry,Ithinktheirisagreatvalueinhighqualityindexingwhichisbothgooglefindableaswellaslogicallyfindablebypeople
lookingtoreplaceaspecificcomponent.Youmayalsowanttolookintoselling/providinglocationspecificservicesthroughIPgeolocationbasedonthe
componenttheyareinterestedinpurchasing.
answeredJan2'11at7:51
share|improvethisanswer
Claris
1,322615
addacomment|
MuchofthedatamanagedbySitelikegooglecomesfromusers.Ientermydataandanresponsibleforitsaccuracy.Siteshavetheirdata,anditiscaptured
fromtheweb.Searchdataiscapturedfromasearch.Thisislikelysignificantlydifferentfromwhatyourareattempting.ThereislittlerequirementforGoogle
stafftodoanythingwithit.
Workingwithmanufacturersfeedscouldmakeyoureffortslessmanpowerintensive.Thetradeoffisinvestinginthedatatransformationsoftware.Youmay
wanttocapturethesourceforeachcrossreference.Thiswilleasereloadswhenyougetupdates.
Frommyexperienceyoualsohavetheissuethatcrossreferencesmaybeunidirectional.AcanreplaceB,butBcannotreplaceA.
upvote1 Aslongasyouhavemanualentry,youwillhaveerrors.Anythingyoucandoinyourinterfacetodetecttheseerrorsislikelyworththeeffort.Inputvolumeto
down staffshouldscalelinearly.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 200/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
vote Reviewtheresearchonattentioncyclestodetermineifyoucandosomethingtoincreasequalityofinputandverificationprocesses.Recentresearchin
securityscanningindicatesthatyoumaywanttogenerateperiodicerrorsintheverificationdata.
Asotherhavenoted,makingiteasierforuserstoflagerrorsisagoodidea.
answeredJan4'11at0:45
share|improvethisanswer
BillThor
3,8391312
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggeddatabasedataoraskyourown
question.
asked 4yearsago
viewed 709times
active 4yearsago
Lookingforajob?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 201/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
DevOpsEngineerContinuousIntegration
DigitalAssess
Thiruvananthapuram,India
continuousintegrationjenkins
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Related
3
Bestdatabasesolutionformanagingahugeamountofdata
325
WhatarethebestpracticesforSQLiteonAndroid?
0
.net:bestpracticeforcheckingdataexistanceindatabaseinaloop?
2
What'sthebestpracticeforhandlingmostlystaticdataIwanttouseinallofmyenvironmentswithRails?
1
Whatisthebestwaytogetdatafromothersubdomainwithdifferentdatabase?
0
Whatisthebestpracticeforparsingdatagotfromawebservice?
3
Whatisthebestwaytostoresimplespatialdata
5
Bestpracticesfordatamanagementinprolog
0
Analyseahugedatasetofnumbers
0
BestapproachDBhitwithsmallamountofdata/singlehitwithhugedata
HotNetworkQuestions
MementoVivereMomentumMori
ThenthTernary
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Wordfor"animals,includinghumans"?
FiveAnglesinaStar
CanIflywithagoldbar?
Whyshouldakeybemadeexplicit?
Whyadding"incolour"whenreferringto"WizardofOz"?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
ImageOpensasLayer0ratherthanBackground
HowtodealwithaGMwhodoesnottelluseverything?
Isthereawordforpeopleincapableofthinking?
Canmathbesubjective?
What'sthebestwaytoinvestformakingregulardonations?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
Needhelprecreatingcrazycolors/materialfromexample
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
6. Electrical
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 202/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
7. Game Engineering 5. Mathematica 6. PersonalFinance 7. Bicycles 5. MathOverflow Careers
Development 7. AndroidEnthusiasts 6. Salesforce &Money 8. Roleplaying 6. more(7)
8. TeX 8. InformationSecurity 7. more(14) 7. Academia Games
LaTeX 8. more(10) 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Howtowriteasqlquerytomultiplytwovalueswhicharenotpresentinany
table?
ThisisaninterviewquestionaskedatAmazon.Helpmeguys!!!
sql
upvote7downvote askedMar5at16:37
favorite
share|improvethisquestion
SolaiRajan
1
4 select3*5asresult?juergendMar5at16:39
Althoughthequestionisnotwellformattedbecauseyourjusttryingtogetaninterviewquestionanswered.Thequestionitselfisn'tbad.
KalelWadeMar5at16:46
addacomment|
1Answer
activeoldestvotes
Youcansavethevaluesasavariableandthenuseit.
DECLARE@XASINT
DECLARE@YASINT
SET@X=3
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 203/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SET@Y=4
upvote0downvote SELECT@X*@Y
answeredMar5at17:01
share|improvethisanswer
wpa81
414
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedsqloraskyourownquestion.
asked 4monthsago
viewed 31times
active 4monthsago
Lookingforajob?
ChiefSoftwareArchitectJava$100K
Crossover
Bengaluru,India/remote
eclipsenetbeans
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 204/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
Related
1155
Addacolumn,withadefaultvalue,toanexistingtableinSQLServer
336
FindingduplicatevaluesinaSQLtable
1
SQLquerytogetallthecombinationsoftwocolumns
1
Querytooutputvalueswhicharenotpresentintable
0
howtowriteSQLqueryinthissituation
0
sqlqueryforconnectingtwotables
1
HowtowriteaqueryinSQL?
1
SQLQuery:HowtomultiplyvaluesinTableAbyValueinTableB?
3
SQLQuerySummarizeTable
0
HowtojointwoqueriesinSQLfrom3tables?
HotNetworkQuestions
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Paidcashforacar,butdealerwantstochangeprice
Whyweren'ttheWeasleysapartoftheOriginalOrder?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Whatistheoriginofthepowericon?
Passfilenamefrombashtopython
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
DoesaUSB3.0connectionrequireaUSB3.0cord?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
HowcouldaresurrectedJesusproveheisJesus?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Doblockingcreatureshealbacktofullbetweenphases?
Whatistheoriginofthisphotoofanunexplodedbomb?
Whydosocksstink?
zero,zerosorzeroes?
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Troublewithterminatinga<apex:pageBlockSection>
Needtostartareligionwithapredefinedselfdestruct
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
ThenthTernary
PythonLabelExpression?ArcGIS10.3.1
morehotquestions
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia Games
8. InformationSecurity
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 205/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
LaTeX 8. more(10) 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Checkastringforconsecutiverepeatedcharacters[closed]
ItisaskedinaninterviewtowritethecodeinJavatodisplaythestringwhichdoesn'thaveconsecutiverepeatedcharacters.
E.g.:Google,Apple,AmazonItshoulddisplay"Amazon"
Iwrotecodetofindcontinuesrepeatingchar.Isthereanyalgorithmorefficientwaytofindit?
upvote0downvotefavorite
javastringcharacter
editedJun26'14at18:47 askedJun26'14at16:27
share|improvethisquestion
KevinPanko Venki
5,20483044 383
closedastoobroadbyMena,T.S.,gnat,EdChum,gotqnJul6'14at9:56
Thereareeithertoomanypossibleanswers,orgoodanswerswouldbetoolongforthisformat.Pleaseadddetailstonarrowtheanswersetortoisolateanissuethatcan
beansweredinafewparagraphs.Ifthisquestioncanberewordedtofittherulesinthehelpcenter,pleaseeditthequestion.
2 Ifyoualreadywrotethecode,trypostingitoveratCodeReviewifyouwantpeopletolookatit.KeppilJun26'14at16:28
2 Whatdoes"continuesrepeatedcharacter"mean?DonBransonJun26'14at16:30
3 @DonBransonIthinkhemeansooinGoogle,ppinAppleandsoon.RafaelOsipovJun26'14at16:33
1 RafaelisrightVenkiJun26'14at16:33
1 "Consecutiverepeatedcharacters"mightbeabetterwaytophraseit.DavidConradJun26'14at16:43
|show2morecomments
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 206/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
1Answer
activeoldestvotes
classreplace
{
publicstaticvoidmain(Stringargs[])
{
Stringarr[]=newString[3];
arr[0]="Google";
arr[1]="Apple";
arr[2]="Amazon";
for(inti=0;i<arr.length;i++)
{
intj;
for(j=1;j<arr[i].length();j++)
{
if(arr[i].charAt(j)==arr[i].charAt(j1))
{
break;
upvote1down }
voteaccepted }
if(j==arr[i].length())
System.out.println(arr[i]);
}
}
}
Logic:MatchthecharactersinaStringwiththepreviouscharacter.
1. Ifyoufindstring[i]==string[i1].Breaktheloop.Choosethenextstring.
2. Ifyouhavereachedtilltheendofthestringwithnomatchhavingcontinuousrepeatedcharacter,thenprintthestring.
answeredJun26'14at16:44
editedJun26'14at17:30
share|improvethisanswer
Jerky
973624
Thanksforthesolution@AyushJainVenkiJun26'14at16:47
Iamnotabletodothatasisshowingup"VoteUprequire15reputation"VenkiJun26'14at16:50
whatistheuseofinitializingjtwicewithvalue1?SparkOnJun26'14at17:23
Correctedthecode.@M.SharmaJerkyJun26'14at17:38
YoucanjustwriteString[]names={"Google","Apple","Amazon"};andfor(Stringname:names).Itwouldmakethecodealotclearer
withoutallthemanualmuckingaroundwitharrays.DavidConradJun26'14at19:07
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavastringcharacteroraskyourown
question.
asked 1yearago
viewed 527times
active 1yearago
Lookingforajob?
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Related
2446
What'sthedifferencebetweenStringandstring?
1595
Read/convertanInputStreamtoaString
3239
HowcanIcheckifonestringcontainsanothersubstring?
120
Java:removealloccurrencesofcharfromstring
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 207/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
11
EfficientwaytofindFrequencyofacharacterinaStringinjava:O(n)
1335
Whyischar[]preferredoverStringforpasswords?
0
howtogetwordsfromasequenceofcharactersinjava?
0
GeneratingallpurmutationsofaJavastring,includingsmallerwords,andexcludingduplicates
3
Removerepeatingcharactersfromstring
0
KeepunicodecharactersinJavastring
HotNetworkQuestions
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
Nicelytypesettingverbatimtext
Derivativeofadefiniteintegralissue
Justifyingsuboptimalresearchqualitybylackofsupervision
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Whatis`$?`?Isitavariable?
Isthereawordforpeopleincapableofthinking?
PythonLabelExpression?ArcGIS10.3.1
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
Troublewithterminatinga<apex:pageBlockSection>
CanICultureBombfaraway?
Clientwantsfontaslogo
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
Patchingabinarywithdd
howcanItaketotalminutesfromtime?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
HowcanIcheckifmyfunctionprint/echo'ssomething?
Alarmclockprinting
zero,zerosorzeroes?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Multiplypurefunctionwithscalar
morehotquestions
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 208/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Daolayerandwebserviceintegration[closed]
I'mdevelopingarestfulwebservicethatwillsavedatainadatabaseandretrivedatafromadatabase.SoI'mplanningtoimplementwebservicelogic
anddatataaccesslogicastwodifferentprojects.Itwouldbegreatifyoucoulddiscussprosandconsinthisapproach.
upvote0down javadatabasewebservices
votefavorite editedJun25'12at12:08 askedJun25'12at12:05
share|improvethisquestion
duffymo abc123
207k14217392 3,64831637
closedasnotarealquestionbyJigarJoshi,duffymo,npinti,artbristol,kapaJun25'12at12:31
It'sdifficulttotellwhatisbeingaskedhere.Thisquestionisambiguous,vague,incomplete,overlybroad,orrhetoricalandcannotbereasonablyansweredinitscurrent
form.Forhelpclarifyingthisquestionsothatitcanbereopened,visitthehelpcenter.Ifthisquestioncanberewordedtofittherulesinthehelpcenter,pleaseeditthe
question.
addacomment|
1Answer
activeoldestvotes
Iwouldrecommendjustoneproject.ThewebservicewillowntheDAOandthedatabase.Noneedfortwo.
Asforpros,readWernerVogel'sACMinterviewaboutwebservicesatAmazon.Payspecialattentiontohisstatementabout"services
owningtheirdata."
upvote1downvote Cons?Yourwayaddscomplexitywithoutbenefit.ItwouldencouragereusingthatDAOsomewhereelse.
accepted
answeredJun25'12at12:08
editedNov11'12at4:08
share|improvethisanswer
duffymo
207k14217392
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavadatabasewebservicesoraskyour
ownquestion.
asked 3yearsago
viewed 234times
active 2yearsago
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 209/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Lookingforajob?
UIDeveloperataprofitableSaaSstartup
Recruiterbox
Bengaluru,India/relocation
htmlcss
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Related
2
javawebservices
5
Exposewebservicedirectlytowebclientsorkeepathinserversidescriptlayerinbetween?
4
Bestwaytoaccessaremotedatabase:viawebserviceordirectDBaccess?
0
adviceonintegrationtestingmydaolayer
2
GuidemeinlearningWebservicesinJava
0
restwebserviceDAOlayerandwebserviceintegration,sessionfactorynullexception
0
Providingdatabaseacccessviajavawebservice
0
DataAccessLayerforWebservices
0
seperatingGUIandDAOviaRESTWebservicesandSpring
0
RESTfulWebservicesIntegrationWithSpringandHibernate
HotNetworkQuestions
Isturninggraphitecarbonintodiamondindustriallydoable?
FiveAnglesinaStar
Whydotheymanifestasrings?
DoesCIDRreally"doaway"withIPaddressclasses?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Ciertasconjugacionesverbalesnoconvencionales
Whyshouldakeybemadeexplicit?
Whatis`$?`?Isitavariable?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
Needtostartareligionwithapredefinedselfdestruct
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
HowcouldaresurrectedJesusproveheisJesus?
ALN*NTicTacToeGame
ImageOpensasLayer0ratherthanBackground
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
Whatistheoriginofthisphotoofanunexplodedbomb?
WhatdoesitmeanifanACmotorhastwovoltageratings?
Justifyingsuboptimalresearchqualitybylackofsupervision
Shouldmy(sequential)collectionstartatindex0orindex1?
HowdoIfacilitateafirsttimeAgileretrospective?
Antiferromagneticordering
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 210/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Howtogetearlyentryintomystictheurge?
Nicelytypesettingverbatimtext
morehotquestions
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
GivenanunsortedArrayfindmaximumvalueofA[j]A[i]wherej>i..inO(n)
time
ThisisanAmazoninterviewQuestion.IhavesolvedthisprobleminO(n)usingdynamicprogramming.ButIwanttoknowcantherebemore
optimizationthanO(n)
fore.g.supposebelowisthearray
371424returns4
upvote8downvote 54321returnsNothing
favorite
43223returns1
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 211/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
6 ThisisthecodeihavewrittenCode
javacarraysalgorithm
editedApr3'12at11:23 askedApr3'12at6:39
share|improvethisquestion
SaeedAmiri Algorithmist
17.1k42062 3,02321644
8 Idon'tseehowgoingfromO(n)toO(nlogn)wouldbeanoptimization.aioobeApr3'12at6:41
2 ButO(nlogn)isworsethanO(n)...DanielKamilKozarApr3'12at6:41
2 YousayyoualreadyhaveanO(n)solution.Bydefinition,anyO(n)isalsoO(nlogn).NPEApr3'12at6:41
3 YoucannotbeanAlgorithmist:(DhruvPathakApr3'12at6:42
BetterthanO(n)here?)Idon'tthinkyoucanescapeexaminingeachelementatleastonce,especiallygiventhatsamplearraysareunsorted.
1
gorlum0Apr3'12at7:45
|show4morecomments
4Answers
activeoldestvotes
Letssayyou'vegotintA[N].
intres=1;
intmin_value=A[0];
for(inti=1;i<N;i++){
//A[i]A[j]ismaximal,whenA[j]isminimalvaluefrom{A[0],A[1],..,A[i1]}
res=max(res,A[i]min_value);
min_value=min(min_value,A[i]);
}
upvote13downvote returnres;
accepted
ComplexityO(N).
YouneedtoexamineNelementssoO(N)isbestwhatyoucanget.
answeredApr3'12at6:42
editedApr3'12at7:13
share|improvethisanswer
JarosawGomuka
2,448519
1 Doyoumean=min(min_value,A[i])?BlackJackApr3'12at6:44
You'reright.I'vecorrectedit.JarosawGomukaApr3'12at6:48
@Algorithmist,Don'tknowwhythislookssomuchlikethisproblem,whichisfromanongoingcontest.>.<PriyankBhatnagarApr
3'12at11:29
addacomment|
ButIwanttoknowcantherebemoreoptimizationthenO(n)
Anyofthenelementscanbepartofthesolution,andthereforeeachneedstobeexamined.Thus,O(n)cannotbeimprovedupon.
Forcompleteness,hereisasolutionthattakesO(n)timeandrequiresO(1)memory:
A=[1,10,20,10,3,4,18,42,15]
smallest=A[0]
upvote6down maxdiff=float('inf')
vote forxinA[1:]:
maxdiff=max(maxdiff,xsmallest)
smallest=min(smallest,x)
printmaxdiff
answeredApr3'12at6:45
editedApr3'12at6:58
share|improvethisanswer
NPE
209k25432641
imsorryforthetypomistake...Iwassolvingsomeotherproblemalso,anditgotmixed.AlgorithmistApr3'12at6:56
@Algorithmist:No,youcan'tdobetterthanO(n).Anyelementcanbepartofthesolutionandthereforeneedstobeexamined.ThereareO(n)
1
elements.NPEApr3'12at6:59
addacomment|
Itcan'tbedonebetterthanO(n)becausewhateverapproachyouuse,youwillhavetoiterateoverthearrayatleastonceandthatstepinitselfisO(n).
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 212/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Restthefightremainsonlytominimizetheconstants.
upvote4
answeredApr3'12at6:59
downvote
share|improvethisanswer
ManojGumber
1,740930
addacomment|
publicstaticintmaxOrderedDiff(int[]A){
//A[x]A[y]|x>y
intmin=0,max=0;
intless=0;
for(inti=1;i<A.length;i++){
if(A[less]>A[i]){
less=i;
}
if(A[i]A[min]>A[max]A[min]||A[i]A[less]>A[max]A[min]){
max=i;
if(A[less]<A[min])
min=less;
}
}
returnmax>min?A[max]A[min]:1;
upvote0downvote }//maxOrderedDiff
TESTWITH:
publicstaticvoidmain(String[]args){
int[][]A={{3,7,1,4,2,4},{5,4,3,2,1},{4,3,2,2,3}};
for(int[]B:A)
System.out.format("%s::%d%n",Arrays.toString(B),maxOrderedDiff(B));
}
answeredApr4'12at1:28
share|improvethisanswer
kasavbere
2,77021949
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 213/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavacarraysalgorithmoraskyour
ownquestion.
asked 3yearsago
viewed 2432times
active 3yearsago
Lookingforajob?
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
BackendDeveloper
NewsInShorts
Noida,India/relocation
algorithmdatastructures
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
108PeopleChatting
JavaScript
1houragoKendallFrey
Awal
Luggage:
Octavian
Madara
uselesschien:
Caprica
ssube:
Garg:
1 Damiean:
Uchiha:
1 Six:1
PHP
1houragoPeeHaa
PeeHaa:
bwoebi:
Rafee:
NikiC:
ircmaxell:
Joe user3692125:
1 1 1 1 1 Watkins: 1
Related
874
InJava,howcanItestifanArraycontainsacertainvalue?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
30
Givenanarray,canIfindinO(n)thelongestrange,whoseendpointsarethegreatestvaluesintherange?
11313
Whyisprocessingasortedarrayfasterthananunsortedarray?
1
Givenunsortedarray,findi,jsuchthati<jandA[i]<A[j]inlineartimeandconstantspace
3
Findatargetvalueinanunsortedarrayofintegersbyperformingadditionsofintegers
1
findpredecessorofagivenelementfromanarray
1
Findingminimumandmaximuminarray
2
SymmetricDifferenceb/wunsortedarrays
0
Maximumgapinunsortedarray
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 214/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
HotNetworkQuestions
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Alarmclockprinting
Whyadding"incolour"whenreferringto"WizardofOz"?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
CanICultureBombfaraway?
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
Howtodrawsequenceofshapeswitharrowsandtext
Derivativeofadefiniteintegralissue
WhoinventedStarTreksideburnsandwhy?
Whycan'tanonabeliangroupbe75%abelian?
HowcanIcheckifmyfunctionprint/echo'ssomething?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Whydosocksstink?
Patchingabinarywithdd
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
HowdoIfacilitateafirsttimeAgileretrospective?
Canmathbesubjective?
Antiferromagneticordering
Whatistheoriginofthisphotoofanunexplodedbomb?
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
Whatwereshoesolesmadefrominpreviousages?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 215/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
howdoesFloat.toString()andInteger.toString()works?
Howcaniimplementanalgorithmtoconvertfloatorinttostring?Ifoundonelinkhttp://geeksforgeeks.org/forum/topic/amazoninterview
questionforsoftwareengineerdeveloper02yearsaboutalgorithms13
buticantunderstandthealgorithmgiventhere
upvote0down
votefavorite javaarrayalgorithms
askedMay12'11at14:38
editedMay12'11at14:45
share|improvethisquestion
ako
280248
Whathaveyoutriedsofar?RachelShallitMay12'11at14:40
1 Areyouaskinghowonemightimplementit,orhowtheJDKactuallyimplementsit?DilumRanatungaMay12'11at14:40
itsainterviewquestion,iwonttoimplemtmyownalgoakoMay12'11at14:44
integertostringismoresimple.fordoubletostringthisguidlinesmightbehelpful:javaDocszviadmMay25'11at19:27
addacomment|
4Answers
activeoldestvotes
thenumbers09aresequentialinmostcharacterencodingsotwiddlingwiththeintegralvalueofitwillhelphere:
intval;
Stringstr="";
while(val>0){
str=('0'+(val%10))+str;
upvote4down val/=10;
vote }
answeredMay12'11at14:52
share|improvethisanswer
ratchetfreak
28.2k21860
Thisexempleisfarbetterthantheother.Itissimple,itfocusandtheproblemandiseasytounderstand.NicolasBousquetMay12'11at
15:37
addacomment|
Here'sasampleofhowtodotheintegertostring,fromitIhopeyou'llbeabletofigureouthowtodothefloattostring.
publicStringintToString(intvalue){
StringBufferbuffer=newStringBuffer();
if(value<0){
buffer.append("");
}
//MAX_INTisjustover2billion,sostartbyfindingthenumberofbillions.
intdivisor=1000000000;
while(divisor>0){
intdigit=value/divisor;//integerdivision,sonoremainder.
if(digit>0){
buffer.append('0'+digit);
value=valuedigit*divisor;//subtractoffthevaluetozerooutthatdigit.
}
divisor=divisor/10;//thenextloopiterationshouldbeinthe10'splacetotheright
}
upvote }
3down
vote Thisisofcourse,veryunoptimized,butitgivesyouafeelforhowthemostbasicformattingisaccomplished.
Notethatthetechniqueof""+xisactuallyrewrittentobesomethinglike
StringBufferbuffer=newStringBuffer();
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 216/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
buffer.append("");
buffer.append(String.valueOf(x));
buffer.toString();
Sodon'tthinkthatwhatiswrittenis100%exactlyHOWitisdone,lookatisaswhatmusthappeninalargerviewofthings.
answeredMay12'11at14:51
share|improvethisanswer
EdwinBuck
38.6k14173
Intheeventthatsomeonetriestoswapoutcharactersetswithonethatdoesn'thaveit'sdigitssequentially(rememberthisisaninterviewquestion,nota
realworldproblem)youcanalwaysimplementthebuffer.append('0'+digit)withaswitchstatement,likesoswitch(digit){case0:
buffer.append("0");break;case1:buffer.append("1");break;...}EdwinBuckMay12'11at14:58
UsingStringBufferistotallyuselessasthejavacompilerwillreplacestringconcatenationwithoneanyway.NicolasBousquetMay12'11at15:36
@Nicolas,ThecompileronlyreplacesStringconcatenationwithaStringBufferintheeventthatalloftheconcatenationsoccurwithinthesamelocalized
1 block.So,System.out.println("("+x+","+y+")");worksjustfinebut,Stringx="";for(inti=0;i<5;i++){x=x+'0'+i;}won't
maintainabufferbetweenloopiterations.EdwinBuckMay12'11at19:34
addacomment|
Thegeneralideaistopickofftheleastsignificantdigitbytakingthenumberremainderten.Thendividethenumberby10andrepeat...untilyouare
leftwithzero.
Ofcourse,itisabitmorecomplicatedthanthat,especiallyinthefloatcase.
ifihaveasingledigitinintfomratthenineedtoinsertitintochar,howtoconvertinttochar?
upvote1down
Easy:
vote
intdigit=.../*0to9*/
charch=(char)('0'+digit);
answeredMay12'11at14:45
share|improvethisanswer
StephenC
311k25281588
1 agreed,butifihaveasingledigitinintfomratthenineedtoinsertitintochar,howtoconvertinttochar?akoMay12'11at14:46
thanks.........................................akoMay12'11at14:51
addacomment|
Well,youcanreadthecodeyourself.
answeredMay12'11at14:57
upvote1downvote
share|improvethisanswer
MikeBaranczak
4,9642250
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 217/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaarrayalgorithmsoraskyourown
question.
asked 4yearsago
viewed 636times
active 4yearsago
Lookingforajob?
ChiefSoftwareArchitectJava$100K
Crossover
Bengaluru,India/remote
eclipsenetbeans
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Linked
2
HowdoesInteger.toString()worksinternally?
Related
463
HowdoestheJavaforeachloopwork?
7
Integer.toString()
0
HowtofindthenumberofoccurencesofanumberinasortedArrayinO(logn)
3
array:convertindexofonedimensionalarraytoavectorindexofamultidimensionalarray
8
HowtofindthepermutationofasortinJava
11
Givenanarray[a1b2c3d4]convertto[abcd1234]
1
HowcanIbubblesortthis?
2
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 218/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
HowdoesInteger.toString()worksinternally?
2
HowtobreakaloopinJavawheretheinputsizeisnotpreviouslyspecified?
0
HowtocalculateO(logn)inbigOnotation?
HotNetworkQuestions
HowdoIfacilitateafirsttimeAgileretrospective?
Shouldmy(sequential)collectionstartatindex0orindex1?
HowcanIcheckifmyfunctionprint/echo'ssomething?
WhoinventedStarTreksideburnsandwhy?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Isturninggraphitecarbonintodiamondindustriallydoable?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
FindingoutifawordisanAnagramofanother
Removestaticobjectsfromanimagesequence
Howtogetearlyentryintomystictheurge?
Whyshouldakeybemadeexplicit?
Whycan'tanonabeliangroupbe75%abelian?
Wordfor"animals,includinghumans"?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Jumpingcarwithtoomanyamps?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
MementoVivereMomentumMori
ThenthTernary
ImageOpensasLayer0ratherthanBackground
HowdoIupgradefromGPLv2toGPLv3?
Multiplypurefunctionwithscalar
Packagetodonotes:HowcanIchangethetextcolor?
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
40Numbersin9Bytes
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 219/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Howtorepresentatriangleofintegers?
Thisaddresses"aspecificprogrammingproblem"fromOnTopic
IamworkingonaninterviewquestionfromAmazonSoftwareInterview
Thequestionis"Givenatriangleofintegers,findthepathofthelargestsumwithoutskipping."
Myquestionishowwouldyourepresentatriangleofintegers?
IlookedthisuponTriangleofIntegersandsawthatatriangleofintegerslookedsomethinglike
1
23
456
78910
1112131415
upvote4downvote Whatisthebestway(datastructure)torepresentsomethinglikethis?Myideawashavingsomethinglike
favorite
int[]r1={1};
int[]r2={2,3};
int[]r3={4,5,6};
int[]r4={7,8,9,10};
int[]r5={11,12,13,14,15};
Isthisthebestwaytorepresentthistriangleintegerstructure?Ithoughtaboutusinga2dimensionalmatrixstructurebutthosehavetohave
arraysofthesamesize.
javapythonalgorithmintegerint
askedFeb21at4:03
share|improvethisquestion
committedandroider
1,817416
4 wellyoucanuseaList<Integer[]>BabyFeb21at4:06
1 Ifyouwanttogetfancyandstupidatthesametime,youcouldusealeaningtree.JonFeb21at4:07
javaorpythonorboth?DnRFeb21at4:11
JustjavafornowcommittedandroiderFeb21at4:16
@Jonjongotthanksthatmakessense.committedandroiderFeb21at4:17
|show3morecomments
4Answers
activeoldestvotes
Youshouldputtheminlinearmemoryandaccessthemas:
inttriangular(introw){
returnrow*(row+1)/2+1;
}
int[]r={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
for(inti=0;i<n_rows;i++){
for(intj=0;j<=i;j++){
System.out.print(r[triangular(i)+j]+"");
}System.out.println("");
}
upvote1downvoteaccepted
row,column
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 220/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ifrow>column:
index=triangular(row)+column
Sinceit'sapredictablestructurethere'sanexpressionfortheoffsetofthebeginningofeachrow.Thiswillbethemostefficientway.
answeredFeb21at4:07
editedFeb21at13:21
share|improvethisanswer
ChristianSarofeen
1,53516
Solinearmemorymeaningarray?committedandroiderFeb21at4:26
Updatedforafullexample.ChristianSarofeenFeb21at13:21
addacomment|
Ithoughtaboutusinga2dimensionalmatrixstructurebutthosehavetohavearraysofthesamesize.
Notcorrect.
InJavayoucanusearraystorepresentnonrectangulardatastructurese.g.
int[][]triangle={{1},
{2,3},
upvote2 {4,5,6},
down {7,8,9,10},
vote {11,12,13,14,15}};
Itisanoption,thoughnotnecessarilythemostconvenientoption.
answeredFeb21at4:51
share|improvethisanswer
StephenC
311k25281588
Whatwouldbemoreconvenient?committedandroiderFeb21at7:32
Possiblyoneoftheothersolutionsproposedbytheotheranswers.Youcanmakeupyourownmind.StephenCFeb21at8:25
IcannotgiveyouaspecificansweronthatbecauseIhavenotconsideredtheimplicationsforthealgorithms,andtheireaseofimplementation.However,
I'mprettysurethatanyofthealternativeswillbeeasiertodealwiththanNdifferentnamed1Darrays...asinyoursamplecode.StephenCFeb22at
9:08
addacomment|
I'dusea2Darraywithguardbands.Intheexamplebelow,the0'srepresentinvalidentriesinthearray.Thetopandbottomrows,aswellastheleftmostand
rightmostcolumnsaretheguardbands.Theadvantageisthatyourpathfindingalgorithmcanwanderaroundthearraywithouthavingtoconstantlycheckfor
outofboundsarrayindices.
int[][]array=
{
{0,0,0,0,0,0,0},
{0,1,0,0,0,0,0},
upvote {0,2,3,0,0,0,0},
1down {0,4,5,6,0,0,0},
{0,7,8,9,10,0,0},
vote {0,11,12,13,14,15,0},
{0,0,0,0,0,0,0}
};
answeredFeb21at4:54
share|improvethisanswer
user3386109
12k21227
butwoudn'tallthose0stakeuptoomuchspace?committedandroiderFeb21at7:32
Howbigisthebiggesttriangle?user3386109Feb21at7:47
Questiondoesn'tsay.Sonostatedlimit,IguesscommittedandroiderFeb21at7:52
@committedandroiderWell,ifyougobeyond10,000rows,thenmaybetheextraspacetakenupbythe0smatters,otherwiseno.user3386109Feb21
at7:54
WhatIwasthinkingaboutwasjustusingonearrayandusingsomeformulalikewhatduskwuffsuggestedtoidentifythedifferentrowsofthetriangle.
Thatwayyousavespace?committedandroiderFeb21at8:00
|show4morecomments
Youdon'tneedtorepresentitatall!Thestartingnumberofrowr(startingat0)isgivenbytheexpression:
r*(r+1)/2+1
upvote0
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 221/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
downvote answeredFeb21at4:11
share|improvethisanswer
duskwuff
86.1k1187126
Soyourepresentthiswithonearray?committedandroiderFeb21at4:24
Ifyourarrayisliterallyjustthesenumbers,youdon'tneedanarrayatall.Youcanjustcalculatewhatthenumberatagivenpositionwillbewithout
storingitanywhere.duskwuffFeb21at4:40
@duskwuffhisarrayisnotjustthosenumbers.immibisFeb21at5:14
@duskwuffthatarraywasjustanexamplefromanotherthread.Isupposethearrayforthisproblemcantakeanyvalueincommittedandroider
Feb21at7:31
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavapythonalgorithmintegerintorask
yourownquestion.
asked 4monthsago
viewed 162times
active 4monthsago
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 222/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
LeadiOSDevloper
NewsInShorts
Noida,India/relocation
iosobjectivec
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Gettheweeklynewsletter!
Topquestionsand
answers
Important
announcements
Unanswered
questions
Signupforthenewsletter
Linked
0
Howtoprintatriangleofintegerswithnumberoflinesspecifiedbytheuser?
Related
111
WhatisthedifferencebetweenanintandanIntegerinJavaandC#?
1148
HowcanIrepresentan'Enum'inPython?
13
Minimizethesumoferrorsofrepresentativeintegers
529
Findanintegernotamongfourbilliongivenones
0
howtoaddownnumberrangeinjava
3
Java:SortintegerarraywithoutusingArrays.sort()
1
Howtofillgapsinasequenceofintegers,bychoosingthebestcomplementarysequence
0
IntegertoBoolean
1
JavaCharacterinStringtointeger
0
howtocreatepaginatorwithincrementsof5pagesindjango
HotNetworkQuestions
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Whatistheoriginofthepowericon?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
Packagetodonotes:HowcanIchangethetextcolor?
Removestaticobjectsfromanimagesequence
DoesaUSB3.0connectionrequireaUSB3.0cord?
Clientwantsfontaslogo
HowtodealwithaGMwhodoesnottelluseverything?
MementoVivereMomentumMori
Thetwopronunciationsof
PythonLabelExpression?ArcGIS10.3.1
Uncorrectedsamplestandarddeviationincorrelationcoefficient
ThenthTernary
Multiplypurefunctionwithscalar
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Antiferromagneticordering
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 223/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
howcanItaketotalminutesfromtime?
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Drawarrowinamindmap
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Whyadding"incolour"whenreferringto"WizardofOz"?
HowdoIupgradefromGPLv2toGPLv3?
ImageOpensasLayer0ratherthanBackground
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
NumberFormatExceptioninmycode
IwassolvingtheConnectedSetsproblemonAmazon'sInterviewStreetsitehttps://amazon.interviewstreet.com/challengesandmycodeworkedperfectlyfor
thepublicsampletestcasesprovidedbythesite,butI'mgettingaNumberFormatExceptionforthehiddentestcasesonline25.Hereisthepartofmycode
thatparsestheinput:
publicclassSolution
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 224/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
{
staticint[][]arr;
staticintnum=2;
staticintN;
staticStringoutput="";
publicstaticvoidmain(String[]args)throwsIOException
{
intT;
BufferedReaderreader=newBufferedReader(newInputStreamReader(System.in));
T=Integer.parseInt(reader.readLine());
inti,j,k;
for(i=0;i<T;i++)//theloopforeachofthe'T'testcases
{
N=Integer.parseInt(reader.readLine());//line25
arr=newint[N][N];
for(j=0;j<N;j++)//theloopsforstoringtheinput2Darray
{
for(k=0;k<N;k++)
{
arr[j][k]=Character.getNumericValue(reader.read());
reader.read();
}
}
Ispentalotoftimetryingtofindwhattheproblemis,butI'vebeenunsuccessfulatit.Thanksforyourhelpinadvance.
EDIT:Theproblemstatementisgivenasfollowsonthesite:
Givena2dmatrix,whichhasonly1sand0sinit.Findthetotalnumberofconnectedsetsinthatmatrix.
Explanation:Connectedsetcanbedefinedasgroupofcell(s)whichhas1mentionedonitandhaveatleastoneothercellinthatsetwithwhichtheysharethe
neighborrelationship.Acellwith1initandnosurroundingneighborhaving1initcanbeconsideredasasetwithonecellinit.Neighborscanbedefinedas
allthecellsadjacenttothegivencellin8possibledirections(i.eN,W,E,S,NE,NW,SE,SWdirection).Acellisnotaneighborofitself.
Inputformat:FirstlineoftheinputcontainsT,numberoftestcases.ThenfollowTtestcases.Eachtestcasehasgivenformat.N[representingthedimension
ofthematrixNXN].FollowedbyNlines,withNnumbersoneachline.
Outputformat:Foreachtestcaseprintoneline,numberofconnectedcomponentithas.
SampleInput:
0010
1010
0100
1111
4
upvote0
down 1001
vote
favorite 0000
0110
1001
10011
00100
00000
11111
00000
00100100
10000001
00100101
01000100
10000000
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 225/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
00110110
10110110
00000000
Sampleoutput:
Constraint:
0<T<6
0<N<1009
Notethattheabovesampletestcasesworkedonmycode.Thehiddentestcasesgavetheexception.
javanumberformatexception
askedMar14'14at13:05
editedMar14'14at13:34
share|improvethisquestion
Ricky
377
addacomment|
4Answers
activeoldestvotes
Okay,soImodifiedmyprogramtoincorporateLeosLiterak'ssuggestiontousetrim()andthenewcodeisasfollows:
publicclassSolution
{
staticint[][]arr;
staticintnum=2;
staticintN;
staticStringoutput="";
publicstaticvoidmain(String[]args)throwsIOException
{
intT;
BufferedReaderreader=newBufferedReader(newInputStreamReader(System.in));
T=Integer.parseInt(reader.readLine().trim());
inti,j,k;
for(i=0;i<T;i++)
{
N=Integer.parseInt(reader.readLine().trim());
upvote1down arr=newint[N][N];
voteaccepted
for(j=0;j<N;j++)
{
String[]temp=reader.readLine().trim().split("");
for(k=0;k<N;k++)
{
arr[j][k]=Integer.parseInt(temp[k]);
}
}
Soinsteadofreadingeachcharacterintheinputmatrixandconvertingittoanintegerandstoring,Inowreadtheentirelineandtrimandsplitthe
stringandconverteachsubstringintoanintegerandstoreinmyarray.
answeredMar14'14at14:33
editedMar14'14at14:39
share|improvethisanswer
Ricky
377
addacomment|
Copiedfromcomments:trytoremoveallwhitecharacterslikespaces,tabulatorsetc.Thesecharactersarenotprohibitedbygoaldefinitionbutthey
cannotbeparsedtonumber.Youmusttrimthemfirst.
upvote1
answeredMar14'14at15:32
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 226/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
downvote
share|improvethisanswer
LeosLiterak
2,55441646
addacomment|
Checkifitsnumberbeforeparsetoint.
Character.isNumber()
upvote0downvote answeredMar14'14at14:47
share|improvethisanswer
MSr
100111
addacomment|
T=Integer.parseInt(reader.readLine())Thiswheretheproblem.whenusertrytogivestringanditconvertintointegerandrunthroughloop?Foreg:if
usergives'R'ascharthanhowtheintegerconversioncanhappenandwillthelooprunfurther??Noright.
upvote0 editedJun17'14at9:16 answeredMar14'14at13:25
downvote
share|improvethisanswer
Benjamin Prabhu
9,0321371131 1138
DidyouevenopenthelinkIputonmyquestionorreadthecommentsonmyquestion?Secondly,theerrorisnotevenonthelineT=
Integer.parseInt(reader.readLine()).Itsonline25,whichisappropriatelycommented.RickyMar14'14at13:29
Well,IopenedthelinkbutitrequestedregistrationandIamnotinterestedinAmazoninterview.Itwouldbegoodtopostcompletequestion.Leos
LiterakMar14'14at13:30
@LeosLiterakI'lleditmyquestiontoputthequestion.Pleasewaitforamoment.RickyMar14'14at13:31
@LeosLiterakEditsmade.RickyMar14'14at13:36
Whataboutspaces?Trytotrimthemfirst.LeosLiterakMar14'14at13:58
|show4morecomments
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 227/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavanumberformatexceptionorask
yourownquestion.
asked 1yearago
viewed 92times
active 1yearago
Lookingforajob?
QualityAssuranceEngineer
recruiterbox.com
Bengaluru,India/relocation
seleniumseleniumwebdriver
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
108PeopleChatting
JavaScript
1houragoKendallFrey
Awal
Luggage:
Octavian
Madara
uselesschien:
Caprica
ssube:
Garg:
1 Damiean:
Uchiha:
1 Six:1
PHP
1houragoPeeHaa
PeeHaa:
bwoebi:
Rafee:
NikiC:
ircmaxell:
Joe user3692125:
1 1 1 1 1 Watkins: 1
Related
2
parseDoubleinJavaresultstoNumberFormatException
0
EncounteringNumberFormatException
1
GettingaNumberFormatException
0
CatchingtheNumberFormatException
1
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 228/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
NumberFormatExceptioninDouble.parseDouble()
1
NumberFormatExceptionerror
0
NumberFormatExceptionwithcalculator
0
NumberFormatExceptioninStars.java
1
WhymycodesthrowNumberFormatException?
0
JavaNumberFormatExceptionLegacyCode
HotNetworkQuestions
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
DoesaUSB3.0connectionrequireaUSB3.0cord?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
MementoVivereMomentumMori
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
SixMusicalFriends
40Numbersin9Bytes
WhydosomepeoplerefertoLinuxasGNU/Linux?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
NineTallMenAreStandingTall
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Removestaticobjectsfromanimagesequence
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Patchingabinarywithdd
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Passfilenamefrombashtopython
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
Whatistheoriginofthisphotoofanunexplodedbomb?
Whyadding"incolour"whenreferringto"WizardofOz"?
WhatdoesitmeanifanACmotorhastwovoltageratings?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
RollmyD&Dcharacter'sabilityscores
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 229/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Quickestwaytofindmissingnumberinanarrayofnumbers
Ihaveanarrayofnumbersfrom1to100(bothinclusive).Thesizeofthearrayis100.Thenumbersarerandomlyaddedtothearray,butthereisone
randomemptyslotinthearray.Whatisthequickestwaytofindthatslotaswellasthenumberthatshouldbeputintheslot?AJavasolutionis
preferable.
upvote41
downvote javaarraysalgorithm
favorite editedOct16'12at14:08 askedJan21'10at23:27
26
share|improvethisquestion
SchmitzIT Thunderhashy
4,77892648 1,69092743
There'snowaythisisn'thomework.Attheleast,it'salittlebrainteaserwhosepurposeistomakeyouthinkandlearn,soIneverunderstandwhywe
9
thinkithelpspeopleforustojusthandthemthecompleteanswersonsilverplatter.KevinBourrillionJan22'10at0:34
ActuallyIwasknowingonesolutionfindthesumofnumbersfrom1100andthensubtractitfromthesumofnumbersinarraytogetthemissing
3
number.Iaminterestedtoseeiftherecanbeanyotherinterestingsolutions.ThunderhashyJan22'10at0:44
2 Whatisthevalueof'empty'?0?1?MAKJan25'10at21:02
Emptyslotcontainsnull.ThunderhashyJan25'10at22:15
2 IwasaskedthisonaninterviewFooBahJul20'11at18:39
|show2morecomments
21Answers
activeoldestvotes
YoucandothisinO(n).Iteratethroughthearrayandcomputethesumofallnumbers.Now,sumofnaturalnumbersfrom1toN,canbeexpressedas
Nx(N+1)/2.InyourcaseN=100.
SubtractthesumofthearrayfromNx(N+1)/2,whereN=100.
Thatisthemissingnumber.Theemptyslotcanbedetectedduringtheiterationinwhichthesumiscomputed.
//willbethesumofthenumbersinthearray.
intsum=0;
intidx=1;
for(inti=0;i<arr.length;i++){
if(arr[i]==0){
upvote70 idx=i;
downvote }else{
accepted sum+=arr[i];
}
}
//thetotalsumofnumbersbetween1andarr.length.
inttotal=(arr.length+1)*arr.length/2;
System.out.println("missingnumberis:"+(totalsum)+"atindex"+idx);
answeredJan21'10at23:32
editedJan22'10at1:16
share|improvethisanswer
Arnkrishn
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 230/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
10.6k3275106
Youcouldmakeanoteofanyindexbeingzerowhileiterationthroughthefirsttime.ThorbjrnRavnAndersenJan21'10at23:39
Summationisprimetointegeroverflow,thefollowingapproachshouldtakecareofthat:XORallthegivennumbers,callthisX1XORall
14 numbersfrom1to100,callthisX2X1XORX2shouldbethemissingnumber,sincealltherepeatednumbersXORaway.AbhinavSharma
Aug5'11at9:23
@AbhinavSharmaTrue,butitalsoworkswithsummationifoverflowoccurs,providedthatoverflowwrapsnicely,whichisguaranteedinJava,
8
andinCforunsignedtypes.DanielFischerDec16'11at11:47
1 @DanielFischerVerycoolresponse!Ilikeyourthinking.)brimboriumNov14'12at11:13
inthiscase,totalshouldbe(arr.length+1)*(arr.length+2)/2tosatisfyn*(n+1)/2becauseformostlanguage,arrayindexstartsfrom0,and
1
weneedtoincrementlengthby1dvlimanJan6'14at2:07
|show2morecomments
longn=100;
inta[]=newint[n];
//XORofallnumbersfrom1ton
//n%4==0>n
//n%4==1>1
//n%4==2>n+1
//n%4==3>0
longxor=(n%4==0)?n:(n%4==1)?1:(n%4==2)?n+1:0;
upvote13down for(longi=1;i<=n;i++)
vote {
xor=xor^a[i];
}
//Missingnumber
System.out.println(xor);
answeredJan27'12at9:14
share|improvethisanswer
prabhakcv
13113
5 Thisanswerlooksinteresting,butitneedsabitmoreexplanation.gsingh2011Jan27'13at6:36
Xorofnumberwithitselfiszero.Soifwetakexorofallnumbersinarraywithallnumberfrom1ton,wewillbeleftwithonlythemissing
2
numberadiJul6'13at7:56
4 Please,cansomeoneexplainwhytheinitialvalueneedstoinvolveamoduloby4?jschankApr23'14at1:55
addacomment|
ThiswasanAmazoninterviewquestionandwasoriginallyansweredhere:Wehavenumbersfrom1to52thatareputintoa51numberarray,what's
thebestwaytofindoutwhichnumberismissing?
Itwasanswered,asbelow:
1)Calculatethesumofallnumbersstoredinthearrayofsize51.
upvote11 2)Subtractthesumfrom(52*53)/2Formula:n*(n+1)/2.
downvote
Itwasalsobloggedhere:SoftwareJobInterviewQuestion
editedJul6'13at6:33 answeredDec16'11at11:34
share|improvethisanswer
Frxstrem bchetty
7,19512158 1,5521719
Itriedthiswith1,2,3and5asthesequence.(i.e.4isthemissingnumber).Thesumofthevaluesis11soidid((11*12)/2)11andiget55.Why
aminotgetting4?ziggyAug5'12at20:32
nisthenumberofnumbers.So,itshouldbe5*(5+1)/2=15...and15(1+2+3+5)=4.bchettyAug6'12at8:46
ahok..gotit.Thanks:)ziggyAug6'12at11:51
addacomment|
WecanuseXORoperationwhichissaferthansummationbecauseinprogramminglanguagesifthegiveninputislargeitmayoverflowandmay
givewronganswer.
BeforegoingtothesolutionAxorA=0soifwexortwoidenticalnumberthevalueisZero.
//Assumingthatthearraycontains99distinctintegersbetween1..99andemptyslotvalueiszero
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 231/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
for(inti=0;i<100;i++)
{
if(ARRAY[i]!=0)
upvote8down XOR^=ARRAY[i];
vote XOR^=(i+1);
}
returnXOR;
Xoring[1..n]withtheelementspresentinthearraycancelstheidenticalnumbersattheendwewillgetthemissingnumber.
answeredJul6'13at6:18
share|improvethisanswer
dungeonHunter
3,78672955
addacomment|
5050(sumofallvaluesinthearray)=missingnumber
intsum=0;
intidx=1;
for(inti=0;i<arr.length;i++){
if(arr[i]==0)idx=i;elsesum+=arr[i];
upvote4 }
downvote System.out.println("missingnumberis:"+(5050sum)+"atindex"+idx);
answeredJan21'10at23:32
editedJan21'10at23:46
share|improvethisanswer
jspcal
23.5k33549
1 whatis5050?thiscodedoesn'tseemtoworkgivenanarraycontaining1,2,0,4,5.core_proSep19'12at17:19
@core_proThesizeofyourexamplearrayis5,not100astheOPspecified.5050isthesumofallintegersfrom1to100andworksforarrayswith
4
100elements.Sotheequivalentwouldbe15foranarrayofsize5.CodesInChaosFeb5'13at17:08
addacomment|
Hereisasimpleprogramtofindthemissingnumbersinanintegerarray
ArrayList<Integer>arr=newArrayList<Integer>();
inta[]={1,3,4,5,6,7,10};
intj=a[0];
for(inti=0;i<a.length;i++)
{
if(j==a[i])
{
j++;
continue;
}
else
{
arr.add(j);
upvote3downvote i;
j++;
}
}
System.out.println("missingnumbersare");
for(intr:arr)
{
System.out.println(""+r);
}
editedFeb25at2:02 answeredMay9'13at8:30
share|improvethisanswer
abatishchev Beena
48.9k45181311 311
addacomment|
Thisisc#butitshouldbeprettyclosetowhatyouneed:
intsumNumbers=0;
intemptySlotIndex=1;
for(inti=0;i<arr.length;i++)
{
if(arr[i]==0)
emptySlotIndex=i;
upvote2downvote sumNumbers+=arr[i];
}
intmissingNumber=5050sumNumbers;
answeredJan21'10at23:34
share|improvethisanswer
MartinBooth
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 232/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
5,8641320
addacomment|
Well,useabloomfilter.
intfindmissing(intarr[],intn)
{
longbloom=0;
inti;
for(i=0;i<;n;i++)bloom+=1>>arr[i];
for(i=1;i<=n,(bloom<<i&1);i++);
upvote2downvote returni;
}
answeredJan13'12at7:18
share|improvethisanswer
user1147136
312
addacomment|
Thesolutionthatdoesn'tinvolverepetitiveadditionsormaybethen(n+1)/2formuladoesn'tgettoyouataninterviewtimeforinstance.
Youhavetouseanarrayof4ints(32bits)or2ints(64bits).Initializethelastintwith(1&~(1<<31))>>3.(thebitsthatareabove100aresetto1)Oryoumaysetthebit
usingaforloop.
1. Gothroughthearrayofnumbersandset1forthebitpositioncorrespondingtothenumber(e.g.71wouldbesetonthe3rdintonthe7thbitfromlefttoright)
2. Gothroughthearrayof4ints(32bitversion)or2ints(64bitversion)
publicintMissingNumber(inta[])
{
intbits=sizeof(int)*8;
inti=0;
intno=0;
while(a[i]==1)//thismeansa[i]'sbitsareallsetto1,thenumbersisnotinsidethis32numberssection
up {
vote no+=bits;
1 i++;
down }
returnno+bitsMath.Log(~a[i],2);//applyNOT(~)operatortoa[i]toinvertallbits,andgetanumberwithonlyonebitset(2atthepowerof
vote }
Example:(32bitversion)letssaythatthemissingnumberis58.Thatmeansthatthe26thbit(lefttoright)ofthesecondintegerissetto0.
Thefirstintis1(allbitsareset)so,wegoaheadforthesecondoneandaddto"no"thenumber32.Thesecondintisdifferentfrom1(abitisnotset)so,byapplyingtheNO
operatortothenumberweget64.Thepossiblenumbersare2atthepowerxandwemaycomputexbyusinglogonbase2inthiscasewegetlog2(64)=6=>32+32
Hopethishelps.
answeredJan1'11at4:59
editedJan1'11at6:05
share|improvethisanswer
MARIU5
112
addacomment|
Ithinktheeasiestandpossiblythemostefficientsolutionwouldbetoloopoverallentriesanduseabitsettorememberwhichnumbersareset,andthen
testfor0bit.Theentrywiththe0bitisthemissingnumber.
upvote0 answeredOct19'10at5:02
downvote
share|improvethisanswer
TusharGupta
990819
addacomment|
//ArrayisshortedandifwritinginC/C++thinkofXORimplementationsinjavaasfollows.
intnum=1;
for(inti=1;i<=100;i++){
num=2*i;
if(arr[num]==0){
System.out.println("index:"+i+"Arrayposition:"+num);
break;
}
elseif(arr[num1]==0){
System.out.println("index:"+i+"Arrayposition:"+(num1));
upvote0downvote break;
}
}//useRabbitandtortoiserace,movethedanglingindexfaster,
//learntfromAlogithimica,Ameerpet,hyderbad**
answeredDec12'10at12:33
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 233/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
share|improvethisanswer
AshisKumar
91
addacomment|
Ifthearrayisrandomlyfilled,thenatthebestyoucandoalinearsearchinO(n)complexity.However,wecouldhaveimprovedthecomplexitytoO(logn)
bydivideandconquerapproachsimilartoquicksortaspointedbygirigiventhatthenumberswereinascending/descendingorder.
upvote0 answeredJun15'11at19:32
downvote
share|improvethisanswer
Moses
91
Thatdoesn'tanswerhowtofindoutwhichnumberismissing.SentryMay9'13at8:42
addacomment|
ThisProgramfindsmissingnumbers
<?php
$arr_num=array("1","2","3","5","6");
$n=count($arr_num);
for($i=1;$i<=$n;$i++)
{
if(!in_array($i,$arr_num))
{
upvote0down array_push($arr_num,$i);print_r($arr_num);exit;
vote }
}
?>
answeredJul19'11at13:14
share|improvethisanswer
Nitesh
91
ThisanswershouldhavebeenfiledunderPHP.ThequestionisfiledunderJAVA.Yetitcanstayheresinceatruealgorithmisalwayssyntax
independent:)AnkurKumarMar1'13at19:33
addacomment|
Onethingyoucoulddoissortthenumbersusingquicksortforinstance.Thenuseaforlooptoiteratethroughthesortedarrayfrom1to100.Ineachiteration,
youcomparethenumberinthearraywithyourforloopincrement,ifyoufindthattheindexincrementisnotthesameasthearrayvalue,youhavefoundyour
missingnumberaswellasthemissingindex.
upvote
0down answeredFeb5'13at17:02
vote
share|improvethisanswer
Stranger
3441729
addacomment|
NowI'mnowtoosharpwiththeBigOnotationsbutcouldn'tyoualsodosomethinglike(inJava)
for(inti=0;i<numbers.length;i++){
if(numbers[i]!=i+1){
System.out.println(i+1);
}
}
wherenumbersisthearraywithyournumbersfrom1100.Frommyreadingofthequestionitdidnotsaywhentowriteoutthemissingnumber.
upvote0downvote
AlternativelyifyouCOULDthrowthevalueofi+1intoanotherarrayandprintthatoutaftertheiteration.
Ofcourseitmightnotabidebythetimeandspacerules.AsIsaid.IhavetostronglybrushuponBigO.
answeredFeb20'13at22:21
share|improvethisanswer
Sayro
91
TheOPsaidthatthenumbersinthearraycanbeunsortedSentryMay9'13at8:41
addacomment|
Belowisthesolutionforfindingallthemissingnumbersfromagivenarray:
publicclassFindMissingNumbers{
/**
*Thefunctionprintsallthemissingnumbersfrom"n"consecutivenumbers.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 234/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
*Thenumberofmissingnumbersisnotgivenandallthenumbersinthe
*givenarrayareassumedtobeunique.
*
*Asimilarapproachcanbeusedtofindallnounique/uniquenumbersfrom
*thegivenarray
*
*@paramn
*totalcountofnumbersinthesequence
*@paramnumbers
*isanunsortedarrayofallthenumbersfrom1nwithsome
*numbersmissing.
*
*/
publicstaticvoidfindMissingNumbers(intn,int[]numbers){
if(n<1){
return;
}
byte[]bytes=newbyte[n/8];
intcountOfMissingNumbers=nnumbers.length;
if(countOfMissingNumbers==0){
return;
}
for(intcurrentNumber:numbers){
intbyteIndex=(currentNumber1)/8;
intbit=(currentNumberbyteIndex*8)1;
//Updatethe"bit"inbytes[byteIndex]
intmask=1<<bit;
bytes[byteIndex]|=mask;
}
for(intindex=0;index<bytes.length2;index++){
if(bytes[index]!=128){
for(inti=0;i<8;i++){
upvote0downvote if((bytes[index]>>i&1)==0){
System.out.println("Missingnumber:"+((index*8)+i+1));
}
}
}
}
//Lastbyte
intloopTill=n%8==0?8:n%8;
for(intindex=0;index<loopTill;index++){
if((bytes[bytes.length1]>>index&1)==0){
System.out.println("Missingnumber:"+(((bytes.length1)*8)+index+1));
}
}
publicstaticvoidmain(String[]args){
List<Integer>arrayList=newArrayList<Integer>();
intn=128;
intm=5;
for(inti=1;i<=n;i++){
arrayList.add(i);
}
Collections.shuffle(arrayList);
for(inti=1;i<=5;i++){
System.out.println("Removing:"+arrayList.remove(i));
}
int[]array=newint[nm];
for(inti=0;i<(nm);i++){
array[i]=arrayList.get(i);
}
System.out.println("Arrayis:"+Arrays.toString(array));
findMissingNumbers(n,array);
}
editedOct26'14at22:24 answeredOct26'14at17:17
share|improvethisanswer
bummi BhumikThakkar
21.2k82756 312
addacomment|
Letssayyouhavenas8,andournumbersrangefrom08forthisexamplewecanrepresentthebinaryrepresentationofall9numbersasfollows000000010010
001101000101011001111000
intheabovesequencethereisnomissingnumbersandineachcolumnthenumberofzerosandonesmatch,howeverassoonasyouremove1valueletssay3we
getainbalanceinthenumberof0'sand1'sacrossthecolumns.Ifthenumberof0'sinacolumnis<=thenumberof1'sourmissingnumberwillhavea0atthis
bitposition,otherwiseifthenumberof0's>thenumberof1'satthisbitpositionthenthisbitpositionwillbea1.Wetestthebitslefttorightandateachiteration
wethrowawayhalfofthearrayforthetestingofthenextbit,eithertheoddarrayvaluesortheevenarrayvaluesarethrownawayateachiterationdependingon
whichbitwearedeficienton.
ThebelowsolutionisinC++
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 235/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
intgetMissingNumber(vector<int>*input,intbitPos,constintstartRange)
{
vector<int>zeros;
vector<int>ones;
intmissingNumber=0;
//basecase,assumeemptyarrayindicatingstartvalueofrangeismissing
if(input>size()==0)
returnstartRange;
//ifthebitpositionbeingtestedis0addtothezero'svector
//otherwisetotheonesvector
for(unsignedinti=0;i<input>size();i++)
{
intvalue=input>at(i);
if(getBit(value,bitPos)==0)
zeros.push_back(value);
else
up ones.push_back(value);
vote }
0
down //throwawayeithertheoddorevennumbersandtest
//thenextbitposition,buildthemissingnumber
vote //fromrighttoleft
if(zeros.size()<=ones.size())
{
//missingnumberiseven
missingNumber=getMissingNumber(&zeros,bitPos+1,startRange);
missingNumber=(missingNumber<<1)|0;
}
else
{
//missingnumberisodd
missingNumber=getMissingNumber(&ones,bitPos+1,startRange);
missingNumber=(missingNumber<<1)|1;
}
returnmissingNumber;
}
Ateachiterationwereduceourinputspaceby2,i.eN,N/2,N/4...=O(logN),withspaceO(N)
//Testcases
[1]whenmissingnumberisrangestart
[2]whenmissingnumberisrangeend
[3]whenmissingnumberisodd
[4]whenmissingnumberiseven
answeredJan16at17:04
editedJan16at17:25
share|improvethisanswer
gilla07
512
addacomment|
Onasimilarscenario,wherethearrayisalreadysorted,itdoesnotincludeduplicatesandonlyonenumberismissing,itispossibletofindthis
missingnumberinlog(n)time,usingbinarysearch.
publicstaticintgetMissingInt(int[]intArray,intleft,intright){
if(right==left+1)returnintArray[right]1;
intpivot=left+(rightleft)/2;
if(intArray[pivot]==intArray[left]+(intArray[right]intArray[left])/2(rightleft)%2)
returngetMissingInt(intArray,pivot,right);
else
returngetMissingInt(intArray,left,pivot);
upvote0 }
downvote publicstaticvoidmain(Stringargs[]){
int[]array=newint[]{3,4,5,6,7,8,10};
intmissingInt=getMissingInt(array,0,array.length1);
System.out.println(missingInt);//itprints9
}
answeredMay10at7:36
editedMay10at7:45
share|improvethisanswer
KonstantinosChalkias
1,04448
addacomment|
Thisisnotasearchproblem.Theemployeriswonderingifyouhaveagraspofachecksum.Youmightneedabinaryorforlooporwhateverifyouwerelooking
formultipleuniqueintegers,butthequestionstipulates"onerandomemptyslot."Inthiscasewecanusethestreamsum.Thecondition:"Thenumbersare
randomlyaddedtothearray"ismeaninglesswithoutmoredetail.Thequestiondoesnotassumethearraymuststartwiththeinteger1andsotoleratewiththe
offsetstartinteger.
int[]test={2,3,4,5,6,7,8,9,10,12,13,14};
/*getthemissinginteger*/
intmax=test[test.length1];
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 236/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
intmin=test[0];
up intsum=Arrays.stream(test).sum();
vote0 intactual=(((max*(max+1))/2)min+1);
down //Find:
vote
//themissingvalue
System.out.println(actualsum);
//theslot
System.out.println(actualsummin);
Successtime:0.18memory:320576signal:0
answeredMay10at7:15
editedMay11at14:27
share|improvethisanswer
Radio
469212
addacomment|
Anotherhomeworkquestion.Asequentialsearchisthebestthatyoucando.AsforaJavasolution,considerthatanexerciseforthereader.:P
answeredJan21'10at23:31
upvote2downvote
share|improvethisanswer
MickSharpe
1,721198
addacomment|
Quicksortisthebestchoicewithmaximumefficiency....
answeredJan21'10at23:33
upvote5downvote
share|improvethisanswer
giri
7,3393592142
actuallyifyouusequicksortyougetO(nlogn).performingarealalgorithmwithyourmindgivesyouO(n)tXKMay2'12at13:01
1 Nopeit'snot.ThereisanO(n)solution...brimboriumNov14'12at11:19
addacomment|
protectedbyCommunityApr28'14at5:41
Thankyouforyourinterestinthisquestion.Becauseithasattractedlowqualityanswers,postingananswernowrequires10reputationonthissite.
Wouldyouliketoansweroneoftheseunansweredquestionsinstead?
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaarraysalgorithmoraskyourown
question.
asked 5yearsago
viewed 89541times
active 2monthsago
Lookingforajob?
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 237/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Linked
6
Trickyalgorithmquestion
0
DesignanO(n)algorithmforfindonenumbernotwithinrange[0,n1]
3
Findamissingnumberinanintegerarray
1
AlgorithmsProgramming
5
Fastestwaytofind2missingnumbersinanarray
0
Mostefficientwayoffindingmissingintegerinarray
0
TimecomplexityO(n)forfindingmissingnumber?
0
Howtodynamicallygrabthefirstavailablenumberinaloop?
Related
1368
CreateArrayList(ArrayList<T>)fromarray(T[])
874
InJava,howcanItestifanArraycontainsacertainvalue?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
2
Fastestwaytofindifintarraycontainsanumber
5
Fastestwaytofind2missingnumbersinanarray
11313
Whyisprocessingasortedarrayfasterthananunsortedarray?
2450
Pairsocksfromapileefficiently?
1
Findingmissingnumbersinadistributedarraysystem
54
Fasteralgorithmtofinduniqueelementbetweentwoarrays?
2
Findmaximumproductof3numbersinanarray
HotNetworkQuestions
ThenthTernary
WhoinventedStarTreksideburnsandwhy?
Justifyingsuboptimalresearchqualitybylackofsupervision
Howtogetearlyentryintomystictheurge?
HowtodealwithaGMwhodoesnottelluseverything?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Shouldmy(sequential)collectionstartatindex0orindex1?
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Howtoprotectaspaceelevatoragainstterrorism
Needtostartareligionwithapredefinedselfdestruct
Troublewithterminatinga<apex:pageBlockSection>
Passfilenamefrombashtopython
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
MementoVivereMomentumMori
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Whatis`$?`?Isitavariable?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Functionsthataretheirowninversion.
LeapyearcheckinJava
Whatisatemporarysolutionforadamagedcarbody?
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
Removestaticobjectsfromanimagesequence
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 238/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Searchingtwoarraysformatches,noextramemory
IhadaninterviewtheotherdaywithAmazon,andaquestiontheyaskedmewaspertainingtothefollowingproblem.
Given2integerarrays,containinganynumberofelementsbothpositiveandnegative,findnumbersthatappearinbotharrays.
IwasabletosolvethisproblemveryeasilywithHashMapssoitwouldhaveO(n)computationalcomplexity,butunfortunatelythiswillalsohaveO(n)
spacecomplexity.Thiscouldbedonewithnoextramemorybyiteratingthroughallelementsineacharray,butthiswouldbeO(n^2).
Theinterviewer,afterIfinishedexplainingtheHashMapmethod,askedifIcouldthinkofamethodthatwouldbeO(n)computationally,butwouldnotuse
anyextramemory.Icouldnotthinkofanyonthefly,andhavenotbeenabletofindasolutionforthis.Isthereawayoffindingthesevalueswithout
usingextramemory,inlineartime?
Note:IhavepostedthisquestiononCareerCup,buteveryoneontheredoesnotseemtogettheconceptthatIneedittonotuseextraspace,andthatithas
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 239/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
tobeO(n)computationally.
HereisthecodeIusedduringtheinterview.Itworks,butjustisnotO(1)forspace.
importjava.util.*;
publicclassArrayFun{
publicstaticvoidmain(String[]args){
int[]a={1,2,3,4};
int[]b={2,5,6,7,3,2,2,2,2,1,2,2,2,2};
ArrayList<Integer>matches=ArrayFun.findMatches(a,b);
for(inti=0;i<matches.size();++i){
System.out.println(matches.get(i));
}
upvote15 }
downvote
favorite publicstaticArrayList<Integer>findMatches(int[]a,int[]b){
6 HashMap<Integer,Integer>map=newHashMap<Integer,Integer>();
ArrayList<Integer>matches=newArrayList<Integer>();
for(inti=0;i<a.length;++i){
map.put(a[i],0);
}
for(inti=0;i<b.length;++i){
if(map.get(b[i])!=null&&map.get(b[i])==0){
map.put(b[i],1);
matches.add(b[i]);
}
}
returnmatches;
}
}
Thiscodewillreturn
1,2,3
EDIT:alsowhenIsaynoadditionalspace,andO(1),Iamkindofusingtheminterchangeably.BynoadditionalspaceImeansmallplaceholdervariables
arefinebutallocatingnewarraysisnot.
javaarraysalgorithm
askedNov8'12at21:27
editedNov8'12at23:33
share|improvethisquestion
MZimmerman6
3,50962052
YoucandoitinO(nlogn)withnoextraspacebysortingbotharraysinplace...that'sprobablynotwhattheywant,thoughdurron597Nov8'12at
6
21:31
Thisispossibleonlywhenthetwoarraysaresorted.Itisnotpossibleotherwise.dasblinkenlightNov8'12at21:32
Iassumethatbotharrayswerenotsorted.Isthisso?juan.facorroNov8'12at21:33
@durron597Thereisnosortingmethodthisefficientthatwon'tuseextraspace(eitherheaporstack).Also,O(nlogn)isthetypicalcase,butthe
worstcaseisusuallyO(n2).MarkoTopolnikNov8'12at21:40
@MarkoTopolnik:Randomizedquicksortisprettygood.ObviouslyallquicksortalgorithmshaveaworstcaseofO(n^2)durron597Nov8'12at
21:43
|show2morecomments
4Answers
activeoldestvotes
ThereisnoO(1)spacemethodforfindingtheintersectionoftwounsortedsetsinO(n)time.
Foradatatypewithanunlimitedrange,theminimumsortingpriceisO(nlnn).
ForadatatypewithalimitedrangeradixsortprovidestheabilitytodoaninplaceradixsortinO(nlnn'n")time,wherenisthesizeofthedata,n'isthe
numberofvaluesthatcanberepresented,andn"hastodowiththecostofcheckingwhethertwovaluesareinthesameradixgroup.Then"timepricecan
bedroppedinreturnforanO(lnn)spaceprice.
upvote7
downvote Inthespecialcaseof32bitintegers,n'is2^32andn"is1,sothiswouldcollapsetoO(n)andprovideawinningsolutionformultibillionrecordsets.
accepted
Forintegersofunlimitedsize,n'andn"precludeanO(n)timesolutionviaradix.
answeredNov8'12at21:33
editedNov20'12at19:37
share|improvethisanswer
MelNicholson
2,627321
thatiswhatmyconclusionwas.Butwhywouldtheyaskmetotryitiftherewasn't?MZimmerman6Nov8'12at21:35
7 Toseeifyouknewthatdurron597Nov8'12at21:35
MaybetheywantedtoseeifyouwouldtrytoB.S.whenyoudidn'tknowtheanswer,orwhetheryoucouldgiveadefinitive"impossible"answer.
2
MelNicholsonNov8'12at21:38
1 Iwouldagreeifanysortinghastobedonebycomparisonsort.However,ifthearraysareJavaintwearenotlimitedtocomparisonsort.Patricia
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 240/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ShanahanNov9'12at2:17
@MZimmerman6Thequestionmayhavebeentoseeifyouknowthatthe\Omega(nlogn)minimumtimeforsortingonlyappliestocomparison
sorts.IfyouhavealimitedrangestructuredtypesuchasJavaint,thereareothersortsthatareO(n).Inparticular,seetheinplaceradixsortinmy
answer.PatriciaShanahanNov9'12at16:12
|show3morecomments
Thekeyistosortthetwoarraysinplace.Ididasearchfor"inplaceradixsort",andfoundInPlaceRadixSort.Ibelievetheproblemissolvable,atleast
forJavaint[],byapplyingthoseideastosorteacharray,bitbybit,thendoingtheobviousscan.
Incidentally,Ithinkthecorrectoutputfortheprobleminthequestioncodeis1,2,3.
Hereismyimplementation,basedontheanswerstothereferencedquestion:
publicclassArrayMatch{
publicstaticvoidmain(String[]args){
int[]a={4,1,2,3,4};
int[]b={2,5,6,7,3,2,2,2,2,1,2,2,2,2};
System.out.print("Originalproblem");
printMatches(a,b);
System.out.println();
int[]a1={4,1,1234,2,3,4,Integer.MIN_VALUE};
int[]b1={1234,2,5,6,7,3,2,2,2,2,1,2,2,2,2,Integer.MIN_VALUE,Integer.MAX_VALUE};
System.out.print("Withnegatives");
printMatches(a1,b1);
System.out.println();
//Printallmatchingelementsbetweenthetwoarrays.
privatestaticvoidprintMatches(int[]a,int[]b){
if(a.length==0||b.length==0){
return;
}
sort(a);
sort(b);
inti=0;
intj=0;
while(true){
while(a[i]<b[j]){
i++;
if(i==a.length){
return;
}
}
while(a[i]>b[j]){
j++;
if(j==b.length){
return;
}
}
if(a[i]==b[j]){
System.out.print(""+a[i]);
do{
i++;
}while(i<a.length&&a[i1]==a[i]);
do{
j++;
}while(j<b.length&&b[j1]==b[j]);
}
if(i==a.length||j==b.length){
return;
}
}
}
//Inplaceradixsort.
privatestaticvoidsort(int[]in){
//Flipthesignbittoregularizethesortorder
upvote2 flipBit(in,31);
downvote sort(in,0,in.length,31);
//Flipbackthesignbitbacktorestore2'scomplement
flipBit(in,31);
}
/**
*Sortasubarray,elementsstartthroughend1ofin,accordingtothe
*valuesinfirstBitthrough0.
*
*@paramin
*@paramstart
*@paramend
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 241/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
*@paramfirstBit
*/
privatestaticvoidsort(int[]in,intstart,intend,intfirstBit){
if(start==end){
return;
}
intmask=1<<firstBit;
intzeroCount=0;
for(inti=start;i<end;i++){
if((in[i]&mask)==0){
zeroCount++;
}
}
intelements=endstart;
intnextZeroIndex=start;
intnextOneIndex=start+zeroCount;
intsplit=nextOneIndex;
if(zeroCount>0&&zeroCount<elements){
while(nextZeroIndex<split){
if((in[nextZeroIndex]&mask)!=0){
//Foundaonebitinthezeroarea,lookforitspartnerintheone
//area
while((in[nextOneIndex]&mask)!=0){
nextOneIndex++;
}
inttemp=in[nextZeroIndex];
in[nextZeroIndex]=in[nextOneIndex];
in[nextOneIndex]=temp;
nextOneIndex++;
}
nextZeroIndex++;
}
if(firstBit>0){
sort(in,start,split,firstBit1);
sort(in,split,end,firstBit1);
}
privatestaticvoidflipBit(int[]in,intbitNo){
intmask=1<<bitNo;
for(inti=0;i<in.length;i++){
in[i]^=mask;
}
}
}
answeredNov8'12at23:25
editedNov9'12at2:00
share|improvethisanswer
PatriciaShanahan
16.2k21343
addacomment|
OnepossibleanswerissimilartotheHashMapsolution...IFyouknowthattheintegersarewithinaverysmallwindow.Itwouldbesimilartothis:
http://en.wikipedia.org/wiki/Bucket_sort
Basically,iftheintegersareguaranteedtobewithinacertainconstantsizewindow(i.e.allofthemare11000)thenyoucandoitinconstantspaceby
up incrementingeachcellofindex=whateveryournumberis.ThisisexactlythesameastheHashMapsolution,exceptyoudon'tneedtobeabletoaccountforall
vote1 possibleintegerslikeaHashMapcan,whichletsyousaveonspace.IfthisisunclearletmeknowinthecommentsandI'llexplainfurther.
down
vote answeredNov8'12at21:39
share|improvethisanswer
durron597
12.8k23059
addacomment|
IbelievethisispossibletodoinplacewithO(1)extraspace.Imakeuseoftheadditionalassumptionthattheelementsinthearraysaremutableaswellas
swappable,butIbelievewithcarefulaccountingthemutabilityassumptioncouldberemovedforthisparticularproblem.
Thebasicideaistodoinplacehashing.Inplacehashingmaybeimplementedbypartitioningthearrayaroundasuitablepercentile,saythe90th,usingtheO(n)
medianofmediansselectionalgorithm.Thisdividesthearrayintoasmallportion(about10%)andalargeportion(about90%)whoseelementsare
distinguishablefromeachother(lessthanthepartitionelementornot).Youcanthenhashfromthe10%portionintothe90%portionbyswapping.Thishashing
up canbeusedtodetectduplicates.ThisisO(n)foreachprocessingof10%ofthearray,sodone10timesisstillO(n).Idescribedthisinmuchmoredetail,though
vote withsomehandwavingImeantocorrectoneday,overatthisrelatedquestion..
0 Forthisparticularproblem,youneedtodoinplacehashing3times.Firstoneachindividualarraytoremoveduplicates.Then,onawrapperrepresentingthe
down combinedarrays(ifindexislessthanlengthofarray1,indexintoarray1,elseindexintoarray2)toreportduplicates.
vote
answeredNov8'12at22:42
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 242/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
share|improvethisanswer
A.Webb
15.1k11949
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaarraysalgorithmoraskyourown
question.
asked 2yearsago
viewed 2100times
active 2yearsago
Lookingforajob?
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 243/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Mumbai,India/relocation
javaj2ee
Linked
149
InPlaceRadixSort
12
Findanumberwithevennumberofoccurrences
2
Checkiftwoarraysaresimilar
Related
619
HowtoconcatenatetwoarraysinJava?
1368
CreateArrayList(ArrayList<T>)fromarray(T[])
874
InJava,howcanItestifanArraycontainsacertainvalue?
670
DeclarearrayinJava?
25
findiftwoarrayscontainthesamesetofintegerswithoutextraspaceandfasterthanNlogN
8
Howtointersecttwosortedintegerarrayswithoutduplicates?
11313
Whyisprocessingasortedarrayfasterthananunsortedarray?
11
Givenanarray[a1b2c3d4]convertto[abcd1234]
2
Checkiftwoarraysaresimilar
2
Givenanarrayof+veintegers,FindthenumberwhichoccursoddnumberoftimesinO(n)time&constantspace.
HotNetworkQuestions
Needhelprecreatingcrazycolors/materialfromexample
Whycan'tanonabeliangroupbe75%abelian?
HowcanIcheckifmyfunctionprint/echo'ssomething?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
ImageOpensasLayer0ratherthanBackground
Whatis`$?`?Isitavariable?
zero,zerosorzeroes?
NineTallMenAreStandingTall
howcanItaketotalminutesfromtime?
Whyadding"incolour"whenreferringto"WizardofOz"?
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
Clientwantsfontaslogo
Whatistheoriginofthisphotoofanunexplodedbomb?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Whydotheymanifestasrings?
What'sanexpressionforacunninglyfakefriend?
Troublewithterminatinga<apex:pageBlockSection>
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
Canmathbesubjective?
HowtodealwithaGMwhodoesnottelluseverything?
DoesaUSB3.0connectionrequireaUSB3.0cord?
Whatisatemporarysolutionforadamagedcarbody?
Packagetodonotes:HowcanIchangethetextcolor?
Doblockingcreatureshealbacktofullbetweenphases?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. Stack 1. English
1. Programmers 1. Photography Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
2. ServerFault Administrators Usage
3. AskDifferent &Fantasy 2. Skeptics 1. Mathematics
3. SuperUser 2. Drupal 1. StackApps
(Apple) 3. GraphicDesign 3. MiYodeya 2. CrossValidated
4. Web Answers 2. MetaStack
4. WordPress 4. SeasonedAdvice (Judaism) (stats)
Applications 3. SharePoint Exchange
Development (cooking) 4. Travel 3. Theoretical
5. AskUbuntu 4. User 3. Area51
5. Geographic 5. Home 5. Christianity ComputerScience
6. Webmasters Experience 4. Stack
InformationSystems Improvement 6. Arqade(gaming) 4. Physics
7. Game 5. Mathematica Overflow
6. Electrical 6. PersonalFinance 7. Bicycles 5. MathOverflow
Development 6. Salesforce Careers
Engineering &Money 8. Roleplaying 6. more(7)
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
LaTeX Games
8. InformationSecurity 8. more(10) 9. more(21)
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 244/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
WhatdatastructureshouldIuseforahighscorelist?[duplicate]
PossibleDuplicate:
HowtosortaMap<Key,Value>onthevaluesinJava?
howtosortMapvaluesbykeyinJava
IamtryingtokeeptrackofscoresandIneedtobeabletosortthescoresintononascendingorderwithoutgettingthekeysandvaluesoutofline.Myfirst
upvote4 thoughtwastouseamapbutI'mreallystrugglingtofindawaytokeepamapsortedbyvalue.ThevaluesareallIntegerobjects.HowwouldIgoabout
downvote sortingahighscorelistlikethis?
favorite
2 javasortingmap
askedJul14'12at23:28
share|improvethisquestion
SaxSalute
274
markedasduplicatebyBohemian,GeorgeStockerJul15'12at0:30
Thisquestionhasbeenaskedbeforeandalreadyhasananswer.Ifthoseanswersdonotfullyaddressyourquestion,pleaseaskanewquestion.
Thispostseemstodescribeyourissue:[stackoverflow.com/questions/109383/[1]:stackoverflow.com/questions/109383/EdgeCaseJul14'12
1
at23:39
addacomment|
1Answer
activeoldestvotes
ThisisaMicrosoft/Amazonjobinterviewtypeofquestion.Youcanuseapriorityqueue,inothertohavethehighestscoreasthefirstelementofthequeue.
Createanodeaskey|valuepair.Implementitinawaythekeyorderismaintainedbythescorevalue,andimplementthequeue.
Givingmoredetails
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 245/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ThisisyourNodeimplementation:
publicclassNode{
privateStringname;//thename
privatedoublescore;//assumingyou'reusingdouble
publicNode(Stringname,doublescore){
this.name=name;
this.score=score;//assumingnegativescoresareallowed
upvote1
}
downvote publicvoidupdateScore(doublescore){
this.score+=score;
}
}
AndwhenyouusePriorityQueue,maketheComparisonbasedonthescorevalue.Ifyouneedtosearch/update,itisO(1),accordingtotheJavaAPI:
Implementationnote:thisimplementationprovidesO(log(n))timefortheenqueinganddequeingmethods(offer,poll,remove()andadd)linear
timefortheremove(Object)andcontains(Object)methodsandconstanttimefortheretrievalmethods(peek,element,andsize).
ReadtheAPI,IguessyouprobablyneedtooverwritetheComparator<?superE>comparator(),oratleastmodifyitforyourneeds.Thatshoulddoit.
answeredJul14'12at23:33
editedJul15'12at0:17
share|improvethisanswer
philippe
2,39332471
Thisisaquestionaboutsortingmaps.HowisaPriorityQueuerelevant?BohemianJul14'12at23:37
@BohemianNo,it'snot.It'saquestionaboutwhichdatastructureisbestforthejob.OPsimplyexplainedthathetriedwithamap,notthathewantsa
mapbasedsolution.kbaJul14'12at23:39
I'mabitconfusedabouthowIwoulduseaPriorityQueueinordertosorttheIntegervalueswhilestillmaintainingthepositionoftheStrings.
SaxSaluteJul14'12at23:45
Couldyouwritemeasmallcodesnippetplease?SaxSaluteJul14'12at23:58
@SaxSaluteIgavemoredetailsabouttheimplementation.Whichprogramminglanguageareyouusing?philippeJul14'12at23:58
|show3morecomments
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavasortingmaporaskyourown
question.
asked 2yearsago
viewed 520times
active 2yearsago
Lookingforajob?
SeniorTechnicalConsultant/DeveloperInnovation
iSpace(aConnollyiHea
Hyderabad,India/remote
scalaakka
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Linked
701
HowtosortaMap<Key,Value>onthevaluesinJava?
145
howtosortMapvaluesbykeyinJava
Related
1129
SortaPythondictionarybyvalue
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 246/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
1
howtoswapkeyinmap?
31
Java:Whatisagooddatastructureforstoringacoordinatemapforaninfinitegameworld?
2
Howwouldyousortdoublevaluesinamapindescendingorder?
11313
Whyisprocessingasortedarrayfasterthananunsortedarray?
4
BestwaytosortMapwithValues
3
JavaMappingDataStructure
0
Java:Sortalistofwordsbylength,thenbyalphabeticalorder
0
SortingaMapbykeyusingvaluesfromanotherMap
0
HowtosortdatainaCSVfileusingaparticularfieldinJava?
HotNetworkQuestions
ALN*NTicTacToeGame
Whatistheoriginofthepowericon?
Thetwopronunciationsof
Whyadding"incolour"whenreferringto"WizardofOz"?
Multiplypurefunctionwithscalar
Using"using"twiceinterpreteddifferentlybydifferentcompilers
WhydosomepeoplerefertoLinuxasGNU/Linux?
Clientwantsfontaslogo
Whatistheoriginofthisphotoofanunexplodedbomb?
WhoinventedStarTreksideburnsandwhy?
Whyshouldakeybemadeexplicit?
Removestaticobjectsfromanimagesequence
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Whatis`$?`?Isitavariable?
Whatwereshoesolesmadefrominpreviousages?
HowtodealwithaGMwhodoesnottelluseverything?
Passfilenamefrombashtopython
Troublewithterminatinga<apex:pageBlockSection>
Whycan'tanonabeliangroupbe75%abelian?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
howcanItaketotalminutesfromtime?
Isturninggraphitecarbonintodiamondindustriallydoable?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Justifyingsuboptimalresearchqualitybylackofsupervision
morehotquestions
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 247/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Whatisthetimecomplexityandspacecomplexityofthisalgorithmtofind
Anagrams?
IamworkingonaninterviewquestionfromAmazonSoftware
Thequestionis
"Designanalgorithmtotakealistofstringsaswellasasingleinputstring,andreturntheindicesofthelistwhichareanagramsoftheinputstring,
disregardingspecialcharacters."
Iwasabletodesignthealgorithmfine,whatIdidinpsuedocodewas
1.Createanarraycharactercountofthesingleinputstring
2.Foreachstringthelist,constructtheanarraycharactercount
3.Comparethecharactercountofeachstringinlisttosingleoutputstring
4.Ifsame,addittoalistthatholdsalltheindexesofanagrams.
5.Returnthatlistofindices.
HereismyimplementationinJava(itworks,testedit)
publicstaticList<Integer>indicesOfAnag(List<String>li,Stringcomp){
List<Integer>allAnas=newArrayList<Integer>();
int[]charCounts=generateCharCounts(comp);
intlistLength=li.size();
for(intc=0;c<listLength;c++){
int[]charCountComp=generateCharCounts(li.get(c));
if(isEqualCounts(charCounts,charCountComp))
allAnas.add(c);
}
returnallAnas;
upvote0 }
privatestaticbooleanisEqualCounts(int[]counts1,int[]counts2){
downvote for(intc=0;c<counts1.length;c++){
favorite if(counts1[c]!=counts2[c])
returnfalse;
}
returntrue;
}
privatestaticint[]generateCharCounts(Stringcomp){
int[]charCounts=newint[26];
intlength=comp.length();
for(intc=0;c<length;c++){
charCounts[Character.toLowerCase(comp.charAt(c))'a']++;
}
returncharCounts;
}
WhatIamhavingtroublewithisanalyzingthespaceandtimecomplexityofthisalgorithmbecauseofbothofthesizesofthelistandofeachstring.
WouldthetimecomplexityalgorithmjustbeO(N)whereNisthesizeofthelist(processingeachStringonce)ordoIhavetotakeintoaccountthecomposite
complexityofthelengthofeachString,inthatcase,O(N*n)wherenisthelengthofthestring?IdidN*nbecauseyouwareprocessingnNtimes.And
wouldspacecomplexitybeO(N)becauseIamcreatingNcopiesofthe26lengtharray?
javaalgorithmdatastructurestimecomplexityspacecomplexity
askedMar2at4:30
share|improvethisquestion
committedandroider
1,817416
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 248/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Idontthinkitstoobroad.Theresoneanswerforspaceandtimecomplexity.....committedandroiderMar2at4:36
IftheunderlyingimplementationofList<String>passedintoindicesOfAnag(...)isaLinkedList,thentheli.get(c)willbeO(N)andthewholething
becomesquadraticinthesizeoftheinput.Betteroveralltouseaniteratortoavoidthis.msandifordMar2at5:05
@msandifordsothisisanexampleofO(N^2)?justwonderingbecauseimlearningaboutthisthissemester.JRowanMar2at5:14
@JRowanIfyouseetheanswerbelow,witharraylist,itshouldbeO(N)whereNisthesumofallthelengthsofstringscommittedandroiderMar2at
5:14
sothetimecomplexityislinear?JRowanMar2at5:15
|show7morecomments
1Answer
activeoldestvotes
AndwouldspacecomplexitybeO(N)becauseIamcreatingNcopiesofthe26lengtharray?
Yes.
WouldthetimecomplexityalgorithmjustbeO(N)whereNisthesizeofthelist
upvote2down
voteaccepted No.Timedependsonsizeofinputstrings,it'llbeO(comp.length+sum_of_li_lengths).
answeredMar2at4:38
editedMar2at5:01
share|improvethisanswer
Everv0id
555415
Wouldn'titjustbeN*n,wherenistheaveragelengthofastring?Idon'tgetwhyyouaddedcomp.lengthandsum_of_li_lengths.
committedandroiderMar2at4:40
Nope,itwouldn't.Stringsinlicanallcontainonlyonecharacter,butlicancontainmillionsofstrings.That'swhatcalledinputdatasizein
complexitytheory.Everv0idMar2at4:43
ohsoyouincludedtwovariablesinyouranalysisbecausetheruntimedependsonbothofthem?Butwhydothesumofallthelengths?Each
timeNruns,it'sjustgoingtolookatoneString.committedandroiderMar2at4:46
Sorry,imissedsmthinyourquestion.Inyourcasetimecomplexitydoesn'tdependonsizeofthelist.Itdependsonlyontotallengthofallyour
strings.Thisisbecauseeverysymbolishandledonce.Everv0idMar2at4:49
Iknowithastodependonthesizeofthelist.Theresaforloopthatendsatthesizeofthelist.Thealgorithmwillscaleuplinearlywithsize.
committedandroiderMar2at4:52
|show3morecomments
YourAnswer
Signuporlogin
SignupusingGoogle
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 249/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaalgorithmdatastructurestime
complexityspacecomplexityoraskyourownquestion.
asked 4monthsago
viewed 111times
active 4monthsago
Lookingforajob?
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Related
1
Relationoftimecomplexityandspacecomplexity
23
Findtheknonrepeatingelementsinalistwithlittleadditionalspace
1
whattypeofmathsisrequiredtounderstandalgorithmtimeandspacecomplexities?
0
Timecomplexityforalgorithm
4
DeterminingtheTimeandSpacecomplexityofagivencode
0
WhatexactlydoesO(n)spacecomplexitymeanandhowinefficientisit?
7
Whatisthespacecomplexityofarecursivefibonaccialgorithm?
3
Whatisthespacecomplexityofthisalgorithm?
0
IsthespacecomplexityofthissubsetalgorithmactuallyO(n)?
3
Whatisthespacecomplexityofenumeratingsubsets?
HotNetworkQuestions
Troublewithterminatinga<apex:pageBlockSection>
Derivativeofadefiniteintegralissue
PythonLabelExpression?ArcGIS10.3.1
Wordfor"animals,includinghumans"?
Whatistheoriginofthepowericon?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
FindingoutifawordisanAnagramofanother
HowtodealwithaGMwhodoesnottelluseverything?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
ThenthTernary
Justifyingsuboptimalresearchqualitybylackofsupervision
Uncorrectedsamplestandarddeviationincorrelationcoefficient
Whyweren'ttheWeasleysapartoftheOriginalOrder?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
HowtoprovemyGmailhasbeenhacked?
zero,zerosorzeroes?
Nicelytypesettingverbatimtext
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 250/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Canmathbesubjective?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
Whatwereshoesolesmadefrominpreviousages?
Whydotheymanifestasrings?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Whystorethepointsinabinarytree?
Thisquestioncoversasoftwarealgorithm,fromOntopic
IamworkingonaninterviewquestionfromAmazonSoftwareQuestion,specifically
"Givenasetofpoints(x,y)andaninteger"n",returnnnumberofpointswhichareclosetotheorigin"
Hereisthesamplehighlevelpsuedocodeanswertothisquestion,fromSampleAnswer
Step1:Designaclasscalledpointwhichhasthreefieldsintx,inty,intdistance
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 251/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Step2:Forallthepointsgiven,findthedistancebetweenthemandorigin
Step3:Storethevaluesinabinarytree
Step4:Heapsort
Step5:printthefirstnvaluesfromthebinarytree
Iagreewithsteps1and2becauseitmakessenseintermsofobjectorienteddesigntohaveonesoftwarebundleofdata,Point,encapsulateawaythe
fieldsofx,yanddistance.Ensapsulation
upvote3down
votefavorite Cansomeoneexplainthedesigndecisionsfrom3to5?
1
Here'showIwoulddostepsof3to5
Step3:Storeallthepointsinanarray
Step4:Sortthearraywithrespecttodistance(IusesomebuildinsortherelikeArrays.Sort
Step5:Withthearraysortedinascendingorder,Iprintoffthefirstnvalues
Whytheauthorofthatresponseuseamorecomplicateddatastructure,binarytreeandnotsomethingsimplerlikeanarraythatIused?Iknowwhata
binarytreeishierarchicaldatastructureofnodeswithtwopointers.Inhisalgorithm,wouldyouhavetouseaBST?
javaarraysalgorithmsortingtree
askedFeb20at21:35
share|improvethisquestion
committedandroider
1,817416
1 Perhapstheymeantheimplicitbinarytreethatheapsortusuallyworkswith?haroldFeb20at21:46
As@haroldsaid,itsoundsliketheymeanyouinsertandextractfromabinaryheap,whichhasaBigOoflog(n),whichisbetterthanthenlog
(n)youwouldgetwiththesortedarrayapproach.jpriebeFeb20at22:02
1 @jpriebebutyouhavetoinsertnitems...soitwillstillbenlognAdrianLeonhardFeb20at22:02
MaybebecausethetimeandspacecomplexityofArrays.sortismorethanwhenyoudoaheapsort(worstcasenlogn).
stackoverflow.com/a/22571601/2344337NeminFeb20at22:05
You'rerightAdrian,mymistakejpriebeFeb20at22:06
|show2morecomments
3Answers
activeoldestvotes
First,IwouldnotsaythathavingPoint(x,y,distance)isgooddesignorencapsulation.distanceisnotreallypartofapoint,itcanbecomputedfromx
andy.Intermofdesign,Iwouldcertainlyhaveafunction,i.e.astaticmethodfromPointoranhelperclassPoints.
doubledistance(Pointa,Pointb)
Thenforthespecificquestion,Iactuallyagreewithyoursolution,toputthedatainanarray,sortthisarrayandthenextracttheNfirst.Whattheexample
maybehintedatisthattheheapsortactuallyoftenusesabinarytreestructureinsidethearraytobesortedasexplainedhere:
Theheapisoftenplacedinanarraywiththelayoutofacompletebinarytree.
upvote1
downvote Ofcourse,ifthedistancetotheoriginisnotstoredinthePoint,forperformancereason,ithadtobeputwiththecorrespondingPointobjectinthearray,
accepted oranyinformationthatwillallowtogetthePointobjectfromthesorteddistance(reference,index),e.g.
List<Pair<Long,Point>>distancesToOrigin=newArrayList<>();
tobesortedwithaComparator<Pair<Long,Point>>
answeredFeb20at22:13
share|improvethisanswer
AbbRsina
3,2421420
Wouldn'titbebettertocalculatethedistanceonceandstoreitasafieldratherthanrecalculatingitfromxandyeachtimeyouneedit?
committedandroiderFeb21at2:41
Evenbetter,youcanusethesquareofthedistancetocomparetheirdistancefromtheorigin.Savesasquareroot.haroldFeb21at9:10
@committedandroider,thatisexactlythepurposeofsortingaPairofdistanceandPoint.ThedistanceisonlycomputedonceforeachPoint.And
thisway,youcanactuallydowhat@haroldsuggest:usethesquareddistanceinsteadofjustdistance.Itsavessomecomputing.AbbRsinaFeb
21at10:11
@AbbRsinaWhatdoesthatpairdo?committedandroiderFeb23at4:45
ThatisjustaconvenientwaytolinkadistancetoaPointforthetimeofsorting:theComparatorwillonlyusethedistancefield.Youcanalsohave
thecomputeddistancecachedasatransientfieldofPointandcomputed/accessedthroughadistanceFromOrigin()method.AbbRsinaFeb23
at10:20
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 252/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ItisnotnecessarytouseBST.However,itisagoodpracticetouseBSTwhenneedingastructurethatisselfsorted.IdonotseetheneedtobothuseBSTand
heapsortit(somehow).YoucouldusejustBSTandretrievethefirstnpoints.Youcouldalsouseanarray,sortitandusethefirstnpoints.Ifyouwanttosortan
up arrayoftypePoint,youcouldimplementtheinterfaceComparable(Pointwouldimolementthatinterface)andoverloadthedefaultmethod.Youneverhaveto
vote chooseanydatastructures,butbydeterminingtheneedsyouhave,youwouldalsoeasilydeterminetheoptimumstructure.
0
down answeredFeb20at22:03
vote
share|improvethisanswer
reaponja
12
Forperformancewise,wouldyougobinarysearchtreeorbinarytreeandheapsort?committedandroiderFeb21at2:31
IalmostalwaysimplementbinarytreesasBSTs,dependingonthecriteriaofsearch.BSTisadictionaryandassuchitisgoodfortheoperationsofinsertion,
deletionandsearchofdata.Inthiscase,thedilemmawouldratherbe(inmyopinion)betweenadictionaryandasequentialdatastructure,likearrayor
arraylist.Inthisinstance,I'duseanarraylist,sinceyoudonotknowtheexactnumberofpointsyou'llneedstored.reaponjaFeb21at7:37
addacomment|
Theapproachdescribedinthispostismorecomplexthanneededforsuchaquestion.Asyounoted,simplesortingbydistancewillsuffice.However,tohelp
explainyourconfusionaboutwhatyoursampleanswerauthorwastryingtogetat,maybeconsidertheknearestneighborsproblemwhichcanbesolvedwitha
kdtree,astructurethatappliesspacepartitioningtothekddataset.For2dimensionalspace,thatisindeedabinarytree.Thistreeisinherentlysortedanddoesn't
needany"heapsorting."
enterimagedescriptionhere
ItshouldbenotedthatbuildingthekdtreewilltakeO(nlogn),andisonlyworththecostifyouneedtodorepeatednearestneighborsearchesonthestructure.If
youonlyneedtoperformonesearchtofindknearestneighborsfromtheorigin,itcanbedonewithanaiveO(n)search.
Howtobuildakdtree,straightfromWiki:
Oneaddsanewpointtoakdtreeinthesamewayasoneaddsanelementtoanyothersearchtree.First,traversethetree,startingfromtherootand
movingtoeithertheleftortherightchilddependingonwhetherthepointtobeinsertedisonthe"left"or"right"sideofthesplittingplane.Onceyou
gettothenodeunderwhichthechildshouldbelocated,addthenewpointaseithertheleftorrightchildoftheleafnode,againdependingonwhich
sideofthenode'ssplittingplanecontainsthenewnode.
Addingpointsinthismannercancausethetreetobecomeunbalanced,leadingtodecreasedtreeperformance.Therateoftreeperformance
degradationisdependentuponthespatialdistributionoftreepointsbeingadded,andthenumberofpointsaddedinrelationtothetreesize.Ifatree
becomestoounbalanced,itmayneedtoberebalancedtorestoretheperformanceofqueriesthatrelyonthetreebalancing,suchasnearestneighbour
searching.
Oncehavehavebuiltthetree,youcanfindknearestneighborstosomepoint(theorigininyourcase)inO(klogn)time.
up StraightfromWiki:
vote
0 Searchingforanearestneighbourinakdtreeproceedsasfollows:
down
vote 1. Startingwiththerootnode,thealgorithmmovesdownthetreerecursively,inthesamewaythatitwouldifthesearchpointwerebeinginserted
(i.e.itgoesleftorrightdependingonwhetherthepointislesserthanorgreaterthanthecurrentnodeinthesplitdimension).
2. Oncethealgorithmreachesaleafnode,itsavesthatnodepointasthe"currentbest"
3. Thealgorithmunwindstherecursionofthetree,performingthefollowingstepsateachnode:
1. Ifthecurrentnodeiscloserthanthecurrentbest,thenitbecomesthecurrentbest.
2. Thealgorithmcheckswhethertherecouldbeanypointsontheothersideofthesplittingplanethatareclosertothesearchpointthanthe
currentbest.Inconcept,thisisdonebyintersectingthesplittinghyperplanewithahyperspherearoundthesearchpointthathasaradius
equaltothecurrentnearestdistance.Sincethehyperplanesareallaxisalignedthisisimplementedasasimplecomparisontoseewhether
thedifferencebetweenthesplittingcoordinateofthesearchpointandcurrentnodeislesserthanthedistance(overallcoordinates)from
thesearchpointtothecurrentbest.
1. Ifthehyperspherecrossestheplane,therecouldbenearerpointsontheothersideoftheplane,sothealgorithmmustmovedown
theotherbranchofthetreefromthecurrentnodelookingforcloserpoints,followingthesamerecursiveprocessastheentire
search.
2. Ifthehyperspheredoesn'tintersectthesplittingplane,thenthealgorithmcontinueswalkingupthetree,andtheentirebranchonthe
othersideofthatnodeiseliminated.
4. Whenthealgorithmfinishesthisprocessfortherootnode,thenthesearchiscomplete.
ThisisaprettytrickyalgorithmthatIwouldhatetoneedtodescribeasaninterviewquestion!Fortunatelythegeneralcasehereismorecomplexthanisneeded,
asyoupointedoutinyourpost.ButIbelievethisapproachmaybeclosetowhatyour(wrong)sampleanswerwastryingtodescribe.
answeredFeb20at22:09
editedFeb20at22:17
share|improvethisanswer
The111
3,22521435
FWIW,sincethequerypointisfixed,youdon'tneedanyofthat.NiklasB.Feb20at22:13
Right.AsInotedifkisalsofixedyoudon'tevenneedtodoanythingexceptanaivelinearsearch.ButIthinkkdtreesareinteresting,andmorepoignantly,I
thinktheymightbewhatthewronganswerintheOPwastryingtogetat.Forfixed"nearest"source(i.e.origin)andgeneralkthoughIagreeyourO(n)
quickselectisprobablyunbeatable.The111Feb20at22:14
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 253/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaarraysalgorithmsortingtreeor
askyourownquestion.
asked 4monthsago
viewed 111times
active 4monthsago
Lookingforajob?
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 254/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
javaj2ee
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Linked
16
JavaEncapsulation
3
WillArrays.sort()increasetimecomplexityandspacetimecomplexity?
Related
300
Whatisthemostefficient/elegantwaytoparseaflattableintoatree?
5
trieorbalancedbinarysearchtreetostoredictionary?
11313
Whyisprocessingasortedarrayfasterthananunsortedarray?
1
ModifiedBinarySearchTreeforSorting?
0
Isthereagoodalgorithmtosortanunsorted,balanced,binarytree(thatisbetterthanjustbuildanewtree)?
0
Createbinarytreefromlevelorderinput
0
ConvertingBinarySearchTreetoanarrayBFT
0
Threadbinarytree
0
Howtoevaluatetheperformanceofabinarytreeimplementedviaalinkedlistoranarraylist?
1
SortingaBinaryTreeFunctionreachesseg.fault
HotNetworkQuestions
HowtodealwithaGMwhodoesnottelluseverything?
Removestaticobjectsfromanimagesequence
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Wordfor"animals,includinghumans"?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
LeapyearcheckinJava
ImageOpensasLayer0ratherthanBackground
HowcanIcheckifmyfunctionprint/echo'ssomething?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Whatwereshoesolesmadefrominpreviousages?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
ALN*NTicTacToeGame
RollmyD&Dcharacter'sabilityscores
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
WhatdoesitmeanifanACmotorhastwovoltageratings?
zero,zerosorzeroes?
Ciertasconjugacionesverbalesnoconvencionales
40Numbersin9Bytes
Howtoprotectaspaceelevatoragainstterrorism
Antiferromagneticordering
Patchingabinarywithdd
ThenthTernary
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
WhatisNode.js?[closed]
Idon'tfullygetwhatNode.jsisallabout.Maybeit'sbecauseIammainlyawebbasedbusinessapplicationdeveloper.Whatisitandwhatistheuse
ofit?
Myunderstandingsofaristhat:
1. Theprogrammingmodeliseventdriven,especiallythewayithandlesI/O.
2. ItusesJavaScriptandtheparserisV8.
3. Itcanbeeasilyusedtocreateconcurrentserverapplications.
upvote507down
votefavorite Aremyunderstandingscorrect?Ifyes,thenwhatarethebenefitsofeventedI/O,isitjustmorefortheconcurrencystuff?Also,isthedirectionof
892 Node.jstobecomeaframeworklike,JavaScriptbased(V8based)programmingmodel?
javascriptnode.jsv8eventedio
editedJun22'13at9:11 askedDec10'09at23:05
share
PeterMortensen Jeff
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 256/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
8,445105794 5,131144682
lockedbyBilltheLizardJun26'13at12:14
Thisquestionexistsbecauseithashistoricalsignificance,butitisnotconsideredagood,ontopicquestionforthissite,sopleasedonotuseitasevidencethatyou
canasksimilarquestionshere.Thisquestionanditsanswersarefrozenandcannotbechanged.Moreinfo:helpcenter.
closedasnotconstructivebyBilltheLizardApr28'12at14:03
Asitcurrentlystands,thisquestionisnotagoodfitforourQ&Aformat.Weexpectanswerstobesupportedbyfacts,references,orexpertise,butthisquestionwill
likelysolicitdebate,arguments,polling,orextendeddiscussion.Ifyoufeelthatthisquestioncanbeimprovedandpossiblyreopened,visitthehelpcenterforguidance.
Ifthisquestioncanberewordedtofittherulesinthehelpcenter,pleaseeditthequestion.
commentsdisabledondeleted/lockedposts/reviews|
10Answers
activeoldestvotes
Ithinktheadvantagesare:
1. Webdevelopmentinadynamiclanguage(JavaScript)onaVMthatisincrediblyfast(V8).ItismuchfasterthanRuby,Python,orPerl.
2. Abilitytohandlethousandsofconcurrentconnectionswithminimaloverheadonasingleprocess.
3. JavaScriptisperfectforeventloopswithfirstclassfunctionobjectsandclosures.Peoplealreadyknowhowtouseitthiswayhavinguseditinthe
browsertorespondtouserinitiatedevents.
upvote213
downvote 4. AlotofpeoplealreadyknowJavaScript,evenpeoplewhodonotclaimtobeprogrammers.Itisarguablythemostpopularprogramminglanguage.
accepted
5. UsingJavaScriptonawebserveraswellasthebrowserreducestheimpedancemismatchbetweenthetwoprogrammingenvironmentswhichcan
communicatedatastructuresviaJSONthatworkthesameonbothsidesoftheequation.Duplicateformvalidationcodecanbesharedbetween
serverandclient,etc.
editedOct23'12at18:26 answeredDec14'09at19:37
share
lockedbyRobertHarveyOct23'12at18:31
RobertHarvey postfuturist
116k24191309 11.1k73866
Thisposthasbeenlockedwhiledisputesaboutitscontentarebeingresolved.Formoreinfovisitmeta.
Iwasabouttoaskthesamequestion.IamstillnotclearaboutthisbutIthinkIneedtoseeaworkingapplicationorbetteryetwriteone.Isit
1
possibletododatabaselookups?iJKMay14'10at14:47
Regarding#1,doyouhaveorknowofanyactualmetricsshowingthatcoderunningonV8isfasterthansimilarcodeinPython?Myintuitiontells
2
methatyouarecorrect,butsomeactualnumberswouldbeahugehelpininfluencingthedecisionmakers.AdamCrosslandJul9'10at16:39
@postfuturist:Itactuallyperformswellagainstlotsofalternatives.ItbeatsJava6prettyhandilyinlotsofcases,too.Neat!AdamCrosslandJul
1
11'10at22:45
1 @postfuturistIthinkyouhavecomparedagainstjava6Xint.Trycomparingwithjava6serverfedesilvaNov18'10at23:08
@Whydidyoueditthispostfor"Legacybullshit"only?Idon'tthink212peoplewouldhavevoteforthispostifyoudidwritethisfromthe
4
beginning.JulienFouilhOct19'12at16:38
commentsdisabledondeleted/lockedposts/reviews|show3morecomments
IuseNode.jsatwork,andfindittobeverypowerful.ForcedtochooseonewordtodescribeNode.js,I'dsay"interesting"(whichisnotapurelypositive
adjective).Thecommunityisvibrantandgrowing.JavaScript,despiteitsodditiescanbeagreatlanguagetocodein.Andyouwilldailyrethinkyourown
understandingof"bestpractice"andthepatternsofwellstructuredcode.There'sanenormousenergyofideasflowingintoNode.jsrightnow,andworkinginit
exposesyoutoallthisthinkinggreatmentalweightlifting.
Node.jsinproductionisdefinitelypossible,butfarfromthe"turnkey"deploymentseeminglypromisedbythedocumentation.WithNode.jsv0.6.x,"cluster"has
beenintegratedintotheplatform,providingoneoftheessentialbuildingblocks,butmy"production.js"scriptisstill~150linesoflogictohandlestufflike
creatingthelogdirectory,recyclingdeadworkers,etc.Fora"serious"productionservice,youalsoneedtobepreparedtothrottleincomingconnectionsanddoall
thestuffthatApachedoesforPHP.Tobefair,RubyonRailshasthisexactproblem.Itissolvedviatwocomplementarymechanisms:1)PuttingRubyon
Rails/Node.jsbehindadedicatedwebserver(writteninCandtestedtohellandback)likeNginx(orApache/Lighttd).Thewebservercanefficientlyservestatic
content,accesslogging,rewriteURLs,terminateSSL,enforceaccessrules,andmanagemultiplesubservices.Forrequeststhathittheactualnodeservice,the
webserverproxiestherequestthrough.2)UsingaframeworklikeUnicornthatwillmanagetheworkerprocesses,recyclethemperiodically,etc.I'veyettofinda
Node.jsservingframeworkthatseemsfullybakeditmayexist,butIhaven'tfoundityetandstilluse~150linesinmyhandrolled"production.js".
ReadingframeworkslikeExpressmakesitseemlikethestandardpracticeistojustserveeverythingthroughonejackofalltradesNode.jsservice...
"app.use(express.static(__dirname+'/public'))".Forlowerloadservicesanddevelopment,that'sprobablyfine.Butassoonasyoutrytoputbigtimeloadonyour
serviceandhaveitrun24/7,you'llquicklydiscoverthemotivationsthatpushbigsitestohavewellbaked,hardenedCcodelikeNginxfrontingtheirsiteand
handlingallofthestaticcontentrequests(...untilyousetupaCDN,likeAmazonCloudFront)).Forasomewhathumorousandunabashedlynegativetakeonthis,
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 257/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
seethisguy.
Node.jsisalsofindingmoreandmorenonserviceuses.Evenifyouareusingsomethingelsetoservewebcontent,youmightstilluseNode.jsasabuildtool,
usingnpmmodulestoorganizeyourcode,Browserifytostitchitintoasingleasset,anduglifyjstominifyitfordeployment.Fordealingwiththeweb,JavaScript
isaperfectimpedancematchandfrequentlythatmakesittheeasiestrouteofattack.Forexample,ifyouwanttogrovelthroughabunchofJSONresponse
payloads,youshouldusemyunderscoreCLImodule,theutilitybeltofstructureddata.
Pros/Cons:
Pro:Foraserverguy,writingJavaScriptonthebackendhasbeena"gatewaydrug"tolearningmodernUIpatterns.Inolongerdreadwritingclientcode.
Pro:Tendstoencouragepropererrorchecking(errisreturnedbyvirtuallyallcallbacks,naggingtheprogrammertohandleitalso,async.jsandother
librarieshandlethe"failifanyofthesesubtasksfails"paradigmmuchbetterthantypicalsynchronouscode)
Pro:Someinterestingandnormallyhardtasksbecometriviallikegettingstatusontasksinflight,communicatingbetweenworkers,orsharingcachestate
Pro:Hugecommunityandtonsofgreatlibrariesbasedonasolidpackagemanager(npm)
Con:JavaScripthasnostandardlibrary.YougetsousedtoimportingfunctionalitythatitfeelsweirdwhenyouuseJSON.parseorsomeotherbuildin
methodthatdoesn'trequireaddingannpmmodule.Thismeansthattherearefiveversionsofeverything.EventhemodulesincludedintheNode.js"core"
havefivemorevariantsshouldyoubeunhappywiththedefaultimplementation.Thisleadstorapidevolution,butalsosomelevelofconfusion.
Versusasimpleoneprocessperrequestmodel(LAMP):
Pro:Scalabletothousandsofactiveconnections.Veryfastandveryefficient.Forawebfleet,thiscouldmeana10Xreductioninthenumberofboxes
requiredversusPHPorRuby
Pro:Writingparallelpatternsiseasy.Imaginethatyouneedtofetchthree(orN)blobsfromMemcached.DothisinPHP...didyoujustwritecodethe
fetchesthefirstblob,thenthesecond,thenthethird?Wow,that'sslow.There'saspecialPECLmoduletofixthatspecificproblemforMemcached,but
whatifyouwanttofetchsomeMemcacheddatainparallelwithyourdatabasequery?InNode.js,becausetheparadigmisasynchronous,havingaweb
requestdomultiplethingsinparallelisverynatural.
Con:Asynchronouscodeisfundamentallymorecomplexthansynchronouscode,andtheupfrontlearningcurvecanbehardfordeveloperswithoutasolid
understandingofwhatconcurrentexecutionactuallymeans.Still,it'svastlylessdifficultthanwritinganykindofmultithreadedcodewithlocking.
Con:Ifacomputeintensiverequestrunsfor,forexample,100ms,itwillstallprocessingofotherrequeststhatarebeinghandledinthesameNode.js
process...AKA,cooperativemultitasking.ThiscanbemitigatedwiththeWebWorkerspattern(spinningoffasubprocesstodealwiththeexpensivetask).
Alternatively,youcouldusealargenumberofNode.jsworkersandonlyleteachonehandleasinglerequestconcurrently(stillfairlyefficientbecausethere
isnoprocessrecycle).
Con:RunningaproductionsystemisMUCHmorecomplicatedthanaCGImodellikeApache+PHP,Perl,Ruby,etc.Unhandledexceptionswillbring
downtheentireprocess,necessitatinglogictorestartfailedworkers(seecluster).Moduleswithbuggynativecodecanhardcrashtheprocess.Whenevera
workerdies,anyrequestsitwashandlingaredropped,soonebuggyAPIcaneasilydegradeserviceforothercohostedAPIs.
Versuswritinga"real"serviceinJava/C#/C(C?really?)
Pro:DoingasynchronousinNode.jsiseasierthandoingthreadsafetyanywhereelseandarguablyprovidesgreaterbenefit.Node.jsisbyfartheleastpainful
asynchronousparadigmI'veeverworkedin.Withgoodlibraries,itisonlyslightlyharderthanwritingsynchronouscode.
Pro:Nomultithreading/lockingbugs.True,youinvestupfrontinwritingmoreverbosecodethatexpressesaproperasynchronousworkflowwithno
blockingoperations.Andyouneedtowritesometestsandgetthethingtowork(itisascriptinglanguageandfatfingeringvariablenamesisonlycaughtat
unittesttime).BUT,onceyougetittowork,thesurfaceareaforheisenbugsstrangeproblemsthatonlymanifestonceinamillionrunsthatsurface
areaisjustmuchmuchlower.ThetaxeswritingNode.jscodeareheavilyfrontloadedintothecodingphase.Thenyoutendtoendupwithstablecode.
Pro:JavaScriptismuchmorelightweightforexpressingfunctionality.It'shardtoprovethiswithwords,butJSON,dynamictyping,lambdanotation,
prototypalinheritance,lightweightmodules,whatever...itjusttendstotakelesscodetoexpressthesameideas.
Con:Maybeyoureally,reallylikecodingservicesinJava?
ForanotherperspectiveonJavaScriptandNode.js,checkoutFromJavatoNode.js,ablogpostonaJavadeveloper'simpressionsandexperienceslearning
Node.js.
ModulesWhenconsideringnode,keepinmindthatyourchoiceofJavaScriptlibrarieswillDEFINEyourexperience.Mostpeopleuseatleasttwo,an
asynchronouspatternhelper(Step,Futures,Async),andaJavaScriptsugarmodule(Underscore.js).
Helper/JavaScriptSugar:
Underscore.jsusethis.Justdoit.Itmakesyourcodeniceandreadablewithstufflike_.isString(),and_.isArray().I'mnotreallysurehowyoucouldwrite
safecodeotherwise.Also,forenhancedcommandlinefu,checkoutmyownUnderscoreCLI.
AsynchronousPatternModules:
Stepaveryelegantwaytoexpresscombinationsofserialandparallelactions.Mypersonalreccomendation.SeemypostonwhatStepcodelookslike.
Futuresmuchmoreflexible(isthatreallyagoodthing?)waytoexpressorderingthroughrequirements.Canexpressthingslike"starta,b,cinparallel.
WhenA,andBfinish,startAB.WhenA,andCfinish,startAC."Suchflexibilityrequiresmorecaretoavoidbugsinyourworkflow(likenevercallingthe
callback,orcallingitmultipletimes).SeeRaynos'spostonusingfutures(thisisthepostthatmademe"get"futures).
Asyncmoretraditionallibrarywithonemethodforeachpattern.Istartedwiththisbeforemyreligiousconversiontostepandsubsequentrealizationthat
allpatternsinAsynccouldbeexpressedinStepwithasinglemorereadableparadigm.
TameJSWrittenbyOKCupid,it'saprecompilerthataddsanewlanguageprimative"await"forelegantlywritingserialandparallelworkflows.The
patternlooksamazing,butitdoesrequireprecompilation.I'mstillmakingupmymindonthisone.
StreamlineJScompetitortoTameJS.I'mleaningtowardTame,butyoucanmakeupyourownmind.
Ortoreadallabouttheasynchronouslibraries,seethispanelinterviewwiththeauthors.
WebFramework:
ExpressGreatRubyonRailseskframeworkfororganizingwebsites.ItusesJADEasaXML/HTMLtemplatingengine,whichmakesbuildingHTMLfar
lesspainful,almosteleganteven.
jQueryWhilenottechnicallyanodemodule,jQueryisquicklybecomingadefactostandardforclientsideuserinterface.jQueryprovidesCSSlike
selectorsto'query'forsetsofDOMelementsthatcanthenbeoperatedon(sethandlers,properties,styles,etc).Alongthesamevein,Twitter'sBootstrap
CSSframework,Backbone.jsforanMVCpattern,andBrowserify.jstostitchallyourJavaScriptfilesintoasinglefile.Thesemodulesareallbecomingde
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 258/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
factostandardssoyoushouldatleastcheckthemoutifyouhaven'theardofthem.
Testing:
up JSHintMustuseIdidn'tusethisatfirstwhichnowseemsincomprehensible.JSLintaddsbackabunchofthebasicverificationsyougetwithacompiled
vote languagelikeJava.Mismatchedparenthesis,undeclaredvariables,typeosofmanyshapesandsizes.YoucanalsoturnonvariousformsofwhatIcall"anal
620 mode"whereyouverifystyleofwhitespaceandwhatnot,whichisOKifthat'syourcupofteabuttherealvaluecomesfromgettinginstantfeedbackon
down theexactlinenumberwhereyouforgotaclosing")"...withouthavingtorunyourcodeandhittheoffendingline."JSHint"isamoreconfigurablevariant
vote ofDouglasCrockford'sJSLint.
MochacompetitortoVowswhichI'mstartingtoprefer.Bothframeworkshandlethebasicswellenough,butcomplexpatternstendtobeeasiertoexpressin
Mocha.
VowsVowsisreallyquiteelegant.Anditprintsoutalovelyreport(spec)showingyouwhichtestcasespassed/failed.Spend30minuteslearningit,and
youcancreatebasictestsforyourmoduleswithminimaleffort.
ZombieHeadlesstestingforHTMLandJavaScriptusingJSDomasavirtual"browser".Verypowerfulstuff.CombineitwithReplaytogetlightningfast
deterministictestsofinbrowsercode.
Acommentonhowto"thinkabout"testing:
Testingisnonoptional.WithadynamiclanguagelikeJavaScript,thereareveryfewstaticchecks.Forexample,passingtwoparameterstoamethod
thatexpects4won'tbreakuntilthecodeisexecuted.PrettylowbarforcreatingbugsinJavaScript.Basictestsareessentialtomakingupthe
verificationgapwithcompiledlanguages.
Forgetvalidation,justmakeyourcodeexecute.Foreverymethod,myfirstvalidationcaseis"nothingbreaks",andthat'sthecasethatfiresmostoften.
Provingthatyourcoderunswithoutthrowingcatches80%ofthebugsandwilldosomuchtoimproveyourcodeconfidencethatyou'llfindyourself
goingbackandaddingthenuancedvalidationcasesyouskipped.
Startsmallandbreaktheinertialbarrier.Wearealllazy,andpressedfortime,andit'seasytoseetestingas"extrawork".Sostartsmall.Writetest
case0loadyourmoduleandreportsuccess.Ifyouforceyourselftodojustthismuch,thentheinertialbarriertotestingisbroken.That's<30minto
doityourfirsttime,includingreadingthedocumentation.Nowwritetestcase1calloneofyourmethodsandverify"nothingbreaks",thatis,that
youdon'tgetanerrorback.Testcase1shouldtakeyoulessthanoneminute.Withtheinertiagone,itbecomeseasytoincrementallyexpandyourtest
coverage.
Nowevolveyourtestswithyourcode.Don'tgetintimidatedbywhatthe"correct"endtoendtestwouldlooklikewithmockserversandallthat.
Codestartssimpleandevolvestohandlenewcasestestsshouldtoo.Asyouaddnewcasesandnewcomplexitytoyourcode,addtestcasesto
exercisethenewcode.Asyoufindbugs,addverificationsand/ornewcasestocovertheflawedcode.Whenyouaredebuggingandloseconfidence
inapieceofcode,gobackandaddteststoprovethatitisdoingwhatyouthinkitis.Capturestringsofexampledata(fromotherservicesyoucall,
websitesyouscrape,whatever)andfeedthemtoyourparsingcode.Afewcaseshere,improvedvalidationthere,andyouwillendupwithhighly
reliablecode.
Also,checkouttheofficiallistofrecommendedNode.jsmodules.However,GitHub'sNodeModulesWikiismuchmorecompleteandagoodresource.
TounderstandNode,it'shelpfultoconsiderafewofthekeydesignchoices:
Node.jsisEVENTBASEDandASYNCHRONOUS/NONBLOCKING.Events,likeanincomingHTTPconnectionwillfireoffaJavaScriptfunctionthat
doesalittlebitofworkandkicksoffotherasynchronoustaskslikeconnectingtoadatabaseorpullingcontentfromanotherserver.Oncethesetaskshavebeen
kickedoff,theeventfunctionfinishesandNode.jsgoesbacktosleep.Assoonassomethingelsehappens,likethedatabaseconnectionbeingestablishedorthe
externalserverrespondingwithcontent,thecallbackfunctionsfire,andmoreJavaScriptcodeexecutes,potentiallykickingoffevenmoreasynchronoustasks(like
adatabasequery).Inthisway,Node.jswillhappilyinterleaveactivitiesformultipleparallelworkflows,runningwhateveractivitiesareunblockedatanypointin
time.ThisiswhyNode.jsdoessuchagreatjobmanagingthousandsofsimultaneousconnections.
Whynotjustuseoneprocess/threadperconnectionlikeeveryoneelse?InNode.js,anewconnectionisjustaverysmallheapallocation.Spinningupanew
processtakessignificantlymorememory,amegabyteonsomeplatforms.Buttherealcostistheoverheadassociatedwithcontextswitching.Whenyouhave10^6
kernelthreads,thekernelhastodoalotofworkfiguringoutwhoshouldexecutenext.AbunchofworkhasgoneintobuildinganO(1)schedulerforLinux,butin
theend,it'sjustwaywaymoreefficienttohaveasingleeventdrivenprocessthan10^6processescompetingforCPUtime.Also,underoverloadconditions,the
multiprocessmodelbehavesverypoorly,starvingcriticaladministrationandmanagementservices,especiallySSHD(meaningyoucan'tevenlogintotheboxto
figureouthowscreweditreallyis).
Node.jsisSINGLETHREADEDandLOCKFREE.Node.js,asaverydeliberatedesignchoiceonlyhasasinglethreadperprocess.Becauseofthis,it's
fundamentallyimpossibleformultiplethreadstoaccessdatasimultaneously.Thus,nolocksareneeded.Threadsarehard.Reallyreallyhard.Ifyoudon'tbelieve
that,youhaven'tdoneenoughthreadedprogramming.Gettinglockingrightishardandresultsinbugsthatarereallyhardtotrackdown.Eliminatinglocksand
multithreadingmakesoneofthenastiestclassesofbugsjustgoaway.Thismightbethesinglebiggestadvantageofnode.
ButhowdoItakeadvantageofmy16corebox?
Twoways:
1. Forbigheavycomputetaskslikeimageencoding,Node.jscanfireupchildprocessesorsendmessagestoadditionalworkerprocesses.Inthisdesign,you'd
haveonethreadmanagingtheflowofeventsandNprocessesdoingheavycomputetasksandchewinguptheother15CPUs.
2. Forscalingthroughputonawebservice,youshouldrunmultipleNode.jsserversononebox,onepercore,usingcluster(WithNode.jsv0.6.x,theofficial
"cluster"modulelinkedherereplacesthelearnboostversionwhichhasadifferentAPI).TheselocalNode.jsserverscanthencompeteonasockettoaccept
newconnections,balancingloadacrossthem.Onceaconnectionisaccepted,itbecomestightlyboundtoasingleoneofthesesharedprocesses.Intheory,
thissoundsbad,butinpracticeitworksquitewellandallowsyoutoavoidtheheadacheofwritingthreadsafecode.Also,thismeansthatNode.jsgets
excellentCPUcacheaffinity,moreeffectivelyusingmemorybandwidth.
Node.jsletsyoudosomereallypowerfulthingswithoutbreakingasweat.SupposeyouhaveaNode.jsprogramthatdoesavarietyoftasks,listensonaTCPport
forcommands,encodessomeimages,whatever.Withfivelinesofcode,youcanaddinanHTTPbasedwebmanagementportalthatshowsthecurrentstatusof
activetasks.ThisisEASYtodo:
varhttp=require('http');
http.createServer(function(req,res){
res.writeHead(200,{'ContentType':'text/plain'});
res.end(myJavascriptObject.getSomeStatusInfo());
}).listen(1337,"127.0.0.1");
NowyoucanhitaURLandcheckthestatusofyourrunningprocess.Addafewbuttons,andyouhavea"managementportal".IfyouhavearunningPerl/Python
/Rubyscript,just"throwinginamanagementportal"isn'texactlysimple.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 259/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Butisn'tJavaScriptslow/bad/evil/spawnofthedevil?JavaScripthassomeweirdoddities,butwith"thegoodparts"there'saverypowerfullanguagethere,
andinanycase,JavaScriptisTHElanguageontheclient(browser).JavaScriptisheretostayotherlanguagesaretargetingitasanIL,andworldclasstalentis
competingtoproducethemostadvancedJavaScriptengines.BecauseofJavaScript'sroleinthebrowser,anenormousamountofengineeringeffortisbeing
thrownatmakingJavaScriptblazingfast.V8isthelatestandgreatestjavascriptengine,atleastforthismonth.Itblowsawaytheotherscriptinglanguagesinboth
efficiencyANDstability(lookingatyou,Ruby).Andit'sonlygoingtogetbetterwithhugeteamsworkingontheproblematMicrosoft,Google,andMozilla,
competingtobuildthebestJavaScriptengine(It'snolongeraJavaScript"interpreter"asallthemodernenginesdotonsofJITcompilingunderthehoodwith
interpretationonlyasafallbackforexecuteoncecode).Yeah,weallwishwecouldfixafewoftheodderJavaScriptlanguagechoices,butit'sreallynotthatbad.
Andthelanguageissodarnflexiblethatyoureallyaren'tcodingJavaScript,youarecodingSteporjQuerymorethananyotherlanguage,inJavaScript,the
librariesdefinetheexperience.Tobuildwebapplications,youprettymuchhavetoknowJavaScriptanyway,socodingwithitontheserverhasasortofskillset
synergy.Ithasmademenotdreadwritingclientcode.
Besides,ifyouREALLYhateJavaScript,youcanusesyntacticsugarlikeCoffeeScript.OranythingelsethatcreatesJavaScriptcode,likeGoogleWebToolkit
(GWT).
SpeakingofJavaScript,what'sa"closure"?Prettymuchafancywayofsayingthatyouretainlexicallyscopedvariablesacrosscallchains.)Likethis:
varmyData="foo";
database.connect('user:pass',functionmyCallback(result){
database.query("SELECT*fromFoowhereid="+myData);
});
//NotethatdoSomethingElse()executes_BEFORE_"database.query"whichisinsideacallback
doSomethingElse();
Seehowyoucanjustuse"myData"withoutdoinganythingawkwardlikestashingitintoanobject?AndunlikeinJava,the"myData"variabledoesn'thavetobe
readonly.Thispowerfullanguagefeaturemakesasynchronousprogrammingmuchlessverboseandlesspainful.
Writingasynchronouscodeisalwaysgoingtobemorecomplexthanwritingasimplesinglethreadedscript,butwithNode.js,it'snotthatmuchharderandyou
getalotofbenefitsinadditiontotheefficiencyandscalabilitytothousandsofconcurrentconnections...
editedJun22'13at10:08 answeredJul21'11at20:37
share
PeterMortensen DaveDopson
8,445105794 20.3k96167
87 +1GreatexplanationcraftsmanJan31'12at8:18
1 @craftsmanThanks.I'vebeenusingthispost/wikitohelpcollectmyownthoughtsontheplatform.DaveDopsonFeb1'12at18:06
4 Fantasticwriteup.Iactuallyespeciallylikedyournotesontesting.Greatstuff.PhaedrusFeb18'12at9:11
@Nickthatisfalse."concurrencyissues"aremitigatedbythefactthatnodeissinglethreaded.Lockinginnodesimplydoesnotexistitisnotneededina
1
singlethreadedparadigm.DaveDopsonFeb22'12at23:24
9 +1.ThisiseasilythelongestpostI'vereadthatdidn'tresultinatl;drcomment.PhillipSchmidtAug9'12at14:42
|show17morecomments
V8isanimplementationofJavaScript.ItletsyourunstandaloneJavaScriptapplications(amongotherthings).
Node.jsissimplyalibrarywrittenforV8whichdoeseventedI/O.Thisconceptisabittrickiertoexplain,andI'msuresomeonewillanswerwithabetter
explanationthanI...Thegististhatratherthandoingsomeinputoroutputandwaitingforittohappen,youjustdon'twaitforittofinish.Soforexample,ask
forthelasteditedtimeofafile:
//Pseudocode
stat('somefile')
Thatmighttakeacoupleofmilliseconds,oritmighttakeseconds.WitheventedI/Oyousimplyfireofftherequestandinsteadofwaitingaroundyouattacha
callbackthatgetsrunwhentherequestfinishes:
upvote //Pseudocode
86down stat('somefile',function(result){
vote //Usetheresulthere
});
//...morecodehere
ThismakesitalotlikeJavaScriptcodeinthebrowser(forexample,withAjaxstylefunctionality).
Formoreinformation,youshouldcheckoutthearticleNode.jsisgenuinelyexcitingwhichwasmyintroductiontothelibrary/platform...Ifounditquitegood.
editedJun22'13at9:17 answeredDec10'09at23:19
share
PeterMortensen rfunduk
8,445105794 17.9k24044
HowiseventedIOimplementedwithoutusinglocks,usingthreading,process,closures?AndIhaveafeelingthattheconceptsarequitesimilartothatof
4
functionalprogrammingandErlang.JeffDec10'09at23:35
It'simplementedasasimpleeventloop,asfarasIknow.v8hasthecallback/etcfunctionalityalready,justlikeanyjavascriptimplementation.rfunduk
1
Dec11'09at0:28
TheIOeventloopofnode.jsmeansthatatanygivenpointoftimeatmostonlyonethingisbeingdone.Iseetwosignificantgains:Thereisnooverhead
2
ofthreadswitching,sonode.jsisveryfast,andsecondlymanytypicalconcurrencybugsJavaisnotoriousforarenotpossible.nalplyApr3'10at9:52
"HowiseventedIOimplementedwithoutusing...closures?"JavaScriptsupportsclosuresandtheyareusedallthetimeinnode.js(anonymousfunctions
1
ansintheexamplehere).panziAug1'10at17:17
@panzi:Didn'tnoticeJeffreyincludedclosuresinhislistofthingsnode.jsisimplemented'without'.Obviouslyeveryfunctioninjavascriptisaclosure
aroundit'sscope:)rfundukAug4'10at11:35
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 260/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
|show1morecomment
Node.jsisanopensourcecommandlinetoolbuiltfortheserversideJavaScriptcode.Youcandownloadatarball,compileandinstallthesource.It
letsyourunJavaScriptprograms.
TheJavaScriptisexecutedbytheV8,aJavaScriptenginedevelopedbyGooglewhichisusedinChromebrowser.ItusesaJavaScriptAPItoaccess
thenetworkandfilesystem.
Itispopularforitsperformanceandtheabilitytoperformparalleloperations.
Understandingnode.jsisthebestexplanationofnode.jsIhavefoundsofar.
upvote36down
vote Followingaresomegoodarticlesonthetopic.
LearningServerSideJavaScriptwithNode.js
ThisTime,YoullLearnNode.js
editedJun22'13at9:23 answeredJan4'11at10:12
share
PeterMortensen AsifMushtaq
8,445105794 8,6601733
addacomment|
Theclosuresareawaytoexecutecodeinthecontextitwascreatedin.
Whatthismeansforconcurencyisthatyoucandefinevariables,theninitiateanonblockingI/Ofunction,andsenditananonymousfunctionforits
callback.
Whenthetaskiscomplete,thecallbackfunctionwillexecuteinthecontextwiththevariables,thisistheclosure.
upvote13down
vote ThereasonclosuresaresogoodforwritingapplicationswithnonblockingI/Oisthatit'sveryeasytomanagethecontextoffunctionsexecuting
asynchronously.
editedJun22'13at9:21 answeredApr12'10at0:56
share
PeterMortensen FireCrow
8,445105794 2,67621928
addacomment|
Twogoodexamplesareregardinghowyoumanagetemplatesanduseprogressiveenhancementswithit.YoujustneedafewlightweightpiecesofJavaScript
codetomakeitworkperfectly.
Istronglyrecommendthatyouwatchandreadthesearticles:
Videoglassnode
Node.jsYUIDOMmanipulation
PickupanylanguageandtrytorememberhowyouwouldmanageyourHTMLfiletemplatesandwhatyouhadtodotoupdateasingleCSSclassnamein
yourDOMstructure(forinstance,auserclickedonamenuitemandyouwantthatmarkedas"selected"andupdatethecontentofthepage).
upvote
8down WithNode.jsitisassimpleasdoingitinclientsideJavaScriptcode.GetyourDOMnodeandapplyyourCSSclasstothat.GetyourDOMnodeand
vote innerHTMLyourcontent(youwillneedsomeadditionalJavaScriptcodetodothis.Readthearticletoknowmore).
Anothergoodexample,isthatyoucanmakeyourwebpagecompatiblebothwithJavaScriptturnedonoroffwiththesamepieceofcode.Imagineyouhavea
dateselectionmadeinJavaScriptthatwouldallowyouruserstopickupanydateusingacalendar.Youcanwrite(oruse)thesamepieceofJavaScriptcodeto
makeitworkwithyourJavaScriptturnedONorOFF.
editedJun22'13at9:26 answeredFeb28'11at23:44
share
PeterMortensen Renato
8,445105794 15925
addacomment|
ThereisaverygoodfastfoodplaceanalogythatbestexplainstheeventdrivenmodelofNode.js,seethefullarticle,Node.js,DoctorsOfficesandFastFood
RestaurantsUnderstandingEventdrivenProgramming
Hereisasummary:
Ifthefastfoodjointfollowedatraditionalthreadbasedmodel,you'dorderyourfoodandwaitinlineuntilyoureceivedit.Thepersonbehindyou
wouldn'tbeabletoorderuntilyourorderwasdone.Inaneventdrivenmodel,youorderyourfoodandthengetoutoflinetowait.Everyoneelse
isthenfreetoorder.
Node.jsiseventdriven,butmostwebserversarethreadbased.YorkexplainshowNode.jsworks:
upvote7 Youuseyourwebbrowsertomakearequestfor"/about.html"onaNode.jswebserver.
down
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 261/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
vote TheNode.jsserveracceptsyourrequestandcallsafunctiontoretrievethatfilefromdisk.
WhiletheNode.jsserveriswaitingforthefiletoberetrieved,itservicesthenextwebrequest.
Whenthefileisretrieved,thereisacallbackfunctionthatisinsertedintheNode.jsserversqueue.
TheNode.jsserverexecutesthatfunctionwhichinthiscasewouldrenderthe"/about.html"pageandsenditbacktoyourwebbrowser."
editedJun22'13at10:13 answeredDec19'11at23:28
share
PeterMortensen adeleinr
8,445105794 465411
addacomment|
Well,Iunderstandthat
Node'sgoalistoprovideaneasywaytobuildscalablenetworkprograms.
NodeissimilarindesigntoandinfluencedbysystemslikeRuby'sEventMachineorPython'sTwisted.
EventedI/OforV8javascript.
upvote6downvote Formethatmeansthatyouwerecorrectinallthreeassumptions.Thelibrarysurelookspromising!
answeredDec10'09at23:17
share
nes1983
7,70822748
1 AlotofthetimesIfindaboutpageisquitevague.JeffDec10'09at23:23
addacomment|
Also,donotforgettomentionthatGoogle'sV8isVERYfast.ItactuallyconvertstheJavaScriptcodetomachinecodewiththematchedperformanceof
compiledbinary.Soalongwithalltheothergreatthings,it'sINSANELYfast.
upvote6 editedJun22'13at10:11 answeredNov29'11at15:15
downvote
share
PeterMortensen QuintonPike
8,445105794 97611929
addacomment|
Q:Theprogrammingmodeliseventdriven,especiallythewayithandlesI/O.
Correct.Itusescallbacks,soanyrequesttoaccessthefilesystemwouldcausearequesttobesenttothefilesystemandthenNode.jswouldstartprocessingits
nextrequest.ItwouldonlyworryabouttheI/Orequestonceitgetsaresponsebackfromthefilesystem,atwhichtimeitwillrunthecallbackcode.However,it
ispossibletomakesynchronousI/Orequests(thatis,blockingrequests).Itisuptothedevelopertochoosebetweenasynchronous(callbacks)orsynchronous
(waiting).
Q:ItusesJavaScriptandtheparserisV8.
up
vote3 Yes
down
vote Q:Itcanbeeasilyusedtocreateconcurrentserverapplications.
Yes,althoughyou'dneedtohandcodequitealotofJavaScript.Itmightbebettertolookataframework,suchashttp://www.easynodejs.com/whichcomes
withfullonlinedocumentationandasampleapplication.
editedJun22'13at10:22 answeredMar9'12at12:47
share
PeterMortensen Charles
8,445105794 311
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavascriptnode.jsv8eventedioorask
yourownquestion.
asked 5yearsago
viewed 231071times
active 2yearsago
Lookingforajob?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 262/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Gettheweeklynewsletter!
Topquestionsand
answers
Important
announcements
Unanswered
questions
Signupforthenewsletter
Linked
3
ServersidejavascriptGeneral
6
Whatisthenode.jsanditspurpose?
298
Node.jsonmulticoremachines
119
JavaScript,Node.js:isArray.forEachasynchronous?
19
WhatisthepointofNode.js
4
nodejsparallelcallbackdesignpattern
6
HowtomakeNode.jsMultitenantforwebsitesonport80?
12
Usingnode.jsinaproductionenvironment
8
Node.jsrequireisnotdefinedexception
4
ParallelizingtasksinNode.js
seemorelinkedquestions
Related
3582
WhatdoesusestrictdoinJavaScript,andwhatisthereasoningbehindit?
1267
HowdoIgetstartedwithNode.js
163
WhatistheHaskellresponsetoNode.js?
214
IDEforNode.js/Javascript?
17
Whataresomearchitecturalreasonstousenode.jsasidefromscalability?
490
Node.js+NginxWhatnow?
1551
HowtodecidewhentouseNode.js?
423
WhatisNode.js'Connect,Expressandmiddleware?
616
WhatisthepurposeofNode.jsmodule.exportsandhowdoyouuseit?
9
HowdoestheNode.jseventloopwork?
HotNetworkQuestions
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 263/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ALN*NTicTacToeGame
Doblockingcreatureshealbacktofullbetweenphases?
Whydotheymanifestasrings?
Drawarrowinamindmap
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
Jumpingcarwithtoomanyamps?
WhydosomepeoplerefertoLinuxasGNU/Linux?
Needtostartareligionwithapredefinedselfdestruct
Passfilenamefrombashtopython
Whatwereshoesolesmadefrominpreviousages?
Howtodrawsequenceofshapeswitharrowsandtext
DoesCIDRreally"doaway"withIPaddressclasses?
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
Paidcashforacar,butdealerwantstochangeprice
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
HowcanIcheckifmyfunctionprint/echo'ssomething?
Howtoprotectaspaceelevatoragainstterrorism
FiveAnglesinaStar
FindingoutifawordisanAnagramofanother
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
Removestaticobjectsfromanimagesequence
Patchingabinarywithdd
CanIwriteapaperoutofasimpleidea
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 264/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ConvertaBSTintopreorderandpostorderlinkedlists
Thisisaround2Amazoninterviewquestion.ConvertagivenBinarySearchTreeintopreorderandpostorderlinkedlistsandthisconversion
hastobeinplace.
upvote1downvote linkedlistbinarysearchtreeinplacepreorderpostorder
favorite askedJul25'14at17:43
editedJul28'14at15:08
share|improvethisquestion
user3660655
83
addacomment|
3Answers
activeoldestvotes
voidpreorder(structnode*head)
{
if(head)
{
addToLL(head>data);
preorder(head>left);
preorder(head>right);
}
}
IntheaddToLL()youcanjustkeepaddingthenodestothelinkedlist.
upvote0downvote
GlobalDeclaration
structnode*llHead;
Sothatthelinkedlistheadisintact.
answeredJul28'14at12:53
editedJul28'14at16:42
share|improvethisanswer
Gopi
15.5k31128
Wehavetoconvertitinplaceuser3660655Jul28'14at15:07
addacomment|
Tosolvethepreorderversionoftheproblem,youcanslightlymodifyasimplepreorder(Refercodebelowtoseethat).
Theideaistoconstructadoublylinkedlistfromthebinarysearchtreeinapreordertraversal.However,weonlysettheforwardlinksduringthe
traversal.
Let'slearnthroughanexample.Ifthetreelookslike:
4
/\
26
/\/\
1357
Then,thelinkedlistshouldlooklike:
4<>2<>1<>3<>6<>5<>7.
Now,weonlysetforwardlinksduringpreordertraversal.Therefore,ourlistwilllooklike.
4>2>1>3>6>5>7
Theleftorpreviouspointers(notshownabove)arestillastheywereinthetree.Wecansettheleftpointersthroughasimpletraversalofthelist
now.
Thecodebelowdoesexactlythis.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 265/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
#include<iostream>
usingnamespacestd;
classnode{
public:
intdata;
node*left,*right;
node(inta){
data=a;
left=right=NULL;
}
};
node*head=NULL,*prev=NULL;
voidpreorder(node*root){
if(!root)return;
//bothheadandprevaren'tset.Thisnodemustbetheroot(andheadofourrequiredlist).
if(!headand!prev)head=root;
upvote0down //storetheaddressofroot'srightchild
vote node*temp=root>right;
/*
Ifprevisset,makecurrentnodeit'srightchild.
(Thisiswhywesaverightchild'saddressforeverynodeintemp.)
*/
if(prev)prev>right=root;
//nowmakethecurrentnodeprev.
prev=root;
cout<<root>data<<"";
preorder(root>left);
preorder(temp);
}
voidprintll(){
node*prev=NULL;
while(head!=NULL){
cout<<head>data<<"";
head>left=prev;
head=head>right;
prev=head;
}
cout<<endl;
}
intmain(){
node*t=newnode(4);
t>left=newnode(2);
t>left>left=newnode(1);
t>left>right=newnode(3);
t>right=newnode(6);
t>right>left=newnode(5);
t>right>right=newnode(7);
preorder(t);
cout<<endl;
printll();
return0;
}
answeredJul29'14at8:38
share|improvethisanswer
rajeshtomar
1
addacomment|
Thebelowalgorithmisforthepreorderconversion.Similarlyyoucandothepostorder.
structnode
{
intdata;
structnode*left;
structnode*right;
};
/Algorithm*/
structnode*bintree2listHelper(structnode*root)
{
if(root==NULL)
returnroot;
if(root>left!=NULL)
{
structnode*left=bintree2listHelper(root>left);
intflag=0;
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 266/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
if(left>left==NULL)
{
left>left=left>right;
}
for(;left>left!=NULL;)
{
structnode*temp=left;
for(;temp>right!=NULL;)
{
flag=1;
temp=temp>right;
}
if(flag)
{
temp>left=root>right;
left=left>left;
break;
}
else
{
left=left>left;
}
if(!flag)
left>left=root>right;
}
if(root>right!=NULL)
{
structnode*right=bintree2listHelper(root>right);
structnode*temp1=right;
for(;right>left!=NULL;)
upvote0downvote {
temp1=right;
right=right>left;
}
right>left=temp1>right;
}
returnroot;
}
structnode*bintreeTolist(structnode*root)
{
if(root==NULL)
returnroot;
root=bintree2listHelper(root);
return(root);
}
structnode*newNode(intdata)
{
structnode*new_node=(structnode*)malloc(sizeof(structnode));
new_node>data=data;
new_node>left=new_node>right=NULL;
return(new_node);
}
voidprintList(structnode*node)
{
while(node!=NULL)
{
printf("%d",node>data);
node=node>left;
}
printf("\n");
}
intmain()
{
typedefstructnodenode;
node*root=newNode(10);
root>left=newNode(12);
root>right=newNode(15);
root>left>left=newNode(25);
root>left>right=newNode(30);
root>right>left=newNode(36);
root>left>right>left=newNode(78);
root>left>right>right=newNode(77);
node*head=bintreeTolist(root);
//Printtheconvertedlist
printList(head);
return0;
answeredAug4'14at13:36
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 267/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
editedAug22'14at6:46
share|improvethisanswer
Gopi
15.5k31128
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedlinkedlistbinarysearchtreeinplace
preorderpostorderoraskyourownquestion.
asked 11monthsago
viewed 360times
active 10monthsago
Lookingforajob?
ChiefSoftwareArchitectJava$100K
Crossover
Bengaluru,India/remote
eclipsenetbeans
Sr.DevelopmentEngineer
AudienceScience
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 268/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Pune,India
javahadoop
Related
1278
WhentouseLinkedListoverArrayList?
2
HowmanytraversalsneedtobeknowntoconstructaBST
1
PreorderBinarySearchTreeInsertion
0
WorsttimecomplexityofaBST(traversingitpostorder)
0
What'swrongwithmyideaaboutpreordertraversal
1
PreOrderSuccessorofaNodeinBST
0
BinarySearchTreeTraversalinJava(outputnotcomingcorrect)
0
OutputPostOrderBinarySearchTreefromGivenPreOrderinputwithoutconstructingtreeorusingrecursions
0
HowcanIcallmyfunctionstocalculatepreorderoftheBST?
0
AllelementsorderinXMLpreorderandpostordertraversalinc#
HotNetworkQuestions
Alarmclockprinting
Isthereawordforpeopleincapableofthinking?
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
CanIflywithagoldbar?
FiveAnglesinaStar
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Whatisatemporarysolutionforadamagedcarbody?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
Whyshouldakeybemadeexplicit?
DoesaUSB3.0connectionrequireaUSB3.0cord?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Isturninggraphitecarbonintodiamondindustriallydoable?
Doblockingcreatureshealbacktofullbetweenphases?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Antiferromagneticordering
Canmathbesubjective?
HowdoIupgradefromGPLv2toGPLv3?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
Derivativeofadefiniteintegralissue
Drawarrowinamindmap
Troublewithterminatinga<apex:pageBlockSection>
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
PythonLabelExpression?ArcGIS10.3.1
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 269/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Longestrunningsequencefromallpermutationsofarrayofstrings
FromarecentinterviewofAmazon,Ifoundthefollowingquestion.Icouldnotfigureoutaneffectivewaytosolveit.
Theproblemreadsas:
Givenanarrayofstrings,youneedtofindthelongestrunningsequenceofacharacteramongallpossiblepermutationsofthestringsinthearray.
INPUT:
ab
ba
upvote4 aac
down OUTPUT:
vote a,3
favorite
1 Note:Fromtheinputandoutputset,Ithinkthepermutationoftheindividualstringsisnottobedone.
Wouldreallyappreciateifsomebodycanhelp.Thanks.
arraysstringalgorithmdatastructurespermutation
askedDec19'12at11:48
editedDec19'12at12:04
share|improvethisquestion
DipeshGupta
300212
2 Pleasedescribehowthelongestrunningsequenceisformed.Thequestionisnotcleartome.PetarMinchevDec19'12at11:53
Titlesayscombinationsandthedescriptionsayspermutations.FarukSahinDec19'12at11:54
FarukSahin:Ihaveeditedthetitle.Apologiesforthemistake.DipeshGuptaDec19'12at12:05
@PetarMinchev:Sointhiscaseofyoutakethethreestringsasthreealphabets(LetssayX=ab,Y=ba,Z=aac)theninthepermutationXYZ(canbe
YZXalso),thelettersareas:"abbaaac".TheletterscomprisingXorYorZneednottobepermutedamongstthemselves.Sointheabovesequencethe
consecutivesequenceofthecharacter"a"comesasthreetimesconseutively.Hencetheoutput.DipeshGuptaDec19'12at12:09
Ithink,theOPmeans"LongestCommonSubsequence"wildplasserDec19'12at12:10
|show1morecomment
6Answers
activeoldestvotes
Lovelyquestion.Somanycornercases.I'mguessingthatthewholepointofthisinterviewquestionistoseehowmanycornercasesyoucomeup.
IhopeIhaven'tmissedany.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 270/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Thereareessentiallytwowaysthatacharactersequencecouldbethesolutiontothisproblem:
1)Itisaninteriorcharactersequence(eg.adddddddddddddddddb)
2)Itistheconcatentationofasuffix,theentirecollectionofstringsconsistingonlyofthatcharacter,andaprefix.Inthiscase,nostringmaybeusedmorethan
once,includingthecasewhereacharacteristhesuffixandtheprefixofthesamestring.(Toavoidresuingthehomogenousstrings,thesuffixesandprefixesmust
bestricti.e.nottheentirestring).
Case1iseasy.Wesimplyrememberasinglecharacterandsequencelength,andthecurrentcharacterandsequencelength.Aswereadinthestrings,ifthecurrent
character/sequencelengthislongerthanthemaximum,wereplacethemaximum.Wedon'tneedtoworryaboutitconflictingwiththecomputationsdoneforCase
2,becauseitwon'taffecttheresult.
Case2isalotmorework.Foreachcharacter,weneedtokeepsomedata.Wecaneitheruseafixedsizearray,oneentrypercharacterinthealphabet,ifthe
alphabetissmall,orwecanuseahashtableofcharacters.BothareO(1)onaveragesincethenumberofcharacterswe'lldealwithcannotbelargerthanthetotal
numberofcharactersinallthestrings,thesizerequirementofthehashtablecanbethoughtofasO(N).(Infact,itislimitedbythesizeofthealphabet,sojustas
withthefixedsizearray,thestoragerequirementistechnicallyO(1)butinthecaseofUnicode,forexample,theconstantisratherlarge.)
up Now,whatdatadoweneed?Stringswhicharejustarepetitionofasinglecharacterareeasyweneedthetotallengthofthosestrings.Soeverytimewefindsuch
vote astring,wecanadditslengthtothetotallengthmemberoftheentryinourpercharacterdata.
2
down For(strict)suffixesandprefixes,itseemslikeweonlyneedtomaintainamaximumlengthforeach.Butwhatifweencounterastringwhoseprefixandsuffix
vote sequencesarethesamecharacter,andbothofthesequencesarelongerthananythatwe'vehandledpreviously?Wecan'tusethestringasbothsuffixandprefix.
Fortunately,thereisasimpleanswer:wekeepthreevalues:maximum_prefix,maximum_suffix,maximum_sum.Ifwe'reupdatingthetableafterreadingaword,
anditturnsoutthatthesamecharacterisbothprefixandsuffix,weupdatethethreevaluesasfollows:
maximum_sum=max(maximum_sum,
prefix_length+maximum_suffix,
suffix_length+maximum_prefix)
maximum_prefix=max(maximum_prefix,prefix_length)
maximum_suffix=max(maximum_suffix,suffix_length)
Notethattheabovepseudocodeworksjustfine(ifabitwastefully)ifeitherprefix_lengthorsuffix_lengthis0.
Sothat'satotaloffourpercharactervalues:homogenous_length,maximum_sum,maximum_prefix,maximum_suffix.Attheendofthescan,weneedtofindthe
characterforwhichhomogenous_length+maximum_sumisthegreatestwecandothatbyasimplescanoverthecharactertable.
TotalprocessingtimeisO(1)percharacter(fortheinitialscan),whichisO(N)(whereNisthetotalnumberofcharactersintheproblem,plusO(max(N,|A|))for
thefinalscanofthecharactertable(|A|isthesizeofthealphabet)inotherwords,O(N).Spacerequirementsweredescribedabove.
answeredDec19'12at16:18
share|improvethisanswer
rici
68k84695
doesitconsidersthecasewheremaximumprefixandmaximumsuffixareofthesameword?user2368055Aug10'14at9:58
@user2368055:yes.maximumsumisalwaysthebestcurrentsumofprefixandsuffixoftwodifferentwords.riciAug10'14at14:50
addacomment|
Youcanusehashmapsforthat.Theslowestalgorithmwillbetomakeamapofcharactercountersforeverystring,andthenfindthemaximum.
Iwouldliketoknowmoreadvancedalgorithmtoo
upvote0down
vote answeredDec19'12at11:55
share|improvethisanswer
DmitryZheshinsky
38918
Thissolutionfailsforthetestcase,countingcharacterswillreturna,4andnota,3(UnlessImisunderstoodyouandthen,pleaseelaborate)
amitDec19'12at12:04
addacomment|
ThisismynaiveRubyimplementation.IwilltryexplainhowIreasonedandimplementedit.
InRubyastringisn'tanenumerablesoRubycan'tenumerateoveritdirectlylikePythoncan.That'swhatstr.chars.to_asolves.Itconvertsthestringtoan
arrayofcharacters.
Myplanwastocountthenumberoftimesacharacteroccurredineachstring.["ab","ba","ccc"]wouldbecome[{"a"=>1,"b"=>1},{"b"=>1,"a"=>1},
{"c"=>3}].ThenIwouldaddthenumberofoccurrencesofeachconsecutivepairofhashes/dictionaries.Inthisexampleitwouldresultin[{"a"=>2,"b"=>2},
{"b"=>1,"a"=>1,"c"=>3}].Thehighestvalueinthisarrayofhasheswouldthenrepresentthelongestrunningsequence.
Theproblemisthatstringsthatcontainsthesamecharacteroverandoveragainwillmakethisalgorithmbreakdown.Mysolutiontothisistocheckforthese
kindofstringsandthenconcatenatethesewiththefollowingstringifthatstringcontainsanysuchcharacter.Thisisimplementedinthearr_of_chararr.eachin
themax_running_sequencemethod.
ThepairwiseadditionisimplementedwithHash#mergeandablock,exceptforthespecialcasewhenthere'sonlyoneelementinthearray.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 271/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
AtlastIscanthearrayofhashesforthemaxvalue.
classSequence_tester
defself.max_running_sequence(arr_of_chararr)
reduced=[]
all_same_chars=[]
arr_of_chararr.eachdo|str|
arr=str.chars.to_a
ifarr.all?{|c|c==arr.first}
all_same_chars+=arr
else
if!all_same_chars.empty?
ifarr.any?{|c|c==all_same_chars.first}
arr+=all_same_chars
else
reduced<<count_char_occurrences(all_same_chars)
end
end
reduced<<count_char_occurrences(arr)
all_same_chars.clear
end
end
up
vote0 if!all_same_chars.empty?
down reduced<<count_char_occurrences(all_same_chars)
end
vote
max_seqs=reduced
ifreduced.length>1
max_seqs=reduced.each_cons(2).mapdo|pair|
pair.first.merge(pair.last){|key,oldval,newval|oldval+newval}
end
end
longest_seq=max_seqs.map{|h|h.max_by{|kv|kv[1]}}.max_by{|a|a[1]}
end
defself.count_char_occurrences(arr)
arr.each_with_object(Hash.new(0)){|o,h|h[o]+=1}
end
end
input=["a","b","c"]
res=Sequence_tester.max_running_sequence(input)
puts"#{res.first},#{res.last}"
input=["abc","abb","abc"]
res=Sequence_tester.max_running_sequence(input)
puts"#{res.first},#{res.last}"
input=["ab","ba","ccc"]
res=Sequence_tester.max_running_sequence(input)
puts"#{res.first},#{res.last}"
input=["ada","dd","dd","eedd"]
res=Sequence_tester.max_running_sequence(input)
puts"#{res.first},#{res.last}"
Outputs:
a,1
b,3
c,3
d,7
answeredDec19'12at21:23
editedDec19'12at21:54
share|improvethisanswer
JonasElfstrm
18k3572
addacomment|
#include<iostream>
usingnamespacestd;
classalphabet
{
stringstr;
intchars[26];
public:
alphabet()
{
for(inti=0;i<26;i++)
chars[i]=0;
voidinitialize(strings)
{
str=s;
for(intpos=0;pos<s.length();pos++)
chars[s[pos]'a']++;
}
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 272/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
intgetCount(inti)
{
returnchars[i];
}
};
upvote0down
vote intmain()
{
intn=3;
alphabet*arr=newalphabet[n];
arr[0].initialize("varun");
arr[1].initialize("ritl");
arr[2].initialize("hello");
intMax=0;
charMaxChar='';
for(inti=0;i<n1;i++)
{
for(intj=0;j<26;j++)
{
intm=arr[i].getCount(j)+arr[i+1].getCount(j);
if(m>Max)
{
Max=m;
MaxChar=char('a'+j);
}
}
}
cout<<"MaxChar="<<MaxChar<<""<<Max<<"times";
system("pause");
}
answeredApr20'13at17:49
share|improvethisanswer
crashed
11
Iamnotveryclearwiththequestion,belowismyunderstanding:wehavetofindlongestoccurrenceofacharacterwhenindividualstringscanbe
permuted.crashedApr20'13at17:55
addacomment|
Inaninterview,Icouldhavecomeupwiththebasicmechanicstosolvethisproblem,butIwouldhavefailedtowritetheentire,errorfreesolutionon
awhiteboard.Debuggercrutch.
Atanyrate,hereismysolutioninC#.
1.)Idefinedtheset.
varset=newList<string>(){"ab","ba","aac"};
2.)Iassembledagenericmethodtoassembleallpermutations,recursively.
privatestaticList<List<T>>GetPermutations<T>(List<T>values)
{
if(values.Count<=1)returnnewList<List<T>>(){values};
varresults=newList<List<T>>();
varperms=GetPermutations(values.Skip(1).ToList());
foreach(varperminperms)
{
foreach(intiinEnumerable.Range(0,perm.Count+1))
{
List<T>list=newList<T>();
list.AddRange(perm.Take(i));
list.Add(values[0]);
list.AddRange(perm.Skip(i));
results.Add(list);
}
}
returnresults;
}
3.)Ifoundallpermutationsoftheset.
varperms=GetPermutations<string>(set);
4.)Idefinedamethodtofindthelongestrunningsequenceinasinglestring.
privatestaticstringLongestRunningSequence(strings)
{
if(string.IsNullOrEmpty(s))returnnull;
if(s.Length==1)returns;
varseq=newDictionary<char,int>();
charprev=s[0];
intcounter=0;
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 273/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
upvote0down foreach(charcurins)
vote {
if(cur==prev)//charsmatch
{
++counter;//incrementcounter
}
else//charsdon'tmatch
{
prev=cur;//storenewchar
counter=1;//resetthecounter
}
//storethehighernumberofcharactersinthesequence
if(!seq.ContainsKey(prev))seq.Add(prev,counter);
elseif(seq[prev]<counter)seq[cur]=counter;
}
charkey=seq.Keys.First();
foreach(varkvpinseq)
{
if(kvp.Value>seq[key])key=kvp.Key;
}
returnstring.Join("",Enumerable.Range(0,seq[key]).Select(e=>key));
}
5.)Idefinedamethodthatfoundthelongestrunningsequenceinalistofstrings,takingadvantageofthepreviousmethodthatdoessoforasingle
string.
privatestaticstringLongestRunningSequence(List<string>strings)
{
stringlongest=String.Empty;
foreach(varstrinstrings)
{
varlocallongest=LongestRunningSequence(str);
if(locallongest.Length>longest.Length)longest=locallongest;
}
returnlongest;
}
6.)Iexpressedeachcalculatedpermutationasalistofsinglestrings.
varstrings=perms.Select(e=>string.Join("",e)).ToList();
7.)Ipassedthislisttotheearliermethodthatfindsthelongestrunningsequenceinalistofstrings.
LongestRunningSequence(strings);//returnsaaa
answeredJun25'13at16:42
share|improvethisanswer
DanGroft
1
addacomment|
Step1:4tablesneedstobemaintainedoflength26FirstonekeepstrackofthelengthofthelongestprefixinthestringSecondonekeepstrackofthe
lengthofthelongestsuffixinthestringThirdonekeepstrackoftheTOTALlengthofstringsthatconsistentirelyofagivencharacterFourthkeepstrackof
longestcharacterinthemiddle
Step2:Runloopfor0to26andaddfirst[i]+second[i]+third[i]andstoretheminsum[i]findthemaximumelementinsum[i]andfourthtable.indexisthe
alphabet(0isA)andmaximumelementisthelength
#include<stdio.h>
#include<string.h>
#include<ctype.h>
intpre[26],su[26],single[26],middle[26],sum[26];
intgetlength(charstr[][10])
{
inti,j,n=3,counter=0,max=1,index;
charc,p;
for(j=0;j<n;j++)
{
for(i=0;i<strlen(str[j]);i++)
{
if(i==0)
{
c=str[j][i];
counter++;
continue;
}
elseif(i==strlen(str[j])1&&c==str[j][i])
{
counter=0;
break;
}
else
{
if(c==str[j][i])
counter++;
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 274/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
else
break;
}
}
if(pre[toupper(c)65]<counter)
pre[toupper(c)65]=counter;
counter=0;
}
for(j=0;j<n;j++)
{
for(i=strlen(str[j])1;i>=0;i)
{
if(i==strlen(str[j])1)
{
c=str[j][i];
counter++;
continue;
}
elseif(i==0&&c==str[j][i])
{
counter=0;
break;
}
else
{
if(c==str[j][i])
counter++;
else
break;
}
}
if(su[toupper(c)65]<counter)
su[toupper(c)65]=counter;
counter=0;
}
for(j=0;j<n;j++)
{
for(i=strlen(str[j])1;i>=0;i)
{
if(i==strlen(str[j])1)
{
c=str[j][i];
upvote counter++;
0down continue;
vote }
else
{
if(c==str[j][i])
counter++;
else
{
counter=0;
break;
}
}
}
if(single[toupper(c)65]<counter)
single[toupper(c)65]=counter;
counter=0;
}
counter=0;
for(j=0;j<n;j++)
{
for(i=1;i<strlen(str[j])1;i++)
{
if(i==1)
{
c=str[j][i];
counter++;
}
else
{
if(c==str[j][i])
{
counter++;
}
else
{
if(middle[toupper(c)65]<counter)
middle[toupper(c)65]=counter;
counter=1;
c=str[j][i];
}
}
}
counter=0;
}
for(i=0;i<26;i++)
{
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 275/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
sum[i]=pre[i]+su[i]+single[i];
if(sum[i]>max)
{
max=sum[i];
index=i;
}
}
for(i=0;i<26;i++)
{
if(middle[i]>max)
{
max=middle[i];
index=i;
}
}
printf("\nlength%dindex%d",max,index);
}
voidmain()
{
chararr[3][10]={"bbbb","dccccccar","vaa"};
getlength(arr);
}
answeredSep7'14at7:36
share|improvethisanswer
aman_41907
52
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 276/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedarraysstringalgorithmdatastructures
permutationoraskyourownquestion.
asked 2yearsago
viewed 1276times
active 10monthsago
Lookingforajob?
ApplicationsEngineer
Kavi
Portland,OR
perllamp
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Related
9
Stringpermutationsrank+datastructure
3
generateallpermutationsinorderwithoutusingexcessivememory
6
Printingallpossiblewordsfroma2Darrayofcharacters
1
VariationofpermutationofanarraycontainingIntegers
0
Mappingofpermutedarrays
0
Permutationofintegersfromanarraygivenlengh
3
Howtoprovethattwostringsarepermutationsofeachother?
0
RecursiveStringpermutationwithrepetitionsallowed
0
HowcanIcountthenumberofpermutationsofsomestringmatchingasetofsubsets?
1
Algorithmstofindpermutationofastring
HotNetworkQuestions
Drawarrowinamindmap
CanICultureBombfaraway?
ImageOpensasLayer0ratherthanBackground
Whatistheoriginofthisphotoofanunexplodedbomb?
Jumpingcarwithtoomanyamps?
howcanItaketotalminutesfromtime?
ALN*NTicTacToeGame
Clientwantsfontaslogo
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Needtostartareligionwithapredefinedselfdestruct
Whatisatemporarysolutionforadamagedcarbody?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Whydotheymanifestasrings?
RollmyD&Dcharacter'sabilityscores
Wordfor"animals,includinghumans"?
ThenthTernary
What'sanexpressionforacunninglyfakefriend?
Whyadding"incolour"whenreferringto"WizardofOz"?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Isthereawordforpeopleincapableofthinking?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 277/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Whatis`$?`?Isitavariable?
HowtodealwithaGMwhodoesnottelluseverything?
LeapyearcheckinJava
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Relationaldatabaseformultipleauthorsmultiplebooks
Thisisaquestionmyfriendwasaskedinhisphoneinterviewwithamazon.Designarelationaldatabasetorecordbookswhereabookcanhavemultiple
authorsandanauthorcanpublishmultiplebooks.Hewasaskedtodesigntherelations(tables)andthetypeofeachattribute(whethertext,String,etc)The
problemisthattheyalsowantedtobeabletosearchbothoverAuthorsnamesandbookstitle.Iknowsomethinglikethiswillnotbeveryefficient:
TableAutor
AutorIDAuthorNamebooksIDs(Text)Example:15,MorrisMano:11,56,234
upvote0 TableBook
BookIDBooktitleAuthorsID(Text)Example:11:ComputerArchitecture:15,34,88
down
vote WhatothertypeisbettertouseinsteadoftypeTextforthoseattributeshere?
favorite
mysqldatabaseoracle
askedOct3'13at23:35
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 278/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
share|improvethisquestion
Cgraphics
1,02542567
addacomment|
3Answers
activeoldestvotes
Thebasicthirdnormalformwouldbesomethinglikethisthatmakesuseofanintersectiontable.Storingcommaseparatedvaluesinarelationaltableis
alwaysamistake.
CREATETABLEauthor(
authorIDintegerprimarykey,
authorNamevarchar2(100)
);
CREATETABLEbook(
bookIDintegerprimarykey,
bookTitlevarchar2(100)
);
upvote CREATETABLEauthor_book(
2down authorIDinteger,
vote bookIDinteger,
constraintpk_author_bookprimarykey(authorID,bookID)
);
Now,inreality,youwouldalmostcertainlybreaktheauthornameintoafirstname,lastname,etc.tofacilitatesearching.IfyouareusingOracle,you'd
probablycreateOracleTextindexesinordertofacilitatesearching.Andifyou'reAmazon,you'dpotentiallywantsomeauxiliarytablescreatedtofacilitate
searchingacrossattributesindifferenttables.
answeredOct3'13at23:42
share|improvethisanswer
JustinCave
135k11137194
addacomment|
Youshouldusearelationtabletolinkauthorswithbooks,notputalistofIDsineachtable.
CREATETABLEauthor_book(
author_idINT,
book_idINT,
UNIQUEKEY(author_id,book_id)
);
Togetthebooksofanauthor,ortheauthorsofabook,usea3wayjoin,e.g.
upvote1downvote SELECTBookTitle
FROMBookb
JOINauthor_bookabONb.BooKID=ab.book_id
JOINAuthoraONa.AuthorID=ab.author_id
WHEREAuthorName='JohnSmith';
answeredOct3'13at23:42
share|improvethisanswer
Barmar
188k1574140
addacomment|
Iwouldhavedonethis:
Author(AuthorId,AuthorName,etc.)
PK:AuthorId
Book(BookId,BookName,ISBN,Edition,etc)
PK:BookId
AuthorBooks(AuthorId,BookId)
PK:(AuthorId,BookId)
FK:AuthorIdfromAuthor,BookIdfromBook(thankstoJustin'sanswerforremindingtoaddthis)
AnotherindexonBookIdtofacilitatequicksearchbyBookId.
NotethatthePKindexcanbeusedtosearchonAuthorId.
Addinganewbook:
1. InsertIntoAuthor
2. InsertIntoBook
upvote1downvote
3. InsertIntoAuthorBook
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 279/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Searchingbyauthorname(assumingauthornameisnotunique):
SELECTab.*,b.*
FROMAuthorBookab,authora
WHEREab.AuthorIdIN(SELECTAuthorId
FROMAuthor
WHEREAuthorName=?)
andsimilarlyforsearchingbybooktitle...
answeredOct3'13at23:45
editedOct3'13at23:51
share|improvethisanswer
VaibhavDesai
1,283513
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedmysqldatabaseoracleoraskyourown
question.
asked 1yearago
viewed 658times
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 280/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
active 1yearago
Lookingforajob?
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
Related
418
HowdoIquicklyrenameamysqldatabase(changeschemaname)?
186
WhatresourcesexistforDatabaseperformancetuning?
59
MySQL'createschema'and'createdatabase'Isthereanydifference
0
Databaseaccessrelatedinfoonclusteredenvironment
508
WhataretheOptionsforStoringHierarchicalDatainaRelationalDatabase?
1
TrueorFalseDatabaserelationconfusionIneedabitofexplainationforthese
1
Howwritedowntodatabasemultipleauthorsinsimplebookstable?
1
Howtodealwithmultipleauthorsreturedfrombookstablequery
1
DatabaseforPHPbooksearch,howtostoremultipleanddifferentnumbersofauthorsdependingonbook
0
Howtoqueryabookwithnoauthorinamanytomanyscenario
HotNetworkQuestions
Whatis`$?`?Isitavariable?
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
Doblockingcreatureshealbacktofullbetweenphases?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
HowcanIcheckifmyfunctionprint/echo'ssomething?
Patchingabinarywithdd
Wordfor"animals,includinghumans"?
Multiplypurefunctionwithscalar
Passfilenamefrombashtopython
Paidcashforacar,butdealerwantstochangeprice
Alarmclockprinting
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
WhydosomepeoplerefertoLinuxasGNU/Linux?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
FiveAnglesinaStar
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
zero,zerosorzeroes?
Howtogetearlyentryintomystictheurge?
Shouldmy(sequential)collectionstartatindex0orindex1?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
WhatdoesitmeanifanACmotorhastwovoltageratings?
HowdoIupgradefromGPLv2toGPLv3?
howcanItaketotalminutesfromtime?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. WordPress
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 281/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
4. Web Development Answers 4. SeasonedAdvice (Judaism) (stats) Exchange
Applications 5. Geographic 3. SharePoint (cooking) 4. Travel 3. Theoretical 3. Area51
5. AskUbuntu InformationSystems 4. User 5. Home 5. Christianity ComputerScience 4. Stack
6. Webmasters 6. Electrical Experience Improvement 6. Arqade(gaming) 4. Physics Overflow
7. Game Engineering 5. Mathematica 6. PersonalFinance 7. Bicycles 5. MathOverflow Careers
Development 7. AndroidEnthusiasts 6. Salesforce &Money 8. Roleplaying 6. more(7)
8. TeX 8. InformationSecurity 7. more(14) 7. Academia Games
LaTeX 8. more(10) 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
AmazonInterviewQuestion:DesignanOOparkinglot[closed]
DesignanOOparkinglot.Whatclassesandfunctionswillithave.Itshouldsay,full,emptyandalsobeabletofindspotforValetparking.Thelothas3
differenttypesofparking:regular,handicappedandcompact.
upvote54 Thanks!
downvote
favorite oop
66 editedApr19'09at6:28 askedApr19'09at6:07
share|improvethisquestion
ojblass burnt1ce
8,212135099 3,439115799
closedasnotarealquestionbyWillNov26'12at0:13
It'sdifficulttotellwhatisbeingaskedhere.Thisquestionisambiguous,vague,incomplete,overlybroad,orrhetoricalandcannotbereasonablyansweredinitscurrent
form.Forhelpclarifyingthisquestionsothatitcanbereopened,visitthehelpcenter.Ifthisquestioncanberewordedtofittherulesinthehelpcenter,pleaseeditthe
question.
23 Didyouleapupandexclaim"whatdoesthishavetodowithbooks?"andstormout?JPAliotoApr19'09at6:39
Igotaskedthatbyaguywhowentontoanothersituation.WhenIusedanearlytextbookGangofFourpatternappropriately,hesaid"Atleast
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 282/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
youknowpolymorphism."Iwasthenthankedforcoming,andtoldthey'dletmeknow.Iwasn'timpressed.DavidThornleyMay7'09at17:18
Isn'tthismemorymanagementproblem?SanjeevKumarDangiNov5'13at8:20
Whenaskedthisquestion,didyouactuallyhavetowriteouttheclassesandfunctionsonCollabEditordidyoujusthavetotalkaboutthem?
committedandroiderMar26at23:27
addacomment|
5Answers
activeoldestvotes
Hereisaquickstarttogetthegearsturning...
ParkingLotisaclass.
ParkingSpaceisaclass.
ParkingSpacehasanEntrance.
Entrancehasalocationormorespecifically,distancefromEntrance.
ParkingLotSignisaclass.
ParkingLothasaParkingLotSign.
ParkingLothasafinitenumberofParkingSpaces.
HandicappedParkingSpaceisasubclassofParkingSpace.
RegularParkingSpaceisasubclassofParkingSpace.
CompactParkingSpaceisasubclassofParkingSpace.
ParkingLotkeepsarrayofParkingSpaces,andaseparatearrayofvacantParkingSpacesinorderofdistancefromitsEntrance.
upvote67 ParkingLotSigncanbetoldtodisplay"full",or"empty",or"blank/normal/partiallyoccupied"bycalling.Full(),.Empty()or.Normal()
downvote
accepted Parkerisaclass.
ParkercanPark().
ParkercanUnpark().
ValetisasubclassofParkerthatcancallParkingLot.FindVacantSpaceNearestEntrance(),whichreturnsaParkingSpace.
ParkerhasaParkingSpace.
ParkercancallParkingSpace.Take()andParkingSpace.Vacate().
ParkercallsEntrance.Entering()andEntrance.Exiting()andParkingSpacenotifiesParkingLotwhenitistakenorvacatedsothatParkingLotcan
determineifitisfullornot.Ifitisnewlyfullornewlyemptyornewlynotfullorempty,itshouldchangetheParkingLotSign.Full()or
ParkingLotSign.Empty()orParkingLotSign.Normal().
HandicappedParkercouldbeasubclassofParkerandCompactParkerasubclassofParkerandRegularParkerasubclassofParker.(mightbeoverkill,
actually.)
Inthissolution,itispossiblethatParkershouldberenamedtobeCar.
answeredApr19'09at6:22
editedApr19'09at6:28
share|improvethisanswer
ChrisMorley
1,24611318
8 Pleasedon'tforgetcar.ojblassApr19'09at6:31
WhydoesParkingSpacehavetobeaclass?Idon'tseeanyneedtocreateanobjectforit?Atalltimes,anyparkingspacehastobeeithera
Handicapped,RegularorCompact.ParkingSpaceshouldbeaninterfacerather.name_maskedDec11'10at18:22
4 Probablywecanaddfloorstoparkinglot..BarryNov5'11at14:06
@Chris,objlass:CanyoupleaserepresentitinUMLmodel.Itwillgivemoreclarity?cexplorerAug8'12at16:47
2 WhydoesParkingLotSignclassexist?Wouldn'tanattribute(say,boolisFull)work?ChinmayNerurkarSep12'12at16:11
|show1morecomment
publicclassParkingLot
{
Vector<ParkingSpace>vacantParkingSpaces=null;
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 283/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Vector<ParkingSpace>fullParkingSpaces=null;
intparkingSpaceCount=0;
booleanisFull;
booleanisEmpty;
ParkingSpacefindNearestVacant(ParkingTypetype)
{
Iterator<ParkingSpace>itr=vacantParkingSpaces.iterator();
while(itr.hasNext())
{
ParkingSpaceparkingSpace=itr.next();
if(parkingSpace.parkingType==type)
{
returnparkingSpace;
}
}
returnnull;
}
voidparkVehicle(ParkingTypetype,Vehiclevehicle)
{
if(!isFull())
{
ParkingSpaceparkingSpace=findNearestVacant(type);
if(parkingSpace!=null)
{
parkingSpace.vehicle=vehicle;
parkingSpace.isVacant=false;
vacantParkingSpaces.remove(parkingSpace);
fullParkingSpaces.add(parkingSpace);
if(fullParkingSpaces.size()==parkingSpaceCount)
isFull=true;
isEmpty=false;
}
}
}
voidreleaseVehicle(Vehiclevehicle)
{
if(!isEmpty())
{
Iterator<ParkingSpace>itr=fullParkingSpaces.iterator();
while(itr.hasNext())
{
upvote15downvote ParkingSpaceparkingSpace=itr.next();
if(parkingSpace.vehicle.equals(vehicle))
{
fullParkingSpaces.remove(parkingSpace);
vacantParkingSpaces.add(parkingSpace);
parkingSpace.isVacant=true;
parkingSpace.vehicle=null;
if(vacantParkingSpaces.size()==parkingSpaceCount)
isEmpty=true;
isFull=false;
}
}
}
}
booleanisFull()
{
returnisFull;
}
booleanisEmpty()
{
returnisEmpty;
}
}
publicclassParkingSpace
{
booleanisVacant;
Vehiclevehicle;
ParkingTypeparkingType;
intdistance;
}
publicclassVehicle
{
intnum;
}
publicenumParkingType
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 284/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
{
REGULAR,
HANDICAPPED,
COMPACT,
MAX_PARKING_TYPE,
}
answeredDec25'11at7:47
share|improvethisanswer
SrikantAggarwal
15113
UseHashMapinsteadoflistswithvehiclenumberaskeyforefficiencyuser3716835Nov20'14at2:20
addacomment|
Modelsdon'texistinisolation.Thestructuresyou'ddefineforasimulationofcarsenteringacarpark,anembeddedsystemwhichguidesyoutoafree
space,acarparkingbillingsystemorfortheautomatedgates/ticketmachinesusualincarparksarealldifferent.
upvote6 answeredMay7'09at16:46
downvote
share|improvethisanswer
PeteKirkham
35.2k257117
addacomment|
InanObjectOrientedparkinglot,therewillbenoneedforattendantsbecausethecarswill"knowhowtopark".
Findingausablecaronthelotwillbedifficultthemostcommonmodelswilleitherhavealltheirmovingpartsexposedaspublicmembervariables,or
theywillbe"fullyencapsulated"carswithnowindowsordoors.
TheparkingspacesinourOOparkinglotwillnotmatchthesizeandshapeofthecars(an"impediancemismatch"betweenthespacesandthecars)
upvote2
downvote Licensetagsonourlotwillhaveadotbetweeneachletteranddigit.Handicapedparkingwillonlybeavailableforlicensesbeginningwith"_",and
licensesbeginningwith"m_"willbetowed.
answeredApr19'09at6:31
share|improvethisanswer
PaulKeister
7,79112450
addacomment|
youwouldneedaparkinglot,thatholdsamultidimensionalarray(specifiedintheconstructor)ofatype"space".Theparkinglotcankeeptrackofhowmany
spacesaretakenviacallstofunctionsthatfillandemptyspaces.Spacecanholdanenumeratedtypethattellswhatkindofspaceitis.Spacealsohasamethod
taken().forthevaletparking,justfindthefirstspacethatsopenandputthecarthere.YouwillalsoneedaCarobjecttoputinthespace,thatholdswhetheritisa
handicapped,compact,orregularvehicle.
classParkingLot
{
Space[][]spaces;
ParkingLot(wide,long);//constructor
FindOpenSpace(TypeOfCar);//findfirstopenspacewheretypematches
}
up enumTypeOfSpace={compact,handicapped,regular};
enumTypeOfCar={compact,handicapped,regular};
vote
2 classSpace
down {
vote TypeOfSpacetype;
boolempty;
//getsandsetshere
//makesurecartype
}
classcar
{
TypeOfCartype;
}
answeredApr19'09at6:32
share|improvethisanswer
ScottM.
5,2651631
addacomment|
protectedbySrikarAppalJul27'13at5:51
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 285/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Thankyouforyourinterestinthisquestion.Becauseithasattractedlowqualityanswers,postingananswernowrequires10reputationonthissite.
Wouldyouliketoansweroneoftheseunansweredquestionsinstead?
Nottheansweryou'relookingfor?Browseotherquestionstaggedooporaskyourownquestion.
asked 6yearsago
viewed 81035times
active 2yearsago
Lookingforajob?
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Linked
1
JavaOOPSParkingLotexampleDesign
Related
4
DatabaseGuyAsks:ObjectOrientedDesignTheory?
608
DoesFunctionalProgrammingReplaceGoFDesignPatterns?
673
ExamplesofGoFDesignPatternsinJava'scorelibraries
3
ObjectOrientedDesignQuestions
0
OOresourcespendinganddesignconfusion?
0
ParkingLot,OOPDesignCustomDesign
10
OOdesignofBooksandTags
1
Whatisabetterdesigniftwosubclasseshavethesamemethod?
5
DesignInterviewCarReservationSystem
0
ObjectOrientedDesignofaparkinglot
HotNetworkQuestions
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
HowcouldaresurrectedJesusproveheisJesus?
HowdoIupgradefromGPLv2toGPLv3?
PythonLabelExpression?ArcGIS10.3.1
NineTallMenAreStandingTall
Packagetodonotes:HowcanIchangethetextcolor?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
Drawinganarrayofnodesusingtheforeachconstruct
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 286/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Doblockingcreatureshealbacktofullbetweenphases?
Whatistheoriginofthisphotoofanunexplodedbomb?
Antiferromagneticordering
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Functionsthataretheirowninversion.
Justifyingsuboptimalresearchqualitybylackofsupervision
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Clientwantsfontaslogo
Shouldmy(sequential)collectionstartatindex0orindex1?
Nicelytypesettingverbatimtext
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
DoesCIDRreally"doaway"withIPaddressclasses?
Needhelprecreatingcrazycolors/materialfromexample
Using"using"twiceinterpreteddifferentlybydifferentcompilers
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
ExpressionEvaluationandTreeWalkingusingpolymorphism?(alaSteve
Yegge)
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 287/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Thismorning,IwasreadingSteveYegge's:WhenPolymorphismFails,whenIcameacrossaquestionthatacoworkerofhisusedtoaskpotentialemployees
whentheycamefortheirinterviewatAmazon.
Asanexampleofpolymorphisminaction,let'slookattheclassic"eval"interviewquestion,which(asfarasIknow)wasbroughttoAmazonby
RonBraunstein.Thequestionisquitearichone,asitmanagestoprobeawidevarietyofimportantskills:OOPdesign,recursion,binarytrees,
polymorphismandruntimetyping,generalcodingskills,and(ifyouwanttomakeitextrahard)parsingtheory.
Atsomepoint,thecandidatehopefullyrealizesthatyoucanrepresentanarithmeticexpressionasabinarytree,assumingyou'reonlyusingbinary
operatorssuchas"+","","*","/".Theleafnodesareallnumbers,andtheinternalnodesarealloperators.Evaluatingtheexpressionmeans
walkingthetree.Ifthecandidatedoesn'trealizethis,youcangentlyleadthemtoit,orifnecessary,justtellthem.
Evenifyoutellthem,it'sstillaninterestingproblem.
Thefirsthalfofthequestion,whichsomepeople(whosenamesIwillprotecttomydyingbreath,buttheirinitialsareWillieLewis)feelisaJob
RequirementIfYouWantToCallYourselfADeveloperAndWorkAtAmazon,isactuallykindahard.Thequestionis:howdoyougofroman
arithmeticexpression(e.g.inastring)suchas"2+(2)"toanexpressiontree.WemayhaveanADJchallengeonthisquestionatsomepoint.
upvote Thesecondhalfis:let'ssaythisisa2personproject,andyourpartner,whowe'llcall"Willie",isresponsiblefortransformingthestring
21down expressionintoatree.Yougettheeasypart:youneedtodecidewhatclassesWillieistoconstructthetreewith.Youcandoitinanylanguage,
vote butmakesureyoupickone,orWilliewillhandyouassemblylanguage.Ifhe'sfeelingornery,itwillbeforaprocessorthatisnolonger
favorite manufacturedinproduction.
17
You'dbeamazedathowmanycandidatesboffthisone.
Iwon'tgiveawaytheanswer,butaStandardBadSolutioninvolvestheuseofaswitchorcasestatment(orjustgoodoldfashionedcascadedifs).
ASlightlyBetterSolutioninvolvesusingatableoffunctionpointers,andtheProbablyBestSolutioninvolvesusingpolymorphism.Iencourage
youtoworkthroughitsometime.Funstuff!
So,let'strytotackletheproblemallthreeways.Howdoyougofromanarithmeticexpression(e.g.inastring)suchas"2+(2)"toanexpressiontreeusing
cascadedif's,atableoffunctionpointers,and/orpolymorphism?
Feelfreetotackleone,two,orallthree.
[update:titlemodifiedtobettermatchwhatmostoftheanswershavebeen.]
ooprecursionpolymorphismbinarytree
communitywiki
editedAug31'08at20:18
share|improvethisquestion
14revs,3users51%
MarkHarrison
BasedonMarkHarrisson'sanswer,IhavewrittenaphpimplementationserdarsenayNov4'13at0:14
addacomment|
16Answers
activeoldestvotes
PolymorphicTreeWalking,Pythonversion
#!/usr/bin/python
classNode:
"""baseclass,youshouldnotprocessoneofthese"""
defprocess(self):
raise('youshouldnotbeprocessinganode')
classBinaryNode(Node):
"""baseclassforbinarynodes"""
def__init__(self,_left,_right):
self.left=_left
self.right=_right
defprocess(self):
raise('youshouldnotbeprocessingabinarynode')
classPlus(BinaryNode):
defprocess(self):
returnself.left.process()+self.right.process()
classMinus(BinaryNode):
defprocess(self):
returnself.left.process()self.right.process()
classMul(BinaryNode):
defprocess(self):
returnself.left.process()*self.right.process()
classDiv(BinaryNode):
defprocess(self):
returnself.left.process()/self.right.process()
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 288/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
classNum(Node):
def__init__(self,_value):
self.value=_value
upvote9 defprocess(self):
downvote returnself.value
accepted
defdemo(n):
printn.process()
demo(Num(2))#2
demo(Plus(Num(2),Num(5)))#2+3
demo(Plus(Mul(Num(2),Num(3)),Div(Num(10),Num(5))))#(2*3)+(10/2)
Thetestsarejustbuildingupthebinarytreesbyusingconstructors.
programstructure:
abstractbaseclass:Node
allNodesinheritfromthisclass
abstractbaseclass:BinaryNode
allbinaryoperatorsinheritfromthisclass
processmethoddoestheworkofevalutingtheexpressionandreturningtheresult
binaryoperatorclasses:Plus,Minus,Mul,Div
twochildnodes,oneeachforleftsideandrightsidesubexpressions
numberclass:Num
holdsaleafnodenumericvalue,e.g.17or42
answeredAug15'08at22:56
editedSep2'08at15:34
share|improvethisanswer
MarkHarrison
96.8k78205308
Thisanswerishorriblyoverengineered.Thequestionwasfor2+(2),notanarbitraryarithmeticcalculation.Also,thisjustexecutesthetree,it
doesn'tbuildit.ReaperUnrealOct31'08at22:44
ThequestionwasforanarithmeticcalculationSUCHAS2+(2),notthecalculationof2+(2).Therefore,it'snotoverengineered,butanswersthe
11
questionasintended.ThomasOwensNov10'08at12:53
Thisanswerisnottothequestionof"Howdoyougofromanarithmeticexpression(e.g.inaSTRING)suchas"2+(2)"....Wheredoes
1 "demo(Plus(Mul(Num(2),Num(3)),Div(Num(10),Num(5))))"comefrom?Thatotherprogramwedon'tgettosee?Whyisthismarkedasbest
answer?GugeNov20'08at2:09
1 "Yougettheeasypart:youneedtodecidewhatclassesWillieistoconstructthetreewith."vanja.Aug11'09at7:31
addacomment|
Thisgetsintoparsing/compilertheory,whichiskindofarabbithole...TheDragonBookisthestandardtextforcompilerconstruction,andtakesthisto
extremes.Inthisparticularcase,youwanttoconstructacontextfreegrammarforbasicarithmetic,thenusethatgrammartoparseoutanabstractsyntaxtree.
Youcantheniterateoverthetree,reducingitfromthebottomup(it'satthispointyou'dapplythepolymorphism/functionpointers/switchstatementtoreducethe
tree).
up
vote4 I'vefoundthesenotestobeincrediblyhelpfulincompilerandparsingtheory.
down
vote answeredAug15'08at21:58
share|improvethisanswer
eplawless
2,23462134
Here'saminimalCFGfortheoriginalquestion:S>NN>2N>NON>(N)O>NReaperUnrealOct31'08at21:04
addacomment|
RepresentingtheNodes
Ifwewanttoincludeparentheses,weneed5kindsofnodes:
thebinarynodes:AddMinusMulDiv
thesehavetwochildren,aleftandrightside
+
/\
nodenode
anodetoholdavalue:Val
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 289/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
nochildrennodes,justanumericvalue
anodetokeeptrackoftheparens:Paren
asinglechildnodeforthesubexpression
()
|
upvote4downvote node
Forapolymorphicsolution,weneedtohavethiskindofclassrelationship:
Node
BinaryNode:inheritfromNode
Plus:inheritfromBinaryNode
Minus:inheritfromBinaryNode
Mul:inheritfromBinaryNode
Div:inheritfromBinaryNode
Value:inheritfromNode
Paren:inheritfromnode
Thereisavirtualfunctionforallnodescalledeval().Ifyoucallthatfunction,itwillreturnthevalueofthatsubexpression.
answeredAug15'08at23:38
share|improvethisanswer
MarkHarrison
96.8k78205308
2 Thereisnoreasontoincludeparenthesesintheabstractsyntaxtree.JonasKongslundNov21'08at1:45
addacomment|
Theproblem,Ithink,isthatweneedtoparseperentheses,andyettheyarenotabinaryoperator?Shouldwetake(2)asasingletoken,
thatevaluatesto2?
Theparensdon'tneedtoshowupintheexpressiontree,buttheydoaffectitsshape.E.g.,thetreefor(1+2)+3isdifferentfrom1+(2+3):
+
/\
+3
/\
12
versus
upvote3down
vote +
/\
1+
/\
23
Theparenthesesarea"hint"totheparser(e.g.,persuperjoe30,to"recursivelydescend")
answeredAug15'08at20:04
share|improvethisanswer
ChrisConway
28.3k2392135
addacomment|
StringTokenizer+LL(1)Parserwillgiveyouanexpressiontree...thepolymorphismwaymightinvolveanabstractArithmeticclasswithan"evaluate(a,b)"
function,whichisoverriddenforeachoftheoperatorsinvolved(Addition,Subtractionetc)toreturntheappropriatevalue,andthetreecontainsIntegersand
Arithmeticoperators,whichcanbeevaluatedbyapost(?)ordertraversalofthetree.
upvote
2down answeredAug15'08at17:50
vote
share|improvethisanswer
eplawless
2,23462134
addacomment|
Hm...Idon'tthinkyoucanwriteatopdownparserforthiswithoutbacktracking,soithastobesomesortofashiftreduceparser.LR(1)orevenLALR
willofcourseworkjustfinewiththefollowing(adhoc)languagedefinition:
Start>E1
E1>E1+E1|E1E1
E1>E2*E2|E2/E2|E2
E2>number|(E1)
SeparatingitoutintoE1andE2isnecessarytomaintaintheprecedenceof*and/over+and.
ButthisishowIwoulddoitifIhadtowritetheparserbyhand:
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 290/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Twostacks,onestoringnodesofthetreeasoperandsandonestoringoperators
Readtheinputlefttoright,makeleafnodesofthenumbersandpushthemintotheoperandstack.
upvote2 Ifyouhave>=2operandsonthestack,pop2,combinethemwiththetopmostoperatorintheoperatorstackandpushthisstructurebacktothe
downvote operandtree,unless
Thenextoperatorhashigherprecedencethattheonecurrentlyontopofthestack.
Thisleavesustheproblemofhandlingbrackets.Oneelegant(Ithought)solutionistostoretheprecedenceofeachoperatorasanumberinavariable.So
initially,
intplus,minus=1
intmul,div=2
Noweverytimeyouseeaaleftbracketincrementallthesevariablesby2,andeverytimeyouseearightbracket,decrementallthevariablesby2.
Thiswillensurethatthe+in3*(4+5)hashigherprecedencethanthe*,and3*4willnotbepushedontothestack.Insteaditwillwaitfor5,push4+5,then
push3*(4+5).
communitywiki
answeredNov10'08at12:49
share|improvethisanswer
anukool_j
addacomment|
Re:Justin
Ithinkthetreewouldlooksomethinglikethis:
+
/\
2()
|
2
Basically,you'dhavean"eval"node,thatjustevaluatesthetreebelowit.Thatwouldthenbeoptimizedouttojustbeing:
upvote1downvote
+
/\
22
Inthiscasetheparensaren'trequiredanddon'taddanything.Theydon'taddanythinglogically,sothey'djustgoaway.
answeredAug15'08at20:14
share|improvethisanswer
Herms
14.9k85588
addacomment|
Iwon'tgiveawaytheanswer,butaStandardBadSolutioninvolvestheuseofaswitchorcasestatment(orjustgoodoldfashionedcascadedifs).A
SlightlyBetterSolutioninvolvesusingatableoffunctionpointers,andtheProbablyBestSolutioninvolvesusingpolymorphism.
Thelasttwentyyearsofevolutionininterpreterscanbeseenasgoingtheotherwaypolymorphism(egnaiveSmalltalkmetacircularinterpreters)tofunction
pointers(naivelispimplementations,threadedcode,C++)toswitch(naivebytecodeinterpreters),andthenonwardstoJITsandsoonwhicheitherrequirevery
bigclasses,or(insinglypolymorphiclanguages)doubledispatch,whichreducesthepolymorphismtoatypecase,andyou'rebackatstageone.Whatdefinition
up of'best'isinusehere?
vote1
down ForsimplestuffapolymorphicsolutionisOKhere'soneImadeearlier,buteitherstackandbytecode/switchorexploitingtheruntime'scompilerisusually
vote betterifyou're,say,plottingafunctionwithafewthousanddatapoints.
answeredAug17'08at13:59
editedAug20'08at18:09
share|improvethisanswer
PeteKirkham
35.2k257117
addacomment|
Ithinkthequestionisabouthowtowriteaparser,nottheevaluator.Orrather,howtocreatetheexpressiontreefromastring.
Casestatementsthatreturnabaseclassdon'texactlycount.
Thebasicstructureofa"polymorphic"solution(whichisanotherwayofsaying,Idon'tcarewhatyoubuildthiswith,Ijustwanttoextenditwithrewriting
theleastamountofcodepossible)isdeserializinganobjecthierarchyfromastreamwitha(dynamic)setofknowntypes.
upvote1
downvote Thecruxoftheimplementationofthepolymorphicsolutionistohaveawaytocreateanexpressionobjectfromapatternmatcher,likelyrecursive.I.e.,map
aBNForsimilarsyntaxtoanobjectfactory.
editedJul3'12at14:51 answeredAug21'08at16:52
share|improvethisanswer
TimCooper MatNoguchi
66.5k18127154 88756
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 291/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
addacomment|
Ormaybethisistherealquestion:howcanyourepresent(2)asaBST?Thatisthepartthatistrippingmeup.
Recursion.
upvote0downvote answeredAug15'08at19:50
share|improvethisanswer
andrewrk
8,014175580
addacomment|
@Justin:
Lookatmynoteonrepresentingthenodes.Ifyouusethatscheme,then
2+(2)
canberepresentedas
.
upvote0downvote /\
2()
|
2
answeredAug15'08at23:12
editedAug15'08at23:40
share|improvethisanswer
MarkHarrison
96.8k78205308
addacomment|
shoulduseafunctionallanguageimo.TreesarehardertorepresentandmanipulateinOOlanguages.
answeredAug15'08at19:28
upvote0downvote
editedAug24'08at21:35
share|improvethisanswer
BrianLeahy
9,58363558
addacomment|
Aspeoplehavebeenmentioningpreviously,whenyouuseexpressiontreesparensarenotnecessary.Theorderofoperationsbecomestrivialandobviouswhen
you'relookingatanexpressiontree.Theparensarehintstotheparser.
Whiletheacceptedansweristhesolutiontoonehalfoftheproblem,theotherhalfactuallyparsingtheexpressionisstillunsolved.Typically,thesesortsof
problemscanbesolvedusingarecursivedescentparser.Writingsuchaparserisoftenafunexercise,butmostmoderntoolsforlanguageparsingwillabstract
thatawayforyou.
upvote
0down Theparserisalsosignificantlyharderifyouallowfloatingpointnumbersinyourstring.IhadtocreateaDFAtoacceptfloatingpointnumbersinCitwasa
vote verypainstakinganddetailedtask.Remember,validfloatingpointsinclude:10,10.,10.123,9.876e5,1.0f,.025,etc.Iassumesomedispensationfromthis(in
favorofsimplictyandbrevity)wasmadeintheinterview.
answeredAug25'08at15:21
share|improvethisanswer
FreeMemory
5,30932135
addacomment|
I'vewrittensuchaparserwithsomebasictechniqueslikeInfix>RPNandShuntingYardandTreeTraversals.HereistheimplementationI'vecameup
with.
It'swritteninC++andcompilesonbothLinuxandWindows.
Anysuggestions/questionsarewelcomed.
So,let'strytotackletheproblemallthreeways.Howdoyougofromanarithmeticexpression(e.g.inastring)suchas"2+(2)"toan
upvote0 expressiontreeusingcascadedif's,atableoffunctionpointers,and/orpolymorphism?
downvote
Thisisinteresting,butIdon'tthinkthisbelongstotherealmofobjectorientedprogramming...Ithinkithasmoretodowithparsingtechniques.
communitywiki
editedNov21'08at1:35
share|improvethisanswer
2revs
xxxxxxx
addacomment|
I'vekindofchuckedthisc#consoleapptogetherasabitofaproofofconcept.Haveafeelingitcouldbealotbetter(thatswitchstatementinGetNodeiskindof
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 292/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
clunky(it'stherecozIhitablanktryingtomapaclassnametoanoperator)).Anysuggestionsonhowitcouldbeimprovedverywelcome.
usingSystem;
classProgram
{
staticvoidMain(string[]args)
{
stringexpression="(((3.5*4.5)/(1+2))+5)";
Console.WriteLine(string.Format("{0}={1}",expression,newExpression.ExpressionTree(expression).Value));
Console.WriteLine("\nShow'soverfolks,pressakeytoexit");
Console.ReadKey(false);
}
}
namespaceExpression
{
//
abstractclassNodeBase
{
publicabstractdoubleValue{get;}
}
//
classValueNode:NodeBase
{
publicValueNode(doublevalue)
{
_double=value;
}
privatedouble_double;
publicoverridedoubleValue
{
get
{
return_double;
}
}
}
//
abstractclassExpressionNodeBase:NodeBase
{
protectedNodeBaseGetNode(stringexpression)
{
//Removeparenthesis
expression=RemoveParenthesis(expression);
//Isexpressionjustanumber?
doublevalue=0;
if(double.TryParse(expression,outvalue))
{
returnnewValueNode(value);
}
else
{
intpos=ParseExpression(expression);
if(pos>0)
{
stringleftExpression=expression.Substring(0,pos1).Trim();
stringrightExpression=expression.Substring(pos).Trim();
switch(expression.Substring(pos1,1))
{
case"+":
returnnewAdd(leftExpression,rightExpression);
case"":
returnnewSubtract(leftExpression,rightExpression);
case"*":
returnnewMultiply(leftExpression,rightExpression);
case"/":
returnnewDivide(leftExpression,rightExpression);
default:
thrownewException("Unknownoperator");
}
}
else
{
thrownewException("Unabletoparseexpression");
}
}
}
privatestringRemoveParenthesis(stringexpression)
{
if(expression.Contains("("))
{
expression=expression.Trim();
intlevel=0;
intpos=0;
foreach(chartokeninexpression.ToCharArray())
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 293/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
{
pos++;
switch(token)
{
case'(':
level++;
break;
case')':
level;
break;
}
if(level==0)
{
break;
}
}
if(level==0&&pos==expression.Length)
{
expression=expression.Substring(1,expression.Length2);
expression=RemoveParenthesis(expression);
}
}
returnexpression;
}
privateintParseExpression(stringexpression)
{
intwinningLevel=0;
bytewinningTokenWeight=0;
intwinningPos=0;
intlevel=0;
intpos=0;
foreach(chartokeninexpression.ToCharArray())
{
pos++;
switch(token)
{
case'(':
level++;
up break;
case')':
vote level;
0 break;
down }
vote
if(level<=winningLevel)
{
if(OperatorWeight(token)>winningTokenWeight)
{
winningLevel=level;
winningTokenWeight=OperatorWeight(token);
winningPos=pos;
}
}
}
returnwinningPos;
}
privatebyteOperatorWeight(charvalue)
{
switch(value)
{
case'+':
case'':
return3;
case'*':
return2;
case'/':
return1;
default:
return0;
}
}
}
//
classExpressionTree:ExpressionNodeBase
{
protectedNodeBase_rootNode;
publicExpressionTree(stringexpression)
{
_rootNode=GetNode(expression);
}
publicoverridedoubleValue
{
get
{
return_rootNode.Value;
}
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 294/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
}
}
//
abstractclassOperatorNodeBase:ExpressionNodeBase
{
protectedNodeBase_leftNode;
protectedNodeBase_rightNode;
publicOperatorNodeBase(stringleftExpression,stringrightExpression)
{
_leftNode=GetNode(leftExpression);
_rightNode=GetNode(rightExpression);
}
}
//
classAdd:OperatorNodeBase
{
publicAdd(stringleftExpression,stringrightExpression)
:base(leftExpression,rightExpression)
{
}
publicoverridedoubleValue
{
get
{
return_leftNode.Value+_rightNode.Value;
}
}
}
//
classSubtract:OperatorNodeBase
{
publicSubtract(stringleftExpression,stringrightExpression)
:base(leftExpression,rightExpression)
{
}
publicoverridedoubleValue
{
get
{
return_leftNode.Value_rightNode.Value;
}
}
}
//
classDivide:OperatorNodeBase
{
publicDivide(stringleftExpression,stringrightExpression)
:base(leftExpression,rightExpression)
{
}
publicoverridedoubleValue
{
get
{
return_leftNode.Value/_rightNode.Value;
}
}
}
//
classMultiply:OperatorNodeBase
{
publicMultiply(stringleftExpression,stringrightExpression)
:base(leftExpression,rightExpression)
{
}
publicoverridedoubleValue
{
get
{
return_leftNode.Value*_rightNode.Value;
}
}
}
}
answeredJan23'09at22:00
share|improvethisanswer
WilfredKnievel
1,63611426
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 295/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Nicetoseeafullimplementation,butIambitconfusedwhyyoucombinedtheparsinglogicwiththeexpressiontreerepresentation,creatingatightcoupling
oftheparsinglogicwithexpressiontree.Also,youcouldgenerateamap(drivenbyxml,adatabase,anincodedictionary,oracustomattributeappliedto
eachclassrepresentinganode)betweenyourtokensandtheclasstheymapto.Theproblemhereistheuseofreflection(viaActivatororsomeother
technique)togenerateyourclasses.MerrittAug15'10at19:06
@Merrittmmmgoodpoint,mighthaveanothercrackatthisnexttimeIhaveafreelunchtime.Thanksforthesuggestions.WilfredKnievelOct20'10at
8:44
addacomment|
Ok,hereismynaiveimplementation.Sorry,Ididnotfeeltouseobjectsforthatonebutitiseasytoconvert.IfeelabitlikeevilWilly(fromSteve's
story).
#!/usr/bin/envpython
#treestructure[leftargument,operator,rightargument,prioritylevel]
tree_root=[None,None,None,None]
#countofparethesisnesting
parenthesis_level=0
#currentnodewithemptyrightargument
current_node=tree_root
#indicesintree_rootnodesLeft,Operator,Right,PRiority
L,O,R,PR=0,1,2,3
#functionsthatrealiseoperators
defsum(a,b):
returna+b
defdiff(a,b):
returnab
defmul(a,b):
returna*b
defdiv(a,b):
returna/b
#treeevaluator
defprocess_node(n):
try:
len(n)
exceptTypeError:
returnn
left=process_node(n[L])
right=process_node(n[R])
returnn[O](left,right)
#mappingoperatorstorelevantfunctions
o2f={'+':sum,'':diff,'*':mul,'/':div,'(':None,')':None}
#convertstokentoanodeintree
defconvert_token(t):
globalcurrent_node,tree_root,parenthesis_level
ift=='(':
parenthesis_level+=2
return
ift==')':
parenthesis_level=2
return
try:#assumptionthatwehavejustaninteger
l=int(t)
except(ValueError,TypeError):
pass#ifnot,noproblem
else:
iftree_root[L]isNone:#ifitisfirstnumber,putitontheleftofrootnode
tree_root[L]=l
else:#putontherightofcurrent_node
upvote0down current_node[R]=l
vote return
priority=(1iftin'+'else2)+parenthesis_level
#iftree_rootdoesnothaveoperatorputitthere
iftree_root[O]isNoneandtino2f:
tree_root[O]=o2f[t]
tree_root[PR]=priority
return
#ifnewnodehaslessorequalspriority,putitonthetopoftree
iftree_root[PR]>=priority:
temp=[tree_root,o2f[t],None,priority]
tree_root=current_node=temp
return
#startingfromrootsearchforaplacewithhigherpriorityinhierarchy
current_node=tree_root
whiletype(current_node[R])!=type(1)andpriority>current_node[R][PR]:
current_node=current_node[R]
#insertnewnode
temp=[current_node[R],o2f[t],None,priority]
current_node[R]=temp
current_node=temp
defparse(e):
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 296/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
token=''
forcine:
ifc<='9'andc>='0':
token+=c
continue
ifc=='':
iftoken!='':
convert_token(token)
token=''
continue
ifcino2f:
iftoken!='':
convert_token(token)
convert_token(c)
token=''
continue
print"Unrecognizedcharacter:",c
iftoken!='':
convert_token(token)
defmain():
parse('(((3*4)/(1+2))+5)')
printtree_root
printprocess_node(tree_root)
if__name__=='__main__':
main()
communitywiki
answeredOct25'13at20:39
share|improvethisanswer
mmierzwa
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 297/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedooprecursionpolymorphismbinary
treeoraskyourownquestion.
asked 6yearsago
viewed 4374times
active 1yearago
Lookingforajob?
DevOpsEngineerContinuousIntegration
DigitalAssess
Thiruvananthapuram,India
continuousintegrationjenkins
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
152PeopleChatting
JavaScript
6hoursagoCapricaSix
afonsomatos:
ivarni:
rlemon:
Awal
Caprica
Sterling
ssube:
6 6 6 Garg: Six:Archer:
6
PHP
6hoursagordlowrey
Fabor:
bwoebi:
Enerdlowrey:
ircmaxell:
Jimbo:
Ronald
6 6 Mihai: 6 6 6 Ulysses
Related
3
DataschemaandqueryforpolymorphictreeinSQLServer
0
Doubtonusingpolymorphismincodinganexpressionparsetree/evaluator
0
Walkfoldertree,bottomup
0
polymorphicbinarysearchtree
0
ComputingthevalueofaBinaryExpressionTree
0
CreatingaBinaryExpressionTreeinjava
2
ExpressionTreeEvaluatingError
0
polymorphictreenumberofleavesjava
7
Mathematicalexpressionsbinarytree
0
RecursiveTreeWalkwithES6Promise
HotNetworkQuestions
HowtodealwithaGMwhodoesnottelluseverything?
Wordfor"animals,includinghumans"?
HowcouldaresurrectedJesusproveheisJesus?
Derivativeofadefiniteintegralissue
Passfilenamefrombashtopython
Whydotheymanifestasrings?
ThenthTernary
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 298/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
HowcanIcheckifmyfunctionprint/echo'ssomething?
Isthereawordforpeopleincapableofthinking?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Alarmclockprinting
DoesCIDRreally"doaway"withIPaddressclasses?
Doblockingcreatureshealbacktofullbetweenphases?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
PythonLabelExpression?ArcGIS10.3.1
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
40Numbersin9Bytes
ALN*NTicTacToeGame
Howtodrawsequenceofshapeswitharrowsandtext
WhatdoesitmeanifanACmotorhastwovoltageratings?
RollmyD&Dcharacter'sabilityscores
zero,zerosorzeroes?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
howtoanswerHLDandLLD
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 299/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
IhaverecentlyattendedAmazonInterviewandgotrejectedafterdesignround,itshappenedthreetimeswithAmazonin2year,ialwaysgettingrejected
becauseofdesignround.pleasehelpmetoknowhowshouldianswerandesignquestion.questionslike1)designelevatorcontrolsystem2)designwhisper
syncfeature(usedinAmazoninstantvideoplatform)theyaskmetodesignEndtoendHLDLLDididnotgetwhatexactlydifferinboth,iexplainasa
algorithmwise,butcouldnotproperlybyHLDandLLD.
imeanisearchedalot,butcouldnotfoundawaytoanswersuchquestion.
upvote
0down Anyhelpwillbegoodforme.
vote
favorite Thanks,
oopdesignamazon
askedFeb10'14at6:48
share|improvethisquestion
user2139898
4517
addacomment|
1Answer
activeoldestvotes
HLD:HighLevelDesignconsistofsubsystemdesigntodefine.Ittargetarchitect,Technicalleadsetc.SolutionTechnicalOverviewinterfaces
primaryclassesDatabaseentitieswithAssumptions
LLD:Lowerleveldesignconsistofindividualmodule/sectiondesignforthesubsystem.ItprimarilyextensionofHLD.Ittargetscoredevelopers&
coversfollowingitems:Allclassesentities&interfacesDBModel(Tables,columnattributes,indexes,constraints)Algorithmsformethodsusedin
upvote1 classesLoggingimplementation
downvote
accepted Ihopeithelps!!
answeredFeb10'14at12:46
share|improvethisanswer
Virgo_The_Perfectionist
88116
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 300/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedoopdesignamazonoraskyourown
question.
asked 1yearago
viewed 151times
active 1yearago
Lookingforajob?
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 301/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Related
64
Howdoyouplananapplication'sarchitecturebeforewritinganycode?
61
Howtocompareobjectsbymultiplefields
1
Howtoenforceahasarelationshipandprotecttheobjectthatishad
21
HowdoIexplainloosecouplingandinformationhidingtoanewprogrammer?
122
Howdoyoudesignobjectorientedprojects?
4
HowtosetIDinObjectOrientedCode
10
Howdoyoukeepyourselfandyourcoworkersfromcreatinghugeclasses
1551
HowtodecidewhentouseNode.js?
0
Howwouldyoudesignthismultipleselectionsystem
2
HowcanIdesignthisconceptinaobjectorientedmanner?
HotNetworkQuestions
Whydosocksstink?
OptimalRopeBurning
HowcanIcheckifmyfunctionprint/echo'ssomething?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Whatwereshoesolesmadefrominpreviousages?
SixMusicalFriends
HowdoIupgradefromGPLv2toGPLv3?
Needtostartareligionwithapredefinedselfdestruct
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
Paidcashforacar,butdealerwantstochangeprice
NineTallMenAreStandingTall
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
WhydosomepeoplerefertoLinuxasGNU/Linux?
PythonLabelExpression?ArcGIS10.3.1
MementoVivereMomentumMori
Drawarrowinamindmap
What'sanexpressionforacunninglyfakefriend?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
Doblockingcreatureshealbacktofullbetweenphases?
Ciertasconjugacionesverbalesnoconvencionales
Howtogetearlyentryintomystictheurge?
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
morehotquestions
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 302/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
ProblemsolvingrelatedtoObjectorientedprogrammingconcepts
ForquietsometimenowIhavebeenworkingonimprovingmyalgoskillsbecauseitsarequirementtoclearinterviewsincompanieslikegoogle,amazonetc.
ButrecentlyIcameacrossquestionsonobjectorientedprogrammingconceptsbeingaskedinamazoninterviews.IbeingaprogrammerinCdoesn'tknow
muchaboutoops.Anysortofhelplikegoodbooks,linkstoimprovetheseskillswillbegreatlyappreciated.Thanksinadvance.
upvote0
down oop
vote askedMay1'11at0:49
favorite
share|improvethisquestion
hue
56111129
addacomment|
4Answers
activeoldestvotes
IstartedwiththefirsteditionofTimBudd's"AnIntroductiontoObjectOrientedProgramming".Itwaslanguageagnostic,soIlearnedthe
concepts,nottheimplementations.
Thethirdeditionisnowout.
upvote1downvote
accepted answeredMay1'11at1:08
share|improvethisanswer
TerryWilcox
7,6111832
addacomment|
ReadtheGoFtostarttotrulyunderstanddesignpatternsolutionsinOOP.
upvote0 answeredMay1'11at0:59
downvote
share|improvethisanswer
Heisenbug
22.8k1369132
I'dskipit.DesignpatternsarenotthesamethingasOOconcepts.TerryWilcoxMay1'11at1:04
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 303/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
@TerryWilcox:youareright.That'snotthesame.Butreadingthatbookhelpedmealotinunderstandinghowmodelingsolutionsusingobjects,in
ordertotakemuchadvantageaspossiblefromOOP.HeisenbugMay1'11at1:13
Ifaninterviewerasksyoutoexplainpolymorphism,theGoFbookisgoingnotgoingtosaveyou.TerryWilcoxMay1'11at1:20
@TerryWilcox:IthinkIshouldkeepmyanswertoo.Lookatthetitle:"ProblemsolvingrelatedtoObjectorientedprogrammingconcepts."Isn'tGoF
aboutproblemsolvingwithOOP?HeisenbugMay1'11at10:49
addacomment|
OnceyouhaveagripontheOOconceptsIwouldreadsomeofthebasicOOprinciplesoutlinedbyRobertMartin:
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
upvote0 TheseprinciplesreallygiveObjectOrientationapurposeandIbetwouldbeexcellentforanyinterviewforadeveloperposition.
downvote
answeredMay2'11at0:56
share|improvethisanswer
DanielZeevPraaSandberg
1812
AndthenonceyougetagriponthoseprinciplesreadingtheGoFOOdesignpatternswillmakealotmoresensesincetheyarebasedonthebasicOO
principlesthatareoutlinedbyRobertMartinDanielZeevPraaSandbergMay2'11at0:59
addacomment|
Isuggest"Headfirst"seriesforbeginners.
1.HeadfirstOOAD
2.Headfirstdesignpatterns.
upvote0downvote Onceyoufeelyouarecomfortablewiththeconcepts,youcanreadGangoffourbookonDesignpatterns&OOAD
answeredMay2'11at5:10
share|improvethisanswer
SandeepGB
2,09611432
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 304/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedooporaskyourownquestion.
asked 4yearsago
viewed 1614times
active 4yearsago
Lookingforajob?
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Gettheweeklynewsletter!
Topquestionsand
answers
Important
announcements
Unanswered
questions
Signupforthenewsletter
Related
116
AspectOrientedProgrammingvs.ObjectOrientedProgramming
222
ObjectOrientedJavascriptbestpractices?
319
FunctionalprogrammingvsObjectOrientedprogramming
24
Theorybehindobjectorientedprogramming
7
ObjectOrientedDesignproblem
2
ObjectOrientedProgramminginPhpAreSOMEaspectsoverkillforanapplication?
2
ObjectOrientedProgrammingProblem
2
SimpleObjectorientedProgrammingConcepts
0
ObjectOrientatedProgrammingPracticeConcepts/EntitiesintoObjects
2
Implementationofobjectorientedanalysispatternsinarelationaldatabase
HotNetworkQuestions
Whyadding"incolour"whenreferringto"WizardofOz"?
Whyweren'ttheWeasleysapartoftheOriginalOrder?
CanICultureBombfaraway?
HowdoIhelpmygroupstopderailingourGMssetpiecebattles?
howcanItaketotalminutesfromtime?
HowdoIupgradefromGPLv2toGPLv3?
Thetwopronunciationsof
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 305/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Whatistheoriginofthepowericon?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Isturninggraphitecarbonintodiamondindustriallydoable?
ImageOpensasLayer0ratherthanBackground
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Multiplypurefunctionwithscalar
SixMusicalFriends
Howtodrawsequenceofshapeswitharrowsandtext
Drawarrowinamindmap
MementoVivereMomentumMori
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Needhelprecreatingcrazycolors/materialfromexample
Passfilenamefrombashtopython
Whydosocksstink?
Doblockingcreatureshealbacktofullbetweenphases?
HowdoIfacilitateafirsttimeAgileretrospective?
HowcanIcheckifmyfunctionprint/echo'ssomething?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
FindKnearestPointstoPointPin2dimensionalplane
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 306/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Source:AMAZONINTERVIEWQUESTION
GivenapointPandotherNpointsintwodimensionalspace,findKpointsoutoftheNpointswhicharenearesttoP.
Whatisthemostoptimalwaytodothis?
upvote3downvote
favorite ThisWikipagedoesnotprovidemuchofhelpinbuildingaalgorithm.Anyideas/approachespeople.
2
performancealgorithmmathlanguageagnostic
askedDec5'13at11:28
editedDec5'13at11:34
share|improvethisquestion
Spandan
594727
Ibalancedyoutozero)WillfollowupwithanswerDec5'13at11:34
Thisisjustavariationonthetheme"Findtheklowestnumbers".Onlythatyouhavetocalculatethedistancesforeachpoint.IngoDec
1
5'13at11:37
@Ingo"calculatethedistancesforeachpoint"...that'sbruteforceyouaresaying?SpandanDec5'13at11:39
1:Pleaseshowsomeeffort.Forexample,thisWikipediapagehasalotofinformationthatiseasilyfoundusinggoogle.Florian
1
BruckerDec5'13at11:42
addacomment|
3Answers
activeoldestvotes
Solution1makeheapofsizeKandcollectpointsbyminimaldistanceO(NLogK)complexity.
Solution2:TakeandarrayofsizeNandSortbydistance.ShouldbeusedQuickSort(Hoaremodification).AsanswertakefirstKpoints.ThisistooNlogN
complexitybutitispossibleoptimizetoapproximateO(N).Ifskipsortingofunnecessarysubarrays.Whenyousplitarrayby2subarraysyoushouldtake
onlyarraywhereKthindexlocated.complexitywillbe:N+N/2+N/4+...=O(N).
Solution3:searchKthelementinresultarrayandtakesallpointlesserthenfounded.ExistsO(N)alghoritm,similartosearchofmedian.
upvote12
downvote Notes:betterusesqrofdistancetoavoidofsqrtoperations,itwillbegreaterfasterifpointhasintegercoordinates.
accepted
AsinterviewanswerbetteruseSolution2or3.
answeredDec5'13at11:40
editedDec5'13at11:47
share|improvethisanswer
1,279416
Verywell:)...SpandanDec5'13at11:46
Canyouexplainsolution3abitmore?Itseemsverysimilartosolution2.DukelingDec5'13at11:47
Solution3isquickselectalgorithm.Storeallthedistancesinanarray.Findtheindexwhichgivesthekthsmallestelementusingmethodsimilarto
quicksort(Chapter9CLRS),thenelementfromindex0tok1willgivealltherequiredkpoints.ShankhoneerChakrovartyNov16'14at22:19
addacomment|
Forjustasinglequery...
Maintainaheapofsizek.
Foreachpoint,calculatethedistancetothepointP.Insertthatdistanceintotheheapanddeletethemaximumfromtheheapifthesizeoftheheapis
greaterthank.
upvote3down
vote Runningtime:O(nlogk)
answeredDec5'13at11:39
share|improvethisanswer
Dukeling
33.2k83169
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 307/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
YoucoulduseKDtreehttp://en.wikipedia.org/wiki/Kd_treetopartitionspaceandgiventhepointyouwillbeabletograduallysearchforneighborsusing
binarysearch.Benefitofusingthisapproachisthatiteasilyscalesuptoonlineversionwhenyoureceivepoints/queriesinruntimeonebyoneorinbatches.
upvote0
down answeredFeb4at5:53
vote
share|improvethisanswer
fury
1
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedperformancealgorithmmathlanguage
agnosticoraskyourownquestion.
asked 1yearago
viewed 2363times
active 5monthsago
Lookingforajob?
Sr.DevelopmentEngineer
AudienceScience
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 308/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Pune,India
javahadoop
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Gettheweeklynewsletter!
Topquestionsand
answers
Important
announcements
Unanswered
questions
Signupforthenewsletter
Related
654
Isfloatingpointmathbroken?
10
Datastructureforfindingnearbykeyswithsimilarbitvalues
4
Motionplanningwithoutagraphacrossaninfiniteplane
28
Giventwolinesonaplane,howtofindintegerpointsclosesttotheirintersection?
578
Easyinterviewquestiongotharder:givennumbers1..100,findthemissingnumber(s)
16
Closepackingpointsintheplane?
57
Nearestneighborsinhighdimensionaldata?
529
Findanintegernotamongfourbilliongivenones
0
findapointnoncollinearwithallotherpointsinaplane
14
Howtofindpairwithkthlargestsum?
HotNetworkQuestions
Whatistheoriginofthisphotoofanunexplodedbomb?
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
RollmyD&Dcharacter'sabilityscores
LeapyearcheckinJava
What'sanexpressionforacunninglyfakefriend?
Whatisatemporarysolutionforadamagedcarbody?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
Whycan'tanonabeliangroupbe75%abelian?
Whydosocksstink?
HowtoprovemyGmailhasbeenhacked?
Whyadding"incolour"whenreferringto"WizardofOz"?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Doblockingcreatureshealbacktofullbetweenphases?
ImageOpensasLayer0ratherthanBackground
Antiferromagneticordering
DoesCIDRreally"doaway"withIPaddressclasses?
Needhelprecreatingcrazycolors/materialfromexample
Wordfor"animals,includinghumans"?
ThenthTernary
Alarmclockprinting
FiveAnglesinaStar
Canmathbesubjective?
Howtogetearlyentryintomystictheurge?
Justifyingsuboptimalresearchqualitybylackofsupervision
questionfeed
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 309/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
WhatisthemaximumnumberofprocessorsthatcanrunusingNresources
suchthatdeadlockwillnotoccur?
AmazonInterviewQuestion:
Theproblemstatementisverysimple.
SupposewehaveNnumberofresources(allareindependentfromeachother),thenwhatisthemaximumnumberofprocessthatcanrun
simultaneously,usingatleastoneoftheresources,suchthattherewillbenodeadlock?
Asampleexampleisprovidedbelow,showingthattwoprocessusingtworesourcescanbeindeadlock.
Twoprocessindeadlock
upvote0down
votefavorite Someonepleaseprovidemetheanswerwithdetails.
processoperatingsystemdeadlock
askedJul12'13at4:58
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 310/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
share|improvethisquestion
shek8034
504410
Cananyonepleasethrowlightonthis??shek8034Jul14'13at3:41
1 stackoverflow.com/questions/5058406/KavishDwivediJul14'13at19:31
Theansweris:N*(N1)shek8034Jul15'13at20:08
addacomment|
Knowsomeonewhocananswer?Sharealinktothisquestionviaemail,Google+,Twitter,orFacebook.
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Browseotherquestionstaggedprocessoperatingsystemdeadlockoraskyourownquestion.
asked 1yearago
viewed 264times
Lookingforajob?
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 311/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Geek(s)
myglamm.com
Mumbai,India/relocation
javaios
Linked
26
Whatisthemaximumnumberofedgesinadirectedgraphwithnnodes?
Related
1
Howoftendodeadlocksoccur(abouttooccur)inanoperatingsystem
27
Maximumnumberofprocessesinlinux
2
Whataretheactionsasystemcantakewhenadeadlockisdetected?
2
Canexitingfromaprocessthatislockingamutexcauseadeadlock?
1
ResourceAllocationGraphDeadlockDetection
1
Nonresourcedeadlock?
0
Possibledeadlockgraphfor3threadsand2resources
0
Ifstarvationofprocessesisoccurred,doesitmeanthattherewillbeadeadlock?
3
Canweusedeadlocksforanything?
1
mixtureoflefthandedandrighthandedphilosophers,atrickyquestions?
HotNetworkQuestions
Whyweren'ttheWeasleysapartoftheOriginalOrder?
Whydosocksstink?
HowdoIupgradefromGPLv2toGPLv3?
ALN*NTicTacToeGame
IsWolframwrongaboutunique3colorability,oramIjustconfused?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Whatisatemporarysolutionforadamagedcarbody?
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
Justifyingsuboptimalresearchqualitybylackofsupervision
Needhelprecreatingcrazycolors/materialfromexample
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
WhoinventedStarTreksideburnsandwhy?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Jumpingcarwithtoomanyamps?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
Whyisthislongoverflowingto1,insteadoftheminimumvalueforthetype?
DoesCIDRreally"doaway"withIPaddressclasses?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Whydotheymanifestasrings?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
Paidcashforacar,butdealerwantstochangeprice
morehotquestions
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. Stack 1. English
1. Programmers 1. Photography
Overflow 1. Database Language&
2. Unix&Linux 2. ScienceFiction
2. ServerFault Administrators Usage 1. Mathematics
3. AskDifferent &Fantasy
3. SuperUser 2. Drupal 2. Skeptics 2. CrossValidated 1. StackApps
(Apple) 3. GraphicDesign
4. Web Answers 3. MiYodeya (stats) 2. MetaStack
4. WordPress 4. SeasonedAdvice
Applications 3. SharePoint (Judaism) 3. Theoretical Exchange
Development (cooking) 4. Travel 3. Area51
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 312/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
5. AskUbuntu 5. Geographic 4. User 5. Home 5. Christianity ComputerScience 4. Stack
6. Webmasters InformationSystems Experience Improvement 6. Arqade(gaming) 4. Physics Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 7. Bicycles 5. MathOverflow Careers
Development Engineering 6. Salesforce &Money 8. Roleplaying 6. more(7)
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia Games
LaTeX 8. InformationSecurity 8. more(10) 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Pythonhowtoremoveduplicatesonlyifconsecutiveinastring?
Forastringsuchas'12233322155552',byremovingtheduplicates,Icanget'1235'.ButwhatIwanttokeepis'1232152',onlyremovingthe
consecutiveduplicates.
Thankyouforyourhelpinadvance.
upvote4downvote
favorite pythonpython2.7
editedJul12'12at21:34 askedJul12'12at21:19
share|improvethisquestion
DSM user1522020
93k5132179 212
addacomment|
6Answers
activeoldestvotes
Microsoft/Amazonjobinterviewtypeofquestion:Thisisthepseudocode,theactualcodeisleftasexercise.
foreachcharinthestringdo:
ifthecurrentcharisequaltothenextchar:
deletenextchar
else
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 313/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
continue
returnstring
upvote7downvote
Asamorehighlevel,try(notactuallytheimplementation):
forsinstring:
ifs==s+1:##checkuntiltheendofthestring
deletes+1
answeredJul12'12at21:22
share|improvethisanswer
philippe
2,39332471
3 Goodcallonnotgivingexactcode(thoughPythonisprettydarnclosetopseudocodealready).JohnYJul12'12at21:28
addacomment|
Hint:theitertoolsmoduleissuperuseful.Onefunctioninparticular,itertools.groupby,mightcomeinreallyhandyhere:
itertools.groupby(iterable[,key])
Makeaniteratorthatreturnsconsecutivekeysandgroupsfromtheiterable.Thekeyisafunctioncomputingakeyvalueforeachelement.Ifnot
specifiedorisNone,keydefaultstoanidentityfunctionandreturnstheelementunchanged.Generally,theiterableneedstoalreadybesortedon
thesamekeyfunction.
upvote4 Sosincestringsareiterable,whatyoucoulddois:
down usegroupbytocollectneighbouringelements
vote extractthekeysfromtheiteratorreturnedbygroupby
jointhekeystogether
whichcanallbedoneinonecleanline..
answeredJul12'12at21:33
share|improvethisanswer
DSM
93k5132179
Excellent!Thanksuser1522020Jul12'12at22:09
addacomment|
importre
answer=re.sub(r'(\d)\1+',r'\1','12233322155552')
upvote2downvote answeredJul16'12at6:01
share|improvethisanswer
PauloFreitas
3,51263261
addacomment|
+1forgroupby.Offthecuff,somethinglike:
fromitertoolsimportgroupby
defremove_dupes(arg):
#creategeneratorofdistinctcharacters,ignoregrouperobjects
unique=(i[0]foriingroupby(arg))
return''.join(unique)
upvote0downvote
CooksformeinPython2.7.2
answeredJul12'12at22:46
share|improvethisanswer
godisdad
12
1 Ithinkwewerealltryingtoavoidactuallygivingtheansweroutright..DSMJul12'12at23:05
addacomment|
t='12233322155552'
foriint:
dup=i+i
t=re.sub(dup,i,t)
upvote0downvote Youcangetfinaloutputas1232152
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 314/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
editedFeb3'13at3:47 answeredJul16'12at5:28
share|improvethisanswer
Pradyun Prasanna
3,913941 534
addacomment|
Firstofall,youcan'tremoveanythingfromastringinPython(google"Pythonimmutablestring"ifthisisnotclear).
Mfirstapproachwouldbe:
foo='12233322155552'
bar=''
forchrinfoo:
ifbar==''orchr!=bar[len(bar)1]:
bar+=chr
upvote0downvote
or,usingtheitertoolshintfromabove:
''.join([k[0]forkingroupby(a)])
editedMar11'14at4:00 answeredJul12'12at23:49
share|improvethisanswer
AndyG paul
5,21822135 31
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 315/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonpython2.7oraskyourown
question.
asked 2yearsago
viewed 1671times
active 1yearago
Lookingforajob?
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
Linked
5
HowcanIconvertaunicodestringintostringliteralsinPython2.7?
1
CountingInstancesofConsecutiveDuplicateLettersinaPythonString
Related
285
HowdoyouremoveduplicatesfromalistinPythonwhilstpreservingorder?
0
Removeconsecutivedots(periods)fromastring?
1
Removingonlyalphaduplicates
0
Howtoremoveduplicatewordsfromsamestringincsvcolumn
0
Howtoremoveduplicatesfromareadandsplittextfile?
3
Removeconsecutiveduplicatesfroma2Dlist,python?
2
Python:Removingentriesofonelistbyduplicatesofanotherlist
1
Pythonlists,csv,duplicationremoval
1
Howtoremoveduplicatelinesonlyincertainsections?Python2.7.9
1
Removeduplicatelinesfromastringinpython
HotNetworkQuestions
Multiplypurefunctionwithscalar
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Isthereawordforpeopleincapableofthinking?
40Numbersin9Bytes
Thetwopronunciationsof
WhatdoesitmeanifanACmotorhastwovoltageratings?
Whyshouldakeybemadeexplicit?
What'sanexpressionforacunninglyfakefriend?
Hebrewdocumentfoundingrandfather'satticwhatdoesitstate?
Canmathbesubjective?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 316/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Clientwantsfontaslogo
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
Whydoesn'tthefundamentaltheoremofcalculusdependonthelowerbound?
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
HowdoIupgradefromGPLv2toGPLv3?
MementoVivereMomentumMori
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
Wordfor"animals,includinghumans"?
Howtogetearlyentryintomystictheurge?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
CanIwriteapaperoutofasimpleidea
Whatistheoriginofthisphotoofanunexplodedbomb?
Howtodrawsequenceofshapeswitharrowsandtext
CanIflywithagoldbar?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Whatisthespacecomplexityofthisalgorithm?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 317/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Thisisproblem9.6fromCrackingtheCodingInterview(5thedition)
Implementanalgorithmtoprintallvalidcombinationsofnpairsofparenthesis
EXAMPLE
Input:3
Output:"((())),(()()),(())(),()(()),()()()"
HereisthealgorithmIimplemented(inJava)
privatestaticSet<String>getAllComb(intn){
Set<String>allPoss=newHashSet<String>();
if(n>0){
if(n==1){
allPoss.add("()");
}else{
Set<String>before=getAllComb(n1);
for(Stringphrase:before){
intlength=phrase.length();
for(intstart=length2;start>=0;start){
if(phrase.charAt(start)=='('){
StringphraseToConsider=phrase.substring(0,start+1)+"()"+
phrase.substring(start+1);
upvote if(!allPoss.contains(phraseToConsider)){
3down allPoss.add(phraseToConsider);
vote }
favorite }
}
StringphraseToConsider="()"+phrase.substring(0);
if(!allPoss.contains(phraseToConsider)){
allPoss.add(phraseToConsider);
}
}
}
}
returnallPoss;
}
Thisproducesthecorrectoutput.Iknowthatinterviewers(atleastatAmazon)lovetoaskyouthetimeandspacecomplexityofyoursolution.Fortime
complexity,IwasabletoshowthatthealgorithmrunsinO(n)witharecurrencerelation.Iamhavingtroublewithanalyzingthespacecomplexity.Ithisisa
recursivesolutionsoitshouldbeatleastO(n)Butateachrecursivecall,Iamalsogeneratingasetthatisboundedbyn.WouldthetotalspacebeO(n)because
ofthenrecursivecallsorisitO(n2)becauseofthesetsizeofboundnforeachrecursivecalln?
algorithmrecursiontimecomplexityspacecomplexity
editedMar23at16:43 askedMar22at21:05
share|improvethisquestion
KyleTrauberman committedandroider
17.6k125390 1,817416
Sometipsonthesidethatdon'tdirectlyhavetodowithyourproblem:1)YoushouldbeabletouseN=0asyourbasecaseitscommoninrecursive
problemstonotneedtotreattheN=1specially2)Ifyouuseabufferoflength2nwhichtherecursivecalls"fillin"youshouldbeabletobringthespace
complexitydowntoO(n).hugomgMar22at21:22
Forn=4,thereare14possiblewaysofwritingproperlymatchedparantheses.Abufferoflength2n(orknforanyk)istoosmalltoholdtheoutputin
general.chepnerMar22at21:25
howwouldyouuseabufferoflength2n?Youcan'tpredefinethesizeofaset.committedandroiderMar22at22:13
@hugomgIjusttohaveanotherbasecaseofN=1becauseit'sjustonelineofcodeofadding"()".Youdon'thavetogothroughallthelinesofcodefor
iteratingoverthepreviousset,allthestrings,etc.Isthisreallybaddesignthoughstill?committedandroiderMar22at22:21
Itsnotbadpersebutextralinesofcodemeansmoreplacesforbugstohidein:)AndusuallytreatingN=1withthesamebranchofcodathantherest
shouldn'tbeabigperformancehit.Ifitisthenthereissomethigfishygoingon...hugomgMar22at23:08
addacomment|
2Answers
activeoldestvotes
Fortimecomplexity,IwasabletoshowthatthealgorithmrunsinO(n)witharecurrencerelation
Thisiswrong.ThenumberofsequencesofbalancedparenthesesisgivenbytheCatalannumbers:thereareexponentiallymanysuchsequences.Your
algorithmcannotbelinearifitisalsocorrectlysolvingtheproblem,becausejustoutputtinganexponentialnumberofsolutionsisitselftakingexponential
time.
upvote3 Asforthememorycomplexity,youseemtostoreallsolutionsforn1ateachstepnofyourrecursion,sothememorycomplexityalsolooksexponentialto
down me,plustheotherstringsyoucreateandrecursivecallsyoumakeateachstep,whichcanonlyaddtothecomplexity.
vote
accepted Youcansolvetheproblemwithoutusingexponentialmemory:thinkabouthowyoucangetridofstoringallprevioussequences.
answeredMar22at21:16
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 318/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
share|improvethisanswer editedMar22at21:21
IVlad
26.5k844121
Wouldn'tyouneedtostoreallprevioussequencestoapplythealgorithm?Ifyoudon'tstorethem,there'snowaytoaccessallthestringsandformallthe
combinationsofparentheses.committedandroiderMar22at22:11
@committedandroiderateachstep,youhavetwopossibilities:putanopenbracketoraclosedone.Bydoingitlikethis,youkeepthememoryusageto
O(n).Thiswillgenerateunbalancedsequencesaswell,butifyoufigureouthowtomakeitgenerateonlybalancedsequences,you'redone.Hint:keep
trackofhowmanyyou'veopenedandhowmanyyou'veclosed.IVladMar22at22:18
Idon'tgetquitegetwhatyoumean.HowIseethisproblemisfindingthepossibilitiesofputting"()"beforeandafteraopeningparenthesis.SayIhave
thefirstfunctioncallf(1)whichwouldbe().Inthiscase,whatdoyoumeanbyateachstep,putanopenbracketoraclosedbracket?Wouldn'tyouhave
toputbothanopenbracketandaclosedbracket?committedandroiderMar22at22:25
@committedandroiderThinkabouthowyoucanconstructasolutionbyputting(or)fromlefttoright:ateachstep,youmusthavemoreopensthan
closed.Thenyoucanbacktrack.Onceyouhavenopens,therestmustbeclosed.Alwaysputanopenifyoucan.Forexample,youstartwith((())).Then
youbacktrackto(((.Youcanmakethelastoneaclosed:(().Then,thenextcanbeanopen:(()(.Nowyoucanonlyhaveclosedfortherest:(()())etc.
IVladMar22at22:51
Withwhatyoudid,Iseetheprocessbehindgoingfrom((()))to(()())buthowwouldyougofrom((()))to()()()?Whatwouldyoufirstbacktrackitto?
committedandroiderMar22at23:07
|show3morecomments
ThenumberofwaystowritenpairsofproperlymatchedparenthesesisthenthCatalannumber,whichactuallygrowsexponentially,notquadratical.The
spacecomplexityoftheoutputaloneisO(2^n)seethewikipediaarticleforaquickoverviewoftheCatalannumbers.
upvote1 Noticethatyouaren'tmakingasinglerecursivecallateachdepth,butpotentiallyO(n)recursivecalls.
down
vote answeredMar22at21:16
share|improvethisanswer
chepner
82.4k764127
Whatdoyoumeanby"noticethatyouaren'tmakingasinglerecursivecallateachdepth"?IfImakeacalltothisfunctionwith4,thenthatwillmakea
callto3,whichwillmakeacallto2,thenso......Isn'tthatasinglerecursivecallateachdepth?committedandroiderMar22at22:15
Forthecallwithn,youdon'tnecessarilymakejustasinglecallwithn1,youmaymakeseveralsuchcalls.Thiswillcausetheamountofspaceusedby
thealgorithmtoincreasemuchmorequickly,eventhoughtherearenevermorethanO(n)activecallsinexistenceatonetime.chepnerMar22at
23:51
Ohsoatdepth4,you'reactuallymakingintotal4recursivecalls,f(3),f(2),f(1)andf(0)?committedandroiderMar23at0:21
addacomment|
YourAnswer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 319/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmrecursiontimecomplexity
spacecomplexityoraskyourownquestion.
asked 3monthsago
viewed 82times
active 3monthsago
Lookingforajob?
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
ApplicationDeveloper,Gurgaon
ThoughtWorksTechnologies
Gurgaon,India
java.net
Related
2
howwouldifindthetimeandspacecomplexityofthiscode?
23
Findtheknonrepeatingelementsinalistwithlittleadditionalspace
0
TimeandspacecomplexityofpassinganarrayinJava
7
Whatisthespacecomplexityofarecursivefibonaccialgorithm?
0
WhatisthetimecomplexityandspacecomplexityofthisalgorithmtofindAnagrams?
6
Ismyanalysisofspacecomplexitycorrect?
0
IsthespacecomplexityofthissubsetalgorithmactuallyO(n)?
3
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 320/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Whatisthespacecomplexityofenumeratingsubsets?
1
Whatisspacecomplexityforbreadthdepthsearchonabinarytree?
0
Whatisthespacecomplexityofthisbinaryadditionsolution?
HotNetworkQuestions
Nicelytypesettingverbatimtext
Wordfor"animals,includinghumans"?
Needtostartareligionwithapredefinedselfdestruct
Troublewithterminatinga<apex:pageBlockSection>
OptimalRopeBurning
Passwordrules:ShouldIdisallow"leetspeak"dictionarypasswordslikeXKCD'sTr0ub4dor&3
WhoinventedStarTreksideburnsandwhy?
Isturninggraphitecarbonintodiamondindustriallydoable?
Whatwereshoesolesmadefrominpreviousages?
Doestheopen/freecontentmovementlowerthebarriersofentryfornonqualifiedpeople?
DoesaUSB3.0connectionrequireaUSB3.0cord?
Thetwopronunciationsof
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
FindingoutifawordisanAnagramofanother
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Howtodecidewhetherastoryisworthwriting?
Whatisatemporarysolutionforadamagedcarbody?
Drawarrowinamindmap
LeapyearcheckinJava
Uncorrectedsamplestandarddeviationincorrelationcoefficient
HowdoIupgradefromGPLv2toGPLv3?
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
What'sanexpressionforacunninglyfakefriend?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 321/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Reverseagivensentenceinjava
Thiswasthequestionaskedmeinamazoninterview.,Writeaprogramtoreverseagivensentencelike"Thisisinterviewquestion"theoutputmust
be"questioninterviewisthis".Cananytellmehowtogetthisdone?
Thanksinadvance
upvote10down
votefavorite java
7 askedApr26'10at13:14
editedApr26'10at13:43
share|improvethisquestion
giri
7,3393592142
YoushouldprobablyconsidertakingJavacertificationclasses,astheywillteachyoucommonlyusedJavalibraryclasses.You'llthenhavethe
toolsneededtoaccomplishsuchtasks.MarcusAdamsApr26'10at13:29
1 Reversethestringfirst.Reversethewordsthen.Ittakestwopassbutveryclean.Canbedonein1passaswell.JackApr26'10at13:35
1 @jack,Ithinkyourfirstwordwasmeanttobe"split",yes?CPerkinsApr26'10at14:00
@CPerkins:well,"thequestion">"noitseuqeht">"questionthe"stillworks,andIsuspectthatiswhatJackmeantsinceanswerershave
2
alreadypostedyourway.PopsApr26'10at14:06
@CPerkinsNo.WhatImeantwas(inpython):<br>str="thisisinterviewquestion"<br>str1=str[::1]<br>printstr1<br>forwordin
str1.split(""):<br>printword[::1]<br>JackApr26'10at14:14
|show2morecomments
10Answers
activeoldestvotes
String[]words=sentence.split("");
String[]reversedWords=ArrayUtils.reverse(words);
StringreversedSentence=StringUtils.join(reversedWords,"");
(usingArrayUtilsandStringUtilsfromcommonslang,buttheseareeasymethodstowritejustafewloops)
upvote21
downvote
answeredApr26'10at13:17
editedApr12'12at22:59
share|improvethisanswer
Bozho
320k60630825
6 Usinganoutsidelibraryforaninterviewquestionthissimpleisn'tgoinggooverthatwell.D'NabreApr26'10at13:38
5 well.thatovergotogoingisn'tsimplethisquestioninterviewanforlibraryoutsideanUsingPowerlordApr26'10at13:44
@D'Nabreifyouknowcommonslangwellenoughtowritethatcode,IthinkitwouldgoVERYwelloverthatwell.ThorbjrnRavnAndersen
5
Apr26'10at13:50
@D'NabreIdon'tthinkso.Iftheyaskyoutoexplainhowaretheseutilitymethodsimplemented,you'dalwaysbeabletoexplain,butthusyouare
1
increasingtheeleganceofyourcode.Whatifthesemethdoswerepresentinjava.util.Arrays?BozhoApr26'10at13:50
Ifsomeonedemonstratedappreciationoftheknowandusethelibrariesguidelineinaninterview,I'ddefinitelyconsiderthataplus.JonikApr26'10
at14:08
|show5morecomments
Yousplitthestringbythespacetheniterateoveritbackwardstoassemblethereversedsentence.
string[]words="Thisisinterviewquestion".split("");
stringrev="";
for(inti=words.length1;i>=0;i)
{
rev+=words[i]+"";
}
//rev="questioninterviewisThis"
upvote19down //canalsouseStringBuilder:
vote StringBuilderrevb=newStringBuilder;
for(inti=words.length1;i>=0;i)
{
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 322/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
revb.Append(words[i]);
revb.Append("");
}
//revb.toString()="questioninterviewisThis"
answeredApr26'10at13:15
editedApr26'10at13:44
share|improvethisanswer
Oded
300k41465673
6 Won'tthisaddatrailingspace?SkilldrickApr26'10at13:26
Isthereareasonyou'reconcatenatingtoastring(whichcreatesanewstringobjecteverytime)insteadofusingaStringBuilder?
2
ChristopherParkerApr26'10at13:27
@ChristopherParkerSimplyshowingtheprinciple.Thiscanofcoursebeadaptedtobemoreperformant(ifneeded).OdedApr26'10at
13:31
@SkilldrickRev.trim();toremovethetrailingspace.Notthatthequestionspecified,butlikeyou,Idislikeextraspaceslikethat.Onion
1
KnightApr26'10at13:45
2 @Adamskiwhatisthatsayingaboutoptimisation...GarethDavisApr26'10at15:59
|show1morecomment
Justbeingdifferent:arecursivesolution.Doesn'taddanyextraspaces.
publicstaticStringreverse(Strings){
intk=s.indexOf("");
returnk==1?s:reverse(s.substring(k+1))+""+s.substring(0,k);
}
System.out.println("["+reverse("Thisisinterviewquestion")+"]");
//prints"[questioninterviewisThis]"
Iwillalsoimproveonthesplitsolutionbyusing\binstead(it'ssoobvious!).
upvote13downvote
String[]parts="Wordboundaryisbetterthanspace".split("\\b");
StringBuildersb=newStringBuilder();
for(inti=parts.length;i>0;){
sb.append(parts[i]);
}
System.out.println("["+sb.toString()+"]");
//prints"[spacethanbetterisboundaryWord]"
answeredApr26'10at13:51
editedApr26'10at14:03
share|improvethisanswer
polygenelubricants
167k58382522
nice,ireallylikedtherecursivesolutiondesign,buttheiteration+stringbuilderhastobefaster,correct?user797963Nov18'13at3:46
addacomment|
Justsplititonaspacecharacterintoastringarray,thenloopoverthearrayinreverseorderandconstructtheoutputstring.
Stringinput="Thisisinterviewquestion";
Stringoutput="";
String[]array=input.split("");
for(inti=array.length1;i>=0;i)
{
output+=array[i];
upvote6downvote
if(i!=0){output+="";}
}
answeredApr26'10at13:16
editedApr26'10at13:29
share|improvethisanswer
RichAdams
12.7k32248
canupleasegivecodewithoutusingsplit()MaxSep6'11at15:56
addacomment|
BozhoalreadygaveagreatJavaspecificanswer,butintheeventyoueverneedtosolvethisproblemwithoutJavaAPImethods:
Toreverse,youcansimplypopindividualwordsontoastackandpopthemallbackoffwhentherearenowordsleft.
(Justtobeextraclear,JavadoesprovideaStackclass,soitispossibletousethismethodinJavaaswell).
upvote5downvote
answeredApr26'10at13:22
share|improvethisanswer
Pops
12.1k1993122
addacomment|
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 323/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
aeveryboringbitofjava:
List<String>l=newArrayList<String>(Arrays.asList("thisisaninterviewquestion".split("\\s")));
Collections.reverse(l);
StringBufferb=newStringBuffer();
for(Strings:l){
b.append(s).append('');
}
b.toString().trim();
ingroovyit'salittlebitmorereadable:
upvote3downvote
"thisisaninterviewquestion"
.split("\\s")
.reverse()
.join('')
answeredApr26'10at13:22
share|improvethisanswer
GarethDavis
18.3k65183
@Oded'sisalotnicer...waytousedtojustusingcollections.GarethDavisApr26'10at13:24
addacomment|
Ialsogiveitatry:Here'saversionusingastackandascanner:
Stringinput="thisisinterviewquestion";
Scannersc=newScanner(input);
Stack<String>stack=newStack<String>();
while(sc.hasNext()){
stack.push(sc.next());
}
StringBuilderoutput=newStringBuilder();
for(;;){//forever
upvote3downvote output.append(stack.pop());
if(stack.isEmpty()){
break;//endloop
}else{
output.append("");
}
}
answeredApr26'10at14:20
share|improvethisanswer
Searles
316212
addacomment|
publicclassReverseString{
publicvoidreverse(String[]source){
Stringdest="";
for(intn=source.length1;n>=0;n){
dest+=source[n]+"";
}
System.out.println(dest);
publicstaticvoidmain(Stringargs[]){
upvote2downvote ReverseStringrs=newReverseString();
String[]str="Whatisgoingon".split("");
rs.reverse(str);
editedJul22'12at13:17 answeredApr28'10at5:14
share|improvethisanswer
BoPersson gmhk
45.3k956111 4,754145694
addacomment|
nicerapproachprobably..hadseenthelogicsomewhere..hereismycodewhichmightdothejob.
publicclassrevWords{
publicstaticvoidmain(String[]args){
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 324/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
revWordsobj=newrevWords();
Stringprint=obj.reverseWords("IamGod");
System.out.println(print);
publicStringreverseWords(Stringwords)
{
if(words==null||words.isEmpty()||!words.contains(""))
upvote1downvote returnwords;
Stringreversed="";
for(Stringword:words.split(""))
reversed=word+""+reversed;
returnreversed;
}
answeredDec1'10at4:35
share|improvethisanswer
shashi
111
addacomment|
Idon'tthinkyoushoulduseanylibrary..1)Reversewholestring2)Reverseeachword.
publicstaticvoidrevWord(char[]a){
//reversewhole
revWord(a,0,a.length);
intst=1;
intend=1;
for(inti=0;i<a.length;i++){
if(st==1&&a[i]!=''){
st=i;
}
if(end==1&&a[i]==''){
end=i;
}
if(i==a.length1){
end=i+1;
}
if(st!=1&&end!=1){
revWord(a,st,end);
upvote0downvote st=1;
end=1;
}
publicstaticvoidrevWord(char[]a,ints,intl){
intmid=(ls)/2;
l;
for(inti=0;i<mid;i++,l){
chart=a[s+i];
a[s+i]=a[l];
a[l]=t;
}
}
answeredApr9'13at3:17
share|improvethisanswer
RajenderSaini
351418
addacomment|
protectedbyKevJul22'12at13:57
Thankyouforyourinterestinthisquestion.Becauseithasattractedlowqualityanswers,postingananswernowrequires10reputationonthissite.
Wouldyouliketoansweroneoftheseunansweredquestionsinstead?
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaoraskyourownquestion.
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 325/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
asked 5yearsago
viewed 26235times
active 2yearsago
Lookingforajob?
UIDeveloperataprofitableSaaSstartup
Recruiterbox
Bengaluru,India/relocation
htmlcss
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Gettheweeklynewsletter!
Topquestionsand
answers
Important
announcements
Unanswered
questions
Signupforthenewsletter
Linked
1
ReversingtheSentenceinjava
4
whatisthesimplewaytoreversethewordsinstringinjava?
1
Reversingwordsindividuallyusingastack
9
HowtoprintthemirrorofStringinjavawithouteffectingthewords?
3
Howtostorewordsfromafileintoastring,andprintthemoutinreverse?
3
Java:ReversetheStringbutremaintheindexofthecomma
Related
2234
IsJavapassbyreferenceorpassbyvalue?
1922
Avoiding!=nullstatementsinJava?
1402
CreatingamemoryleakwithJava
2088
Java+=operator
0
ReversingasentencerecursivelyinJava
1
ReversingtheSentenceinjava
1
JavaUsingastacktoreversethewordsinasentence
2
Reversingthewordsinasentencestring
2
Reversethewordsinasentence
2
Solutioncritique:reversingwordsinasentence
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 326/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
HotNetworkQuestions
IsthereanEnglishequivalenttothePersiansaying"Nowthatit'smyturn,theskycamedown"?
Whydosocksstink?
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
HowcanIcheckifmyfunctionprint/echo'ssomething?
HowdoIfacilitateafirsttimeAgileretrospective?
Whatisatemporarysolutionforadamagedcarbody?
ImageOpensasLayer0ratherthanBackground
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
HowtoprovemyGmailhasbeenhacked?
Shouldmy(sequential)collectionstartatindex0orindex1?
40Numbersin9Bytes
Whatistheoriginofthepowericon?
Jumpingcarwithtoomanyamps?
Nicelytypesettingverbatimtext
Whyshouldakeybemadeexplicit?
OptimalRopeBurning
FindingoutifawordisanAnagramofanother
Justifyingsuboptimalresearchqualitybylackofsupervision
MementoVivereMomentumMori
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
Uncorrectedsamplestandarddeviationincorrelationcoefficient
WhycanfunctionallanguagesbedefinedasTuringcomplete?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 327/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Algorithmtofindsimilarityofquestions
Ididsamedataminingandpulledalltheinterviewquestionsfromgoogleandmicrosoftonglassdoor:http://letschat.info/?p=34
http://letschat.info/?p=37
Ihavethetwolistsonthere.
WhatIwanttodoismaybepullafewothercompaniesinterviewquestionsandtrytofindquestionsthatsimilaramongmultiplesources.
IdidsomegooglingandIfoundthisproject:
http://lucene.apache.org/core/
andIcoulddothefollowing:http://javatechniques.com/blog/luceneinmemorytextsearchexample/
Howeverthisseemslikeoverkill.Isthereasimpleralgorithmthatcouldhelpmefindsimilarquestions?Whatalgorithmdoesstackoverflowuse?
Iwasthinkingofmaybegeneratingascorebasedonthenumberofwordsthatmatchbetweentwoquestionsandfilteritthatway.
upvote3down
votefavorite Iwanttotrytowhittlethelistofquestionsdowntoalistofuniquenumberofquestions.
Update:
Idecidedtouselucene.Iputmyentirelistintoanindexandtheiteratethroughthelistanduselucenetosearchfor10itemslikeit.Ithenaddupthe
scoreofthe10resultstooseewhatquestionswereaskedthemost.
Hereisthelinktotheactualcode:http://letschat.info/rankingofreducedamazonquestions/
Itisn'ttoocomplicated.Hereisanexampleoftheresults:http://letschat.info/rankingofreducedamazonquestions/
fromtheoriginalsource:http://letschat.info/listofamazonquestions/
algorithmsearchdatamining
askedFeb26'12at20:31
editedMar8'12at20:27
share|improvethisquestion
SamFisher83
1,36811839
Ilikeyourideaofgettingascorebasedonwordmatchcount.Everytimeonequestionisaddedtothelist,youshouldsavethequestionalong
withthescoretothedb.Thenit'sasimplequeryasnewquestionscomein?IndusterFeb26'12at20:38
addacomment|
2Answers
activeoldestvotes
Actually,cosinesimilarityontfidfvectors,whichiswhatLuceneimplements,isacommon(andprettybasic)wayofmeasuringinterdocumentsimilarity.
I'dtryitifIwereyou(althoughyourdocumentsmaybeabitshortforittofunctionreallywell).Lucenedoessomenicetextnormalizationaswell.
upvote2
down answeredFeb26'12at20:39
vote
share|improvethisanswer
larsmans
194k22336505
Iamnottryingtodointerdocumentsimilarity,butmoretryingtocomparesentences,butIguessImightjustusethatmethod.ThanksSamFisher83
Feb26'12at21:14
SentencesarejustveryshortdocumentsTFIDFandcosinesimilarityarethetwostandardtechnologiesfortextualsimilarity.AnonyMousseFeb27
2
'12at6:49
addacomment|
Simmetricsisalibrarythatoffersmultiplestringcomparisonalgorithms.Checkwhichonesworksbestforyourneeds.
Oneapproachyoumightconsidersincetheseare"questions"istousengrams,improvesaccuracy.
upvote0downvote answeredMar3'12at2:16
share|improvethisanswer
Mikos
5,78722652
Doesn'tseemlikeitisactivelydevelopedSamFisher83Mar7'12at1:34
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 328/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedalgorithmsearchdataminingorask
yourownquestion.
asked 3yearsago
viewed 466times
active 3yearsago
Lookingforajob?
Sr.DevelopmentEngineer
AudienceScience
Pune,India
javahadoop
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Geek(s)
myglamm.com
Mumbai,India/relocation
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 329/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
javaios
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
Related
53
Algorithmforfindingsimilarimages
4
Algorithmsforfindingsimilarquestionsbasedonanotherquestion'stitle?
7
Recommendationalgorithm(andimplementation)forfindingsimilaritemsandusers
615
Ukkonen'ssuffixtreealgorithminplainEnglish?
1
HowtoidentifyanewpatterninaURLwithamachinelearningalgorithm(Textmining)
2
WhatalgorithmdoesStackOverflowuseforfindingsimilarquestions?
0
SimpleexplanationofdifferentElasticSearchsimilarityalgorithms
1252
Whatistheoptimalalgorithmforthegame2048?
0
Comparing2NearestNeighborslistsintermsofsimilarity
4
Goodalgorithmtofindsimilarareasinimages?
HotNetworkQuestions
FindingoutifawordisanAnagramofanother
HowtoprovemyGmailhasbeenhacked?
ImageOpensasLayer0ratherthanBackground
LeapyearcheckinJava
SixMusicalFriends
Nicelytypesettingverbatimtext
Idiomforsomeonewhobuysallthebestgeartodosomethingbeforetheyevenhaveabasicproficiency?
Whycan'tanonabeliangroupbe75%abelian?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
DoesCIDRreally"doaway"withIPaddressclasses?
CanIflywithagoldbar?
WhatdoesitmeanifanACmotorhastwovoltageratings?
Whydosocksstink?
DoesaUSB3.0connectionrequireaUSB3.0cord?
HowdoIfacilitateafirsttimeAgileretrospective?
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
CanIwriteapaperoutofasimpleidea
ALN*NTicTacToeGame
HowcanIcheckifmyfunctionprint/echo'ssomething?
What'sanexpressionforacunninglyfakefriend?
Wordfor"animals,includinghumans"?
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Thetwopronunciationsof
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 330/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Interviewquestionsatamazoninunix[closed]
1.Countmultipleoccurencesofyournameinafile..andyournameisoccurringmultipletimesinaline.
2.WritearegularexpressiontoretrieveRavi10fromthefile.AndprintonlythenameRavi10(completelineshouldnotbeprinted).
3.Inalogfileyouhavedateinyyyymmddhh:mi:ssformat.Retrivethosedateswheretimeisbetween19:10:00to19:20:00
upvote5downvotefavorite
shellunix
askedApr4'13at12:12
editedApr4'13at12:27
share|improvethisquestion
Satheesh
581211
closedastoolocalizedbyiiSeymour,hlovdal,user4815162342,bensiu,talonmiesApr4'13at12:41
Thisquestionisunlikelytohelpanyfuturevisitorsitisonlyrelevanttoasmallgeographicarea,aspecificmomentintime,oranextraordinarilynarrowsituationthatis
notgenerallyapplicabletotheworldwideaudienceoftheinternet.Forhelpmakingthisquestionmorebroadlyapplicable,visitthehelpcenter.Ifthisquestioncanbe
rewordedtofittherulesinthehelpcenter,pleaseeditthequestion.
3 AreyouinamiddleofaUNIXinterviewandpostthemessagewithyourmobiletogettheresult?:)fedorquiApr4'13at12:13
ThiswasthequestionaskedinamazoninterviewwhichiwasnotabletoanswersopleaseletmeknowSatheeshApr4'13at12:15
addacomment|
1Answer
activeoldestvotes
IhopeIgetthejobifIanswerproperly...
1.Countmultipleoccurencesofyournameinafile..andyournameisoccurringmultipletimesinaline.
grepo"your_name"file|wcw
2.WritearegularexpressiontoretrieveRavi10fromthefile.AndprintonlythenameRavi10(completelineshouldnotbeprinted).
grepo"Ravi10"file
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 331/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
upvote2downvote 3.Inalogfileyouhavedateinyyyymmddhh:mi:ssformat.Retrivethosedateswheretimeisbetween19:10:00to19:20:00
awk'{if(($4~"19:1[09]")||($4~"19:20")){print}}'your_file
answeredApr4'13at12:30
share|improvethisanswer
fedorqui
73.9k2292129
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedshellunixoraskyourownquestion.
asked 2yearsago
viewed 3239times
active 2yearsago
Lookingforajob?
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
Related
95
IsthereaUnixutilitytoprependtimestampstolinesoftext?
24
Unixshellfilecopyflatteningfolderstructure
183
What'sthebestwaytocheckthatenvironmentvariablesaresetinUnixshellscript
78
AddupacolumnofnumbersattheUnixshell
88
ListingonlydirectoriesinUNIX
0
howtomovefilesfromonepathtoanotherpathinunixusingshellscript
87
GoingtoaspecificlinenumberusingLessinUnix
0
IssueconvertingDatetoTimestampusingUnix
1
Howtoextractdetailsfromreporthavingdateinyyyymmddformatinarowuntillnextyyyymmddentryfoundsinunix
0
BestpracticetoreducethecomplexityoftheUNIXShellscript
HotNetworkQuestions
Troublewithterminatinga<apex:pageBlockSection>
HowcanIcheckifmyfunctionprint/echo'ssomething?
Whatistheoriginofthisphotoofanunexplodedbomb?
Isthereawordforpeopleincapableofthinking?
CanICultureBombfaraway?
Whatdoesthisnotehaveastempointingupandanotherpointingdown?
PythonLabelExpression?ArcGIS10.3.1
Whyshouldakeybemadeexplicit?
Justifyingsuboptimalresearchqualitybylackofsupervision
FindingoutifawordisanAnagramofanother
Multiplypurefunctionwithscalar
Paidcashforacar,butdealerwantstochangeprice
Nicelytypesettingverbatimtext
LeapyearcheckinJava
Using"using"twiceinterpreteddifferentlybydifferentcompilers
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
Needhelprecreatingcrazycolors/materialfromexample
Whatwereshoesolesmadefrominpreviousages?
Ifallmotionisrelative,howdoeslighthaveafinitespeed?
HowtodealwithaGMwhodoesnottelluseverything?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 332/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
Doblockingcreatureshealbacktofullbetweenphases?
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Howtodecidewhetherastoryisworthwriting?
morehotquestions
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
AmIfollowingagoodapproach?
Pleasefindthelinktothediscussedproblem.
Sorting|AmazonInterviewQuestion
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 333/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Ifollowedthisfollowingapproachbytakingrandomarrays.Wouldwantyoursuggestionsonwhatotherapproachescanbefollowedtosolvethe
problem:
publicclassThreeMachineInsertionSorting{
publicstaticvoidmain(String[]args){
int[]ar1={10,9,8,7,6,5,4,3,2,1,10};
int[]ar2={20,19,18,17,16,15,14,23,12,11,10};
int[]ar3={20,19,21,122,10,9,11,12,4,13,18,17};
performInsertionSort(ar1,ar2,ar3);
}
privatestaticvoidperformInsertionSort(int[]ar1,int[]ar2,int[]ar3){
int[][]arrayOfArrays={ar1,ar2,ar3};
int[]unSortedArray=mergeArrays(ar1,ar2,ar3,arrayOfArrays);
inti,j,key;
for(i=1;i<unSortedArray.length;i++){
key=unSortedArray[i];
j=i1;
while(j>=0&&key<unSortedArray[j]){
unSortedArray[j+1]=unSortedArray[j];
j;
}
unSortedArray[j+1]=key;
}
System.out.println("SizeoftheunSortedarrayis:="+unSortedArray.length);
shareLoad(unSortedArray,arrayOfArrays);
privatestaticvoidshareLoad(int[]sortedArray,int[][]arrayOfArrays){
intloadFactor=sortedArray.length/3;
intindex=0;
while(index<sortedArray.length){
for(int[]ar:arrayOfArrays){
upvote0downvote for(inti=0;i<ar.length;i++){
favorite if(i<=loadFactor){
ar[i]=sortedArray[index];
index++;
}
}
}
}
for(int[]ar:arrayOfArrays){
System.out.println("******************************************arrayproperties**************************************");
System.out.println("Sizeofarray::"+ar.length);
for(inti=0;i<ar.length;i++){
System.out.print(ar[i]+"");
}
System.out.println("\n******************************************************************");
}
privatestaticint[]mergeArrays(int[]ar1,int[]ar2,int[]ar3,int[][]arrayOfArrays){
int[]colaboratedArray=newint[ar1.length+ar2.length+ar3.length];
System.out.println("Lengthofmultidimensionalarray:"
+arrayOfArrays.length);
inti=0;
while(i<colaboratedArray.length){
for(int[]ar:arrayOfArrays){
for(intj=0;j<ar.length;j++){
colaboratedArray[i++]=ar[j];
}
}
returncolaboratedArray;
}
}
sorting
askedFeb24at10:29
share|improvethisquestion
Ankit
266318
addacomment|
1Answer
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 334/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
activeoldestvotes
Hereisabitofanaivesolution.
SortM1,M2andM3usinginplacesortingalgorithm.
CombineM1andM3byfindingoutthepointwhereallelementsfromM1canbeswappedoutforsmallerelementsinM3.
Tofindthispointtake1/9ofthenumbersinM3andmovetothebufferinM1.Noticethat1/9ofthenumbersisexactlythe10%capacityavailable.Westartwith
thesmallestbucketinM3andcompareittothelargestbucketinM1.JustbycomparingthelargestvaluefromtheM3bucketandthesmallestvaluefromtheM1
bucketwecandetermineifwecanswapthemoutcompletelyornot.IfwecanthenmovethebucketfromM1toM3andbringinnewbucketfromM3.Dothis
untilwehaveM1andM3partitioned.
up NowwemustsortM1andM3again.NowwemusttakethesmallestelementsfromM2andmovethemtoM1untilwehaveM1andM2partitioned.Afterthatis
vote donewecansortM1andM2.NoticethatM1isnowfinished.
0
down FinishbypartitioningM2andM3andthensortbothandtheproblemissolved.
vote
Noticethatthissolutionrequiresustosortallmachinesthreetimes,andeachdataelementisinworstcasemoved3timesbetweenmachines.
Thissolutioncanbeimprovedifwecanfindthemedianoftwounsortedsets,thenwecanpartitionthesetsaccordingtothismedianandthentransferring
elements,andonlysortintheendonceweknowthatthefinalnumbersareoneachmachine.
ItcanbefurtherimprovedifwecanfindtheKthlargestelementof3unsortedsetsefficientlywithouttransferringdata.
answeredFeb24at13:09
share|improvethisanswer
Mazvl
5851417
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 335/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedsortingoraskyourownquestion.
asked 4monthsago
viewed 28times
active 4monthsago
Lookingforajob?
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Related
30
AgoodSortedListforJava
12
howtosortbylengthofstringfollowedbyalphabeticalorder?
0
Howtosortthefollowingarray?
0
CountingSortoddresultsforlistwithduplicateentries
0
Whatwouldbeagoodalgorithmforsortingobjectsbyimportance?
3
Pleaseexplainthefollowingsortingfunction
0
HowcanIfindthetaoffollowingRecurrence
0
BlockSortAlgorithm
2
Whatisagoodapproachforanaccountingalgorithm?
3
Javascriptthegoodparts:sortingnotstable?
HotNetworkQuestions
Ciertasconjugacionesverbalesnoconvencionales
Whydotheymanifestasrings?
SixMusicalFriends
Passfilenamefrombashtopython
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Whatis`$?`?Isitavariable?
Packagetodonotes:HowcanIchangethetextcolor?
HowcouldaresurrectedJesusproveheisJesus?
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
NineTallMenAreStandingTall
FiveAnglesinaStar
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Paidcashforacar,butdealerwantstochangeprice
Nicelytypesettingverbatimtext
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 336/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
WhoinventedStarTreksideburnsandwhy?
40Numbersin9Bytes
Whatistheoriginofthepowericon?
Howtogetearlyentryintomystictheurge?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
WhyareUNIX/POSIXsystemcallnamingssoillegible?
zero,zerosorzeroes?
DoesCIDRreally"doaway"withIPaddressclasses?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Howtoconvertapathcontaining..traversalstoacanonicalpath,inPHP?
[closed]
IjusthadaninterviewwithAmazon.Iwasaskedthisquestion:
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 337/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
//CONVERTINPUTTOOUTPUT:
//input=>/var/www/../html/../a/data/
//output=>/var/a/data/
Isthereabettersolutiontoitthanthis?
$string="/var/www/../html/../a/data/";
$str=explode('/',$string);
if($str[0]=="")
array_shift($str);
upvote2
downvote $max=sizeof($str);
for($i=0;$i<$max;$i++){
favorite $str[$i]="/".$str[$i];
if(strpos($str[$i],"..")){
unset($str[$i]);
unset($str[$i1]);
}
}
echo$string=implode($str);
phpstring
editedApr4at3:35 askedApr3at23:35
share|improvethisquestion
BoltClock ArturGrigio
304k66753914 145
closedasunclearwhatyou'reaskingbyBarmar,Rizier123,nhgrif,Mat'sMug,GhostApr4at1:56
Pleaseclarifyyourspecificproblemoraddadditionaldetailstohighlightexactlywhatyouneed.Asit'scurrentlywritten,itshardtotellexactlywhatyou'reasking.See
theHowtoAskpageforhelpclarifyingthisquestion.Ifthisquestioncanberewordedtofittherulesinthehelpcenter,pleaseeditthequestion.
1 Whatisthepatternbehindthistogettothisoutput?Rizier123Apr3at23:37
2 Uh,@Barmar...no?There'snocodetoreviewhere.nhgrifApr3at23:40
@nhgrifHepostedthecodeinananswer.BarmarApr3at23:41
@BarmarAnswer'saren'tpartofthequestion.HisanswermightbeappropriateforCodeReview,buthisquestiondefinitelyisn't,andhisquestion
2
definitelyisn'taquestionaboutimprovingcode.nhgrifApr3at23:42
@BarmarAndheequallywouldn'tunderstandtheprotocolatCodeReview.Don'trecommendbadquestionstoothersites.Justclosethemforwhatever
1 appropriateclosereason.IsthisquestionTooBroad?IsitUnclear?Chooseoneofthoseclosereasonsanddon'trecommendpeopleaskbadquestions
onothersitesandforceothersitestoalsohavetodealwithapoorquestion.nhgrifApr3at23:59
|show1morecomment
1Answer
activeoldestvotes
AssumingcorePHPfunctionsarepermitted,howaboutthis?
<?php
echorealpath('/var/www/../html/../a/data/');
upvote1downvoteaccepted
answeredApr3at23:37
share|improvethisanswer
halfer
11.6k53161
wow!Ifeelquitedumbrightnow!Thankyou.ArturGrigioApr4at4:02
Ha,noworries@Artur.Ofcourse,yoursmayhavebeenfineiftheywerelookingforanalgorithm.halferApr4at7:51
addacomment|
Nottheansweryou'relookingfor?Browseotherquestionstaggedphpstringoraskyourownquestion.
asked 3monthsago
viewed 45times
active 3monthsago
Lookingforajob?
ApplicationDeveloper,Pune
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 338/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
ThoughtWorksTechnologies
Pune,India
java.net
PolyglotDeveloper(ruby,javascript,clojure,etc.)
MavenHiveTechnologiesPvt
Bengaluru,India/relocation
rubyonrailsstartup
Related
2790
HowcanIpreventSQLinjectioninPHP?
209
ConvertinganintegertoastringinPHP
3239
HowcanIcheckifonestringcontainsanothersubstring?
189
Howtostripallspacesoutofastringinphp?
142
howtogetthelastcharofastringinPHP?
751
HowdoIcheckifastringcontainsanotherstringinObjectiveC?
96
Howtoconvertstringtobooleanphp
2
HowtodealwithinlinePHPforeignlanguagecharacters?
117
PHPstringcontains
0
howdoiwriteaspaceafterastringinaphppageredirectedfromahtmlpage?
HotNetworkQuestions
Functionsthataretheirowninversion.
WouldahomemadelawnchairballoonbevisibleonATCandcollisionavoidanceradar?
Removestaticobjectsfromanimagesequence
Arethereanycoststousingavirtualfunctionifobjectsarecasttotheiractualtype?
What'sanexpressionforacunninglyfakefriend?
Whatwereshoesolesmadefrominpreviousages?
Whatis`$?`?Isitavariable?
Derivativeofadefiniteintegralissue
Whyadding"incolour"whenreferringto"WizardofOz"?
Howlongisitreasonabletowaitforagraduatestudentorpostdoctoobtainavisa?
Whyshouldakeybemadeexplicit?
ThenthTernary
Alarmclockprinting
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Multiplypurefunctionwithscalar
Wordfor"animals,includinghumans"?
WhatwillbethesituationoftheworldwheneverybeingswillattainNirvana?
Whatisatemporarysolutionforadamagedcarbody?
DoesCIDRreally"doaway"withIPaddressclasses?
Whydospaceagenciesinvestmoreinflybyprobesratherthanorbitingsatellites?
Using"using"twiceinterpreteddifferentlybydifferentcompilers
Antiferromagneticordering
IsthereanEnglishequivalanttotheRussiansaying"thebakerneverbuyshisbread"?
SixMusicalFriends
morehotquestions
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 339/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Canyoupairprogramremotely?
Wehaveateamofabout7engineers,whomIsupervise.Wedonothaveaformalofficewhereweallwork.Instead,ahandfularelocatedoutsideofourcity,
whiletherestofusarescatteredaroundtheBayArea.
Quitefrequently,IfindmyselfattemptingtoteachconceptslikeTDDorrefactoringtosomeofourmorejunior(ornot)developers.ThebesttechniqueI
knowispairprogramming,whereyoubothsitatthesamecomputerandworkonaproblemtogether.Sincewearenotinthesameplacemostofthetime,the
upvote28 onlyoptionistousesomekindofscreensharingandSkypetohaveoneofus"drive"whiletheotherconsults,andthenswitch.
downvote
favorite Myquestionishasanyonetriedthis"virtual"pairprogramming,anddidyoufinditatalluseful?
7
tddpairprogramming
askedAug29'08at16:16
share|improvethisquestion
SamMcAfee
4,83893758
screenhero.comMSSucksJun19'14at6:55
addacomment|
11Answers
activeoldestvotes
I'vedonequitealotofpairprogrammingnotonlycrosssitebutcrosstimezone.IliveinIsraelandIworkwithpeopleontheWestCoastallthetime.The
bestwayI'vefoundistousesharedVNCsessionandskype.Youneedsome"goodbehavior"toensurethatonlyoneofustypesatagiventime.TheVNC
serverthatweusegivesustwodifferentpointerssowecanmoveourrespectivemicewithoutgettingintheway,solongaswedon'tactuallyclick.
upvote Themainproblemisthattheclipboardisshared,soifsomeoneselectssomethingit'sautomaticallycopiedtotheother'sclipboard.
11down Asageneralrule,pairprogrammingcrosssite,whilenotideal,iscertainlyworkable,andmostdefinitelyuseful.
vote
accepted answeredAug29'08at18:44
share|improvethisanswer
NathanFellman
37.6k47167244
Which"VNCserverthatweusegivesustwodifferentpointers"?BrianCarltonFeb22'10at19:27
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 340/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
2 @Brian,weuseRealVNCfromrealvnc.comNathanFellmanFeb23'10at8:24
screenhero.comMSSucksJun19'14at6:55
addacomment|
IknowNetbeanshasapluginfor"DeveloperCollaboration"(flashdemo),whichisbasicallylikemultiplayerprogramming.Anychangesyoumakeinyour
localfilearereplicatedalmostimmediatelytotheotherparty.It'sprettycool,butit'sbeenawhilesinceI'veplayedwithit,andI'veneveruseditforareal
project.Thereisachatwindowbutyou'reprobablybetteroffstilltalkingonthephoneorusingskype.
upvote
5down answeredAug29'08at16:48
vote
share|improvethisanswer
OutlawProgrammer
6,98453055
addacomment|
Yes,youcanabsolutelypairprogramremotely,andI'vedonesosuccessfullyforextendedperiodsoftime.WehadSkypeaudiochatopenprettymuchallday
long,andusedTeamViewertomirrorthescreen.Workedsplendidly.
upvote IfIrecallcorrectly,ithasapen/drawingtoolthatallowsthenavigatortoshowthedriverwhathe'stalkingaboutonthescreen.
4down
vote editedJan4'12at6:51 answeredMar29'10at14:06
share|improvethisanswer
sra MattiasPetterJohansson
19.8k63466 443316
+1thishasbeenmyexperience,insomewayssharingascreencanbebetterthansittingatthesamecomputerasyoucanbothseethecodeunobstructed.
Theonlyproblemisthereisalotofwaitingforthedrivertodothingsbutthereisnoreasonwhyyoucantbeinvestigatingthesamethingprivatelyonyour
ownmachineatthesametimeWillbillJul30'10at11:06
addacomment|
Tryingtopairprogramremotelyprobablywon'tbeasusefulasdoingitinperson,butyoucanofcoursedoitusingcollaborativeeditorsas
SubEthaEditinOSX.
upvote3down answeredAug29'08at16:20
vote
share|improvethisanswer
FedericoBuiles
2,18321741
WithiChatforcommunicationaswell.AbizernMar4'09at17:15
addacomment|
I'djustwantedtoaddsomereallynicepluginfortheEclipseIDEitscalledSarosandit'sOSS.Hassomereallybeautifulfeatures!
Ithassomenicefeatures(highlightingsource,builtinVoIP(beta),chatandsomemoretocomesuchasscreensharingandwhiteboardfeatures)...
Findoutaboutitatsarosproject.org
upvote3downvote
editedApr29'14at23:35 answeredMar29'10at13:41
share|improvethisanswer
Josh Gnark
4,84342750 1,45741738
addacomment|
We'veusedwebexforthis.Whileit'snotnecessarilyidealforthiskindofthing,itdoeshavesomefeaturestomediatewhocontrolsthecomputer
andwhen.
upvote2down answeredJul15'09at14:03
vote
share|improvethisanswer
JasonBaker
65.3k72260438
addacomment|
We'vebeenusingthenewECFfeaturesinEclipse3.4(Ganymede)andwelikeit.We'renotactuallyremotefromeachotherexceptwhenoneofusis
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 341/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
workingathomebutECFletsyoueditthesamefileandalsohasanIMwindowforchatting.IfyouuseSkype,somuchthebetter.
upvote1 There'sagoodscreencastonVimeoofthescreensharingthatreallymadeusexcitedaboutit.
downvote
answeredAug29'08at16:22
share|improvethisanswer
MattGrommes
4,31672334
addacomment|
Inmycurrentjob,I'veworkedwithanotherdeveloperwhowasinanotherlocation.Whileweconsultedquiteoftenwitheachotherthroughphonecalls
(headsetsareahugeplus!)andscreensharing,thereal'togetherwork'(includingsomerealpairprogramming)wasmuchmoreeffectivewhenIvisitedhis
location(didthattwiceforawholeweek,andtheseweekswereveryintense).
Themainproblemwithscreensharingisthatyouneverknowwhoisgoingtomovethemouse,...(forexampletopointatsomethingonthescreen).
upvote
1down Onthatproject,weendedupdividingtheworkinto2subprojects,andgottogether(meaning:travelling)toplugthemtogether.
vote
answeredAug29'08at16:24
share|improvethisanswer
OysterD
3,09242129
addacomment|
OnOSX,I'veusedvimandamultiuserGNUscreensessionthisgivesmuchbetterresponsivenessthanVNC,screensharing,etc.Iusethissetupalongwith
Skypeandaheadsetforvoicecommunication.
I'vedonealotofpairingremotelylikethisandIfinditcanworkverywell.However,forittoworkwell,justaswithfacetofacepairing(butprobablymore
upvote so),Ithinkyouneedbothpartiestobewellmotivatedandfamiliarwiththetoolsyouareusing.Also(morethaninthefacetofacescenario)Ithinkthatit
1down helpstogivemoreofarunningcommentaryonwhatyouaredoing.
vote
answeredJan29'09at14:00
share|improvethisanswer
JamesMead
2,6701117
addacomment|
YesIhavedoneremotepairing.
WeusedanoldfashionedspeakerphoneandVNC.WepairedbetweenSeattleandBournemouth,England.ThecrossatlantictimelagmadeVNCvery
difficulttouseit'sdifficultnottointerruptsomebodyelseusingthemousewiththerandomnetworklag.
Youneedalotofpatienceandsomeconventionstakingturns"driving"thekeyboardandmouse.
Weonlydidremotepairingfordevelopmentforshortperiodsoftimesay30minsorsobecausemostpeopledevelopedheadachesquitequickly.It
upvote wassopainfulwiththenetworklags.Wejustkeptforproblemsolvingandwherepeoplegottoapointwhereitwaseasiertoexplainbydemonstrationthanby
1down readingtextonawiki.
vote
Ithinkthesedays,youmightgetabetterresultusingremotedesktopwhichIhavealsousedforpairing.Myremotedesktopremotepairingwasforsupport
anddeploymentthoughanditwasbetweentworemotedevelopersloggingintoamachineatwork.Peopletellmethatremotedesktopismuchmoreefficient
thanVNCintermsofbandwidthbutIcan'tverifythat.
answeredNov8'09at1:26
share|improvethisanswer
daf
5,33012442
addacomment|
thereisaprettygoodlistofeditorswithcollaborativerealtimefeaturesonwikipedia:http://en.wikipedia.org/wiki/Collaborative_real
time_editor#List_of_current_editors
IpersonallytriedEtherpadwhichwaslateracquiredbyGoogleandpartiallyintegratedintoGoogleWave'srealtime"mail"transmission,afeaturesetthatnow
presumablysurvivesinGoogledocs.AnotherverynicewebbasedSolutionisMozilla'sCloudcodeformerlyknownasBespin.Adobealsohasmadeanentrance
intothiswithBuzzWords,thoughnotusedforcoding,hencenosyntaxhighlightingandalike,itdoesworkwithlockingsessionsforonlyoneeditortotake
control.IhadnoluckwiththeEclipseCOLAFramework(ECF)buttheprojectlookedpromisingwhenIlastlookedintoit.SomepeopledosimplyuseGoogle
docs
CompaniessuchasGoogleandAmazonalsocommonlyusethosewebeditorsintheirinterviewprocessforquickpairprogrammingsessionsonsmaller
problems,wheretheintervieweecodesinawebbasedsessionandanInterviewerusestexthighlightingandaliketodrillintospecificsessions,Ihaveseen
interviewersevensimplyeditingthecodealongside.
Otherthansomeofthereportsseenhere,IneverhadcrossAtlanticissueswithdelayandhavedonelonger/intensecodingsessions.Thereisafairamountof
up researchontheinfluenceofjitteranddelayoncollaborativeediting,wherequiteoftenjitterisperceivedasfarmoredisruptiveandconstantdelay,equalacrossall
vote usedtools,appearsassomethinguserscanadoptto:http://scholar.google.com/scholar?q=Jitter+and+Delay+real+time+collab
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 342/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
0 Thoughsittingnexttoeachothermayavoidsomeoftherequiredadaptationstoadifferentstyleofcommunication,therearedistinctadvantagesinusingsoftware
down tocollaborate.Pairingoverasystemallowsfullrecordsofanentiresession,andshoulddetailsworkedoninasessionbecomeunclear(thoughthatshouldperhaps
vote nothappen,itsurelysometimesdoes)youcansimplygothroughtherecordingofthesession.Etherpadhadahandylittlefeaturethatallowsyoutogothrougha
timelineofalleditsandslidebackandfourththroughthesession.
Inmyopinioncodingcollaborativelyshouldnotbeapproachedinthesamewayaspairprogramming,inthatyoushouldtakeadvantageoftheabilitytoedit
concurrently.Pingpongprogrammingbecomesalotmoreinteractivewhentestsareconstantlywritten,eachdevchoosesatwillwhethertowatchtheotherone
liveorwaitandunderstandthefinishedtestinstead.ItallowsforsmalldetourswritingthesameapproachinanA/Bprogrammingfashionwithouthavingtowait
forbothtosequentiallybeimplementedanddiscussed,insteadbothcanbewrittenalongside.
bestregardsGranit
answeredJun18'13at9:54
share|improvethisanswer
DrGranit
15113
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedtddpairprogrammingoraskyourown
question.
asked 6yearsago
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 343/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
viewed 2165times
active 1yearago
Lookingforajob?
PolyglotDeveloper(ruby,javascript,clojure,etc.)
MavenHiveTechnologiesPvt
Bengaluru,India/relocation
rubyonrailsstartup
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
SoftwareDevelopmentEngineerUI
AudienceScience
Pune,India
htmlcss
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Linked
6
HowcanIcodesimultaneouslywithafriendonVisualStudio?
Related
11
PeerReviewsorPairProgramming,orBoth?
4
Adversarial/NaivePairingwithTDD:Howeffectiveisit?
5
Ifyoupairprogram,doyoustillneedapeerreview?
4
Whatispairprogramming?
5
TestDrivenDevelopmentandPairProgramming
21
ToolsforRemotePairProgramming
6
RemotePairProgramminginIntelliJ
1
pairprogrammingandsolodeveloper
0
Whatisanidealpairprogrammingsetup?
3
Whataresomegoodservicesortoolstouseforremotepairprogramming?
HotNetworkQuestions
PythonLabelExpression?ArcGIS10.3.1
MementoVivereMomentumMori
Justifyingsuboptimalresearchqualitybylackofsupervision
IsWolframwrongaboutunique3colorability,oramIjustconfused?
Canmathbesubjective?
ALN*NTicTacToeGame
zero,zerosorzeroes?
DoesCIDRreally"doaway"withIPaddressclasses?
FiveAnglesinaStar
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Ciertasconjugacionesverbalesnoconvencionales
WhycanfunctionallanguagesbedefinedasTuringcomplete?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 344/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
Removestaticobjectsfromanimagesequence
Antiferromagneticordering
HowcanIsecretlynotatewhichsquaresonacombatmaparetraps?
Troublewithterminatinga<apex:pageBlockSection>
Needhelprecreatingcrazycolors/materialfromexample
Howtojustifydiggingclawsandopposablethumbsinthesamebeing
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
LeapyearcheckinJava
IsthereanyadvantagetousingaweatherresistantGFCIinabathroom?
CanIwriteapaperoutofasimpleidea
Paidcashforacar,butdealerwantstochangeprice
What'sthebestwaytoinvestformakingregulardonations?
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography
Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction
Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 1. Mathematics
2. Skeptics 1. StackApps
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 2. CrossValidated
3. MiYodeya 2. MetaStack
4. Web 4. WordPress Answers 4. SeasonedAdvice (stats)
(Judaism) Exchange
Applications Development 3. SharePoint (cooking) 3. Theoretical
4. Travel 3. Area51
5. AskUbuntu 5. Geographic 4. User 5. Home ComputerScience
5. Christianity 4. Stack
6. Webmasters InformationSystems Experience Improvement 4. Physics
6. Arqade(gaming) Overflow
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance 5. MathOverflow
7. Bicycles Careers
Development Engineering 6. Salesforce &Money 6. more(7)
8. Roleplaying
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia
Games
LaTeX 8. InformationSecurity 8. more(10)
9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
currentcommunity
chatblog
StackOverflow
MetaStackOverflow
StackOverflowCareers
yourcommunities
Signuporlogintocustomizeyourlist.
morestackexchangecommunities
StackExchange
signuplogintourhelp
TourStarthereforaquickoverviewofthesite
HelpCenterDetailedanswerstoanyquestionsyoumighthave
MetaDiscusstheworkingsandpoliciesofthissite
stackoverflowcareers
search
StackOverflow
Questions
Tags
Users
Badges
Unanswered
AskQuestion
Takethe2minutetour
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free.
Whichismoresuitable:hashtableorBSTintermsofserialization,
concurrency?
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 345/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
IthinkaHashTablewouldbemoresuitableifwe'redoingcollisionresolutionviachaining,becauseforanyreadorwriteoperationwe'dhavetoacquire
lockonthatentry(index&value)inhashtablewhereaswe'dhavetoacquirelockonentireBSTtomakeanyupdatestoit.
IthinkweneedtotakelockonentireBSTstructure,becauseimaginewe'vetoinsertanewnodeintothetree,wefirsthavetotraversetoreachtheright
parentposition(saynodeA)andifwehaven'tacquiredlockthetreestructuremightchangeandwe'dhavetostartafresh.
Incaseofhashtablestheinputwouldalwayshashtothesamepositionandwe'dknowwhichindextotakelockon,whichisunknownincaseofBST.
upvote4down
votefavorite PleasecorrectmewhereverI'mwrongandhelpmefindtherightanswer.
1
P.S:ThisisanAmazonInterviewQuestion.
serializationconcurrencyhashmapbinarysearchtree
askedFeb21'13at7:46
share|improvethisquestion
studyingalgorithms
97129
HaveyoureadtheresearchpaperforanefficientconcurrentBSTbyBronsonetal.?thitonFeb21'13at8:49
I'llreadthatpaper.ThanksstudyingalgorithmsFeb21'13at19:31
addacomment|
2Answers
activeoldestvotes
Ithinkintermsofconcurrencywhatyouhavesaidiscorrect,andahashtablewillbeabetterchoicebutintermsofserializationIthinkaBSTwillbebetter.
ThisisbecauseinBSTwewillhaveonlydatanodes,howeverinhashtablewewillhavebothkeyandvaluepairsfordata,aswellhavefewkeysforwhich
therewillbenovalue.ThusitwillrequiremorespacewhenserializedascomparedtoBST.
upvote
0down answeredFeb21'13at9:27
vote
share|improvethisanswer
abhinav
657316
addacomment|
Youcandoahybridsolution.Doahashtablewhereeachslotisabinarytree.Sosay1024slots,eachwithabinarytree.Collisionsonthehashgointoabinary
tree,don'tneedtolockeverythingoninsert,justthetreeyouneedtoupdate.
Furtherifyouuseatomicoperationsandsomeclevernessyoucanmakeitevenmoreconcurrentbyavoidinglockingaltogether.Atomicupdatetoinsertthenew
node,ifatomicupdatefailsanotherthreadaddedanode,simplyloopagainuntilyousucceed.
Ihavealreadydonethishttps://github.com/exodist/GSD/tree/master/Structures
Thisisahighlyconcurrenthash/treehybrid.Itusesatomicoperations,nomutexes.Itcanspinoninsert,butneverblocksforreadsorupdatestoexistingkeys.It
canberesized/balanced/etc.Youcantraverseallentries,etc.Managesitsownmemoryandhascallbacksforrefcountingkeys/values.Youcanalso'link'keys
inonedictionarytoanothersothatupdatingakeyinthefirstaltersthevalueofthesecond.
Thisdesignactuallyhasperformanceincreaseswhenyouthrowmorethreadsattheproblem:
(T)ishowmanythreads,ignoreMI,slotsishowmanyhashslotsareused,andOpsishowmanyitemsarebeinginserted(divideitbythreadstoseehowmuch
eachthreaddoes)
./performance.run
T,MI,Slots,Ops:InsertRebalanceUpdateResizeLookupImmute
4,16,1024,5000000:2.7655003630.9152320652.5406594762.1726548132.5454095602.089993698
13.029449975
upvote 4,16,32768,5000000:2.1224598661.4035483092.4134833741.8850839012.0922724662.643681518
0down 12.560529434
vote 4,16,1048576,5000000:1.7009948091.0637040102.0308093672.4572757071.4534139243.671012425
12.377210242
16,16,1024,5000000:0.7856757812.3112819041.8056107530.6215211460.5495464730.744009412
6.817645469
16,16,32768,5000000:0.4973596380.3160175531.2576631420.6107614140.3908493550.825944608
3.898595710
16,16,1048576,5000000:0.3283089890.6476328011.2672306251.1394026930.3423998271.189220470
4.914195405
64,16,1024,5000000:0.1294071320.7672620212.6319290190.1579773130.1038480040.177964574
3.968388063
64,16,32768,5000000:0.0876566060.0683302311.3657948520.1662619660.0791127280.203542885
1.970699268
64,16,1048576,5000000:0.0746056800.2843229791.3729986070.6505033490.0849569380.828653807
3.296041360
Notes:Singlerunonani7with8gbram.Usesgccatomicbuiltins,intheprocessofswitchingfromold__syncto__atomic,whichmayhelpperformancedueto
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 346/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
memorymodels.
answeredNov1'13at0:20
share|improvethisanswer
Exodist
334111
addacomment|
YourAnswer
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingStackExchange
Postasaguest
Name
Email required,butnevershown
PostYourAnswer discard
Bypostingyouranswer,youagreetotheprivacypolicyandtermsofservice.
Nottheansweryou'relookingfor?Browseotherquestionstaggedserializationconcurrencyhashmap
binarysearchtreeoraskyourownquestion.
asked 2yearsago
viewed 179times
active 1yearago
Lookingforajob?
Geek(s)
myglamm.com
Mumbai,India/relocation
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 347/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
javaios
ApplicationDeveloper,Pune
ThoughtWorksTechnologies
Pune,India
java.net
SoftwareEngineer/Sr.SoftwareEngineerJava
SecloreTechnologyPvt
Mumbai,India/relocation
javaj2ee
iOSDeveloper
HelpshiftTechnologies
Pune,India/relocation
iosobjectivec
Related
16
HowtoSerializeBinaryTree
1
Serializationandconcurrency
9
Serializingmapswhichareinitializedinconstructors
6
DoIneedaconcurrenthashmapifeachthreadinsertsuniquekeys?
1
tbbconcurrenthashmaps:howtocompareandset
0
SerializeclasswhichextendsfromHashMapJava
1
SerializeBSTTree
1
Concurrenthashtables
1
HashtableimplementingwithBinarySearchTree
0
ResizingConcurrentHashMap
HotNetworkQuestions
Whatis`$?`?Isitavariable?
Whatistheoriginofthisphotoofanunexplodedbomb?
HowcanIcheckifmyfunctionprint/echo'ssomething?
Nicelytypesettingverbatimtext
CanICultureBombfaraway?
Ciertasconjugacionesverbalesnoconvencionales
40Numbersin9Bytes
NineTallMenAreStandingTall
Drawarrowinamindmap
WhatdoesitmeanifanACmotorhastwovoltageratings?
Papers,please:Cancharacterstrappedinourrealityacquireenoughpaperworktobelegal?
WhycanfunctionallanguagesbedefinedasTuringcomplete?
Paidcashforacar,butdealerwantstochangeprice
Wouldatheoreticaldecisionmakersubscribingtothefollowingprinciplesdecideagainsthumanabortion?
Needtostartareligionwithapredefinedselfdestruct
HowdoIfacilitateafirsttimeAgileretrospective?
ThenthTernary
DoesVoiceoftheChainMasterletmecastapurelyverbalspellthroughmyfamiliar?
Antiferromagneticordering
HowtodealwithaGMwhodoesnottelluseverything?
Whatistheoriginofthepowericon?
CombatingtheDunningKrugerfailuretorecognisegenuineskillinothers?
Functionsthataretheirowninversion.
Derivativeofadefiniteintegralissue
questionfeed
tourhelpblogchatdatalegalprivacypolicyworkhereadvertisinginfomobilecontactusfeedback
Technology Life/Arts Culture/Recreation Science Other
1. English
1. Stack 1. Programmers 1. Photography Language&
Overflow 2. Unix&Linux 1. Database 2. ScienceFiction Usage
2. ServerFault 3. AskDifferent Administrators &Fantasy 2. Skeptics 1. Mathematics
3. SuperUser (Apple) 2. Drupal 3. GraphicDesign 1. StackApps
3. MiYodeya 2. CrossValidated
4. Web 4. WordPress Answers 4. SeasonedAdvice 2. MetaStack
(Judaism) (stats)
Applications Development 3. SharePoint (cooking) Exchange
4. Travel 3. Theoretical
5. AskUbuntu 5. Geographic 4. User 5. Home 3. Area51
5. Christianity ComputerScience
6. Webmasters InformationSystems Experience Improvement 4. Stack
6. Arqade(gaming) 4. Physics
7. Game 6. Electrical 5. Mathematica 6. PersonalFinance Overflow
7. Bicycles 5. MathOverflow
Development Engineering 6. Salesforce &Money Careers
8. Roleplaying 6. more(7)
8. TeX 7. AndroidEnthusiasts 7. more(14) 7. Academia Games
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 348/349
7/13/2015 algorithmAmazon:WatercollectedbetweentowersStackOverflow
LaTeX 8. InformationSecurity 8. more(10) 9. more(21)
sitedesign/logo2015stackexchangeincusercontributionslicensedunderccbysa3.0withattributionrequired
rev2015.7.10.2720
file:///C:/Users/dell/Desktop/New%20folder/merged.htm 349/349