LeetCode Two Sum -JavaScript brute-force and optimized;

Awesome picture of Google. Not really relevant, might be the reason you clicked on this story.
pseudo-code for Brute Force //so out input will be an array of numbers [0,3,5,2,1,4] and our target will be a number between -infinity and +infinity
//we need to add two of our numbers together to reach the target
// we can do with through looping in a forloop, iterating over the entire array.
//because we need to add two numbers, we can use a nested for-loop
//if arr[index1] + arr[index2] = targetNumber, we need to return
[index1, index 2]
function(array, targetNumber){
//check length to make sure it is not less than or equalto 1
if(array.length <=1)return null;
//we will create two loops nested
for(let i = 0; i < array.length; i++){
// we will start our second index at index1 + 1
for(let j = i+1; j < array.length; j++){
//and check if the array values at each index equal the targetNumber
if(array[i]+array[j] === target){
return [i,j]
We have an array of [1,2,3,4,5] and we need to find a pair that equal 8; if we have a 1, we will need a 7, if we have a 2, we will need a 6...if we have a 3, we will need a 5. numberWeWant - numberWeHave = THE NUMBER WE NEED ::party::party::
  • 1x Function
  • 1x Object instantiated
  • 1x For-Loop
  • 1x If Logic
  • 1x Object-Builder
  • 1x Return-er




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Next.JS in React JS

How to establish two-way communication using MessageChannel

How to host a Static Website using AWS S3

Create Angular Dynamic Components— Generic Pattern with Inputs, Outputs & Methods

React: The Shape of State and My Common Mis-states

Speed up your coding using Emmet — a really powerful tool

How to Use Supabase Authentication in a React Application

FabricJS performance hack

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anthony Johnson

Anthony Johnson

More from Medium

Fizzbuzz — An Interview Algorithm Classic

Kth Maximum and Minimum in an Array

Introduction to JavaScript

Two Sum Problem (JavaScript)