JavaScript implementation of the 2-sum algorithm solution

Attempting to tackle the 2-Sum problem with a simple Javascript solution. The challenge involves finding pairs of integers in an array that add up to a specific target sum.

After reviewing several language-agnostic examples utilizing hash tables, I set out to create my own Javascript implementation:

// Integer set:
arr = [1,4,2,3,0,5];
// Target sum:
arg = 7;

// Generate hash table
hashTable = {};
arr.forEach(function(value, index){ 
  hashTable[value] = index;
});

// hashTable = {
//   0: 4,
//   1: 0,
//   2: 2,
//   3: 3,
//   4: 1,
//   5: 5,
// }


for (var i = 0; i < arr.length; i++) {
  if (hashTable[arg - arr[i]]) {
      console.log([hashTable[arg - arr[i]], i])
  }
}

Expecting the pairs 4,3 and 5,2 but getting 3,1 5,2 1,3 and 2,5. While trying to pinpoint the error by manually tracing through the logic, it is evident that something isn't aligned with the referenced language-agnostic solutions found online (here and here). Seeking assistance to identify and rectify the discrepancy.

Answer №1

You are currently outputting the indices of summands, but you actually need their values:

 console.log([hashTable[arg - arr[i]], i])

This is why you are seeing these values:

  • 3, 1; indicating that the item at index 3 + the item at index 1 = 7
  • 5, 2; indicating that the item at index 5 + the item at index 2 = 7 and so on.

Try modifying the i in the output to arr[i], and changing hashTable[arg - arr[i]] to arr[hashTable[arg - arr[i]] – this should resolve the issue:

// Integer set:
var arr = [1,4,2,3,0,5];
// Target sum:
var arg = 7;

// Generate hash table
var hashTable = {};
arr.forEach(function(value, index){ 
  hashTable[value] = index;
});


for (var i = 0; i < arr.length; i++) {
  if (hashTable[arg - arr[i]]) {
      console.log([arr[hashTable[arg - arr[i]]], arr[i]]);
  }
}

Please note, you may see symmetric results such as 4 + 3 = 7 and 3 + 4 = 7.
For optimization, consider checking while inserting:

var arr = [1, 4, 2, 3, 0, 5];
var arg = 7;

var hashtable = {};
arr.forEach(function(x) { 
  hashtable[x] = true;
  if (hashtable[arg - x]) 
    console.log([arg - x, x]); 
})

Answer №2

function findPairs(arr, target){
var hashmap = {};
for (var j = 0; j < arr.length; j++) {
    if (hashmap[arr[j]] !== undefined) {
        console.log(arr[j], target - arr[j]);
    }
    hashmap[target - arr[j]] = j;
  }
 }

Answer №3

Give this a try:

function findPairsThatAddUpToSum(arr, sum){
  var firstArray = arr.slice(), secondArray = arr.slice(), length = firstArray.length, pairs = [];
  for(var i=0, x; i<length; i++){
    x = firstArray[i];
    for(var j=1, y; j<length; j++){
      y = secondArray[j];
      if(x + y === sum){
        pairs.push([x, y]);
      }
    }
  }
  return pairs;
}
console.log(findPairsThatAddUpToSum([1,4,2,3,0,5], 7));

Answer №4

This function is effectively solving various scenarios.

   const findSumIndices = (arr, target) => { 
        let numObject = {};
        arr.forEach((val, idx) => numObject[val] = idx);
        for (let i = 0; i < arr.length; i++) {
            let difference = target - arr[i];
            if (numObject.hasOwnProperty(difference) && numObject[difference] !== i) {
                return [i, numObject[difference]];
            }
        }
    }

Answer №5

const numbers = [2, 4, 6, 8, 10];
let targetSum = 16;
let indices = [];
function findTargetSum(numbers, targetSum) {
    for (let i = 0; i < numbers.length; i++) {
        for (let j = i+1; j < numbers.length; j++) {
            if (numbers[i] + numbers[j] == targetSum) {
               indices.push(i,j);
               return indices;
            }

        }
    }
}
let finalResult = findTargetSum(numbers, targetSum);
console.log(finalResult);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am looking to upload a text file into a Javascript program in order to display the data from the file in a table format

As I venture into the world of programming, a new assignment has come my way. I have been given this txt file: nombre="Mario"; apellido="Atencio"; cedula="8-782-2289"; telefono="233-7867"; correo="<a href="/c ...

"Enhance Your Website with jQuery: Organized Lists with Fixed Length, Connected,

I currently have a list that is separated into three columns, structured as follows: Column1 Column2 Column3 1 4 7 2 5 8 3 6 9 The list ranges from 1 to 9 and each column consists of a fixed number of rows (3). I am lo ...

"Utilizing the splice method to insert an element at specified indexes within an

const list = [] const obj = { name: '', mobile: '' } _.forEach(errors, (value, key) => { // eslint-disable-next-line no-debugger // debugger const field = key. ...

Error encountered in Google's Structured Data Testing Tool

<script type="application/ld+json"> {"@context" : "http://schema.org", "@type" : "LocalBusiness", "name" : "mywebsite.com", "description": "Lorem ipsum dolor sit amet", "image" : "http://mywebsite.com/image.jpg", "telephone" : "987654321", ...

Is it possible to use an image loaded as a texture to create another texture mipmap in three.js?

This is not a problem, it's simply a question. Currently, I am working on a terrain project using an atlas texture. In order to reduce color bleeding, I am planning to create mipmaps externally and then apply them to the terrain texture. At the mome ...

Steps to retrieve a file following an AJAX request

Is it possible to automatically download a file following an AJAX call? Currently, when I make the AJAX request, it redirects me to the resource instead of initiating the file download. This is the AJAX function I am using: $('.download').click ...

What is the best way to store a user input value into an array by utilizing a JTextField in Java for each input

I'm working on a program that allows users to add names into a text field. I've created an array called String[] studentNames;. However, when the user hits submit, the name is added to the array as a whole. Is there a way for each new text entry ...

Creating a dynamic feature to add a row at the bottom of a table

I am currently working with JavaScript in the context of an AngularJS application, attempting to insert a row at the bottom of a table that shows the total sum of a specific column. Here is the code snippet I am using: var table = document.querySelecto ...

Rotating the model from its center after panning the model

Hey there! I've been tinkering around with Three.js and loading JSON models using JSONLoader. I also have TrackballControls.js set up for some basic interaction. However, I've noticed that the rotation behaves differently after moving (PAN) the o ...

Video demo: Issue with Bootstrap navigation bar expansion being truncated

When developing my React app, I installed the latest Bootstrap using npm by running: npm install bootstrap followed by: npm install bootstrap jquery and then: npm install jquery popper.js Initially, my Navbar functioned perfectly when the window was wid ...

What is the process for displaying distinct icons for Google Map markers?

In my project, I am trying to display different marker icons on Google Maps. Below is the code snippet that I have used for this purpose. The markers array contains various types of markers with custom icons that I want to show on the map. You can view the ...

obtaining pictures from information obtained in vuejs

Trying to showcase images in my code that are already stored in my data like this: <div > <tr v-for='(ships,index) in destroyedShipBox' :key='index'> <td>{{ships}}</td> ...

Unable to fetch new data from props after making an AJAX call in React

Looking for a function that can send data to the server. addRemark(id,e) { var remarktext = this.state.popUpText; this.props.addRemark(id,remarktext); // this function sends data to the server this.props.closePopUp(); setTimeout(function() { this ...

Discovering the most frequently occurring sequence of symbols within a collection of lists is my ultimate goal

I need to identify the most frequent sequence of symbols from the set of [lists] CATEGORIES = [...list of categories...] Problem with iteration is here: print(compare_bitwise(i, i+=1)) I have provided an example of data only in the initial list, as all ot ...

Tips for utilizing innerHeight for a div during both window loading and resizing tasks?

I'm currently working on calculating the top/bottom padding of a div (.content) based on its height, and updating it upon loading and resizing the window. The goal is to have it centered nicely next to another div (.character) positioned beside it. I ...

Recalling a hidden div in a flexbox arrangement

I am facing a challenge with hiding and displaying two aside divs to enable a fullscreen view of my central div main. The layout is created using flexbox to assign proportions, but when I try to redisplay the elements, it disrupts the original design. Belo ...

Creating a component that responds to changes in the state data

In my Vue application, I have the following layout: App.vue <template> <div id="app"> <Progress /> <router-view /> <Footer /> </div> </template> <script> import Footer from "@/components/Fo ...

Evaluating Vue.js Watchers using Jasmine

I want to write a test for a VueJS watcher method, in order to verify if it's being called. The watcher method in my component is structured like this: watch: { value: (newValue, oldValue) => { if (newValue.Status === 'Completed') ...

Browser-based Javascript code execution

I've been pondering this question for a while now, and I can't seem to shake it off. I'm curious about how JavaScript is actually processed and executed in a web browser, especially during event handling scenarios. For instance, if there are ...

Exploring the world of Django: Using model formsets with the power

I am struggling to use Ajax for submitting my zipped formsets. The code functions flawlessly without Ajax, but as soon as I try to incorporate Ajax, I encounter a ValidationError: [u'ManagementForm data is missing or has been tampered with'] Thi ...