Thereis a moreefficientandmorecomplexanswertothisproblem, which, onceyouunderstand, itreallyopensyoureyestothinkingaboutthesealgorithmsin a differentlightthanjusttryingtobruteforceitintheeasiestwaypossible.
It's alsonottoodifficulttocomeacrossthislessobviousanswer, whichiswhyit's a greatstartingplaceforanyonelookingtolearnmorealgorithms.
Let's gothroughwhatthealgorithmisaskingustodoit, sayingthatgivenanarrayofimagessonumberswewanttoreturntheindicesofthosenumbersinSaudiarraysuchthatthosetwonumbersthatwereturnaddupto a specifictargetnumberwe'reaskingfor.
Buttheproblemis, aswehave a loopinsideofanotherloop, whichmeanswehavetorunthroughthisnumber's arrayonceforeverysinglenumberinsidethenumbersarray, whichmeansit's a big o notationofendsquared, whichisreallybad.
Soessentially, we'rejustrestoringourrayinsideof a hash, whichmeanswecanlookupthenumberinstantlywithouthavingtolookthroughourentirerayeverysingletimetoseeifthenumberexist.
Sonowthatwehave a highlevelunderstandingofthisalgorithm, let's goaheadandimplementthisusingJavascripttogetstartedprogrammingthis, weneedtofirstcreatethatpreviousvalueshashthatwehave.
I'm justgoingtouse a traditionalfor a loopheresowecansaywehave a variable I wewantinitializeaszeroAndthenwhatwewanttodoiswewannasaywhen I islessthanournumbersdotlengthWhatwewanttodoisaddonetoe I everysingletimeandinsideofherewecandoallofthecodeforcheckingourvalues.
Sothefirstthingthatwewanttodoiswewanttogetthevaluethatweneedsowecancreate a variablecalledneededvalue.
Wecantakeourcurrentnumberandwe, ofcourse, justwanttostoretheindexforthatcurrentnumber, whichinourcase, is I makesure I changethistoe I andthatshouldbeeverythingweneedtodotogetthisworking.