# LeetCode Two Sum -JavaScript brute-force and optimized;

There are thousands of ways to solve “simple” problems in leet-code; today im going to go over a “brute-force” solution; and after explain the not so intuitive approach, and hopefully give YOU a better understanding how the “not so intuitive” approach works.

‘The ability to speak exactly is intimately related to the ability to know exactly.” — Wendell Berry

Big shout-out to jakesully at leetcode.com/jakesully for coming up with an awesome solution; Awesome picture of Google. Not really relevant, might be the reason you clicked on this story.

So, lets get started.

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

So, what does this tell us? We have an array of integers,and IF two of the elements in our set will equal out to our target value we need to RETURN the indexes corresponding to those numbers.

If you took time to read through the pseudo-code you can see the simplicity in the solution, essentially all we need to do is run through our array a bunch of times until our values match up to equal the target value, at that point we return the value.

But, this is extremely inefficient, its really gross, but its a good starting point.

We will need to loop through our array, there’s no getting around it(if there is a way, please comment below), but, can you think of a way that we would only have to run through it once?

What if we determine what numbers we need to look for by knowing what we already have?

So we are going through this array, if we know what number we are looking for and we know a number that we have, for example;

So we need to figure out a way to keep track of the numbers we have and the number we need; this can be done with an object and a little bit of ingenuity ;

WARNING!!: This code may throw you off if you’re not a mathMagician… I’m funny, I know….

• 1x Function
• 1x Object instantiated
• 1x For-Loop
• 1x If Logic
• 1x Object-Builder
• 1x Return-er

So,

If looks simple enough, and it really is.