Returning a set of indexes for two elements in an array that combine to equal a specified target sum

For my current project, I've been tasked with writing a function that accepts an array of numbers along with a target number.

The goal is to identify two numbers in the array that can be added together to reach the target value, and then return the indices of these two numbers as a tuplet (index1, index2).

To tackle this challenge, I decided to use a nested for loop to compare each element in the array to every other element. I then included an if statement to pinpoint the indices when the desired sum is achieved.

Unfortunately, it seems like something isn't quite right with my code. It could be an issue with how I am returning the results as a tuplet, or maybe the logic for obtaining the correct indices needs tweaking. Any suggestions, advice, or hints on resolving this puzzle would be greatly appreciated. Thank you!

function twoSum(numbers, target) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = 0; j < numbers.length; j++) {
      if (numbers[i] + numbers[j] === target) {
        return [numbers.indexOf(i), numbers.indexOf(j)];
      }
    }
  }
}

Answer №1

The Array#indexOf() method is used to find the position of a specific value within an array. For example, if we have an array [1,2,3], calling [1,2,3].indexOf(2) will return 1. If the value being searched for is not found in the array, like in [1,2,3].indexOf(0), then it will return -1.

In this scenario, you are interested in retrieving the indices of variables i and j from the array. These values represent the current positions of your counter variables.

function twoSum(numbers, target) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = 0; j < numbers.length; j++) {
      if (numbers[i] + numbers[j] === target) {
        return [i, j];
      }
    }
  }
}

console.log(twoSum([1,2,3,4],5)) // 1+4 = 5 => [0,3]
console.log(twoSum([1,2,3,4],9)) // undefined since there is no solution

Answer №2

After implementing the fix with coordinates [i, j], this algorithm becomes operational. However, it is deemed highly inefficient in its current state. Specifically, when faced with an unsolvable scenario, it undergoes a staggering amount of attempts, totaling pairs.

Instead, consider sorting the array in ascending order. Commence with i=0 and identify the smallest j by scanning from right to left until n[i] + n[j] ≥ target. Progressively increment i while readjusting j to maintain the condition n[i] + n[j] ≥ target. Repeat this process until i intersects with j or exact equivalency is reached. This revised approach significantly reduces the number of pairs needed to be evaluated to approximately L. The cost implication of the sorting operation scales proportionally to L.log(L).

Hence, one strategic approach involves sorting the array and identifying matching value pairs as outlined above. Retrieving the indexes within the original array can be accomplished either through maintaining a duplicate with subsequent use of indexof, or alternatively, by enhancing the array with appended indices for each element and jointly sorting them together.

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

The Impact of Speed and Performance on Generating Multiple HTML Templates using JavaScript Classes

Currently, I am in the process of developing a travel website using Ruby on Rails 4 which heavily relies on Javascript (or Coffeescript) for functionalities such as Google Maps and other APIs. The workflow involves making an initial call to the server, con ...

Ways to programmatically increase the names of variables in JavaScript?

I am currently working on developing a user-friendly recipe app with Node/Express. Users are able to access a 'new recipe' HTML form where they can easily add as many ingredients as they desire by clicking the 'add ingredient' button. U ...

React hooks causing the for loop to only work on the second iteration

I am working on a project where I need to implement tags, similar to what you see on this website. Before adding a tag, I want to ensure that it hasn't already been selected by the user. I have set up a for loop to compare the new tag with the existin ...

Quasar QDrawer module - locking closure

Is there a way to prevent the drawer from closing if the user has unfinished work in it? I want to be able to display a confirmation message, etc... I thought about using something like can-be-closed="canBeClosed", and then I discovered the dial ...

Using JQuery to reveal a hidden child element within a parent element

I'm facing a challenge with displaying nested ul lists on my website. The parent ul is hidden with CSS, causing the child ul to also remain hidden even when I try to display it using jQuery. One approach I've attempted is adding a class to the f ...

Saving JSON data retrieved from the server into an array in Angular 2

Using a nodejs server to retrieve data from an SQL database has been challenging. I attempted to store the data in taches, which is an array of Tache : getTaches(): Observable<Tache[]> { return this.http.get(this.tachesUrl) .map(response => ...

Escaping multiple levels of quotations in a string within HTML documents

Currently, I am developing an application with Java as the backend and AngularJS 1.0 for the frontend. To display data tables, I am utilizing the veasy AngularJS plugin which I have customized extensively for my app. However, I am facing a small issue. I ...

What is the correct way to use "DELETE" and "BACKSPACE" in a condition statement?

Attempting to prevent the deletion of input values when the length is 2 or lower, but my if statement doesn't seem quite right. $(document).ready(function() { $('#mobile').val("09"); // Set initial value to "09" $('#mobile&ap ...

Incorporating multiple true statements into an IF ELSE structure can enhance the decision-making

I'm struggling with getting a true return value for numbers that are integers and have either 4 or 6 digits - no decimals or letters allowed. The issue seems to be the validation of whether it's really a number and if it has a decimal point. Alt ...

Show only the portion of the image where the cursor is currently hovering

Information in advance: You can check out the current code or view the live demo (hover image functionality not included) at . The concept: I would like to have it so that when I hover my cursor (displayed as a black circle) over the image, only the s ...

XMLHttpRequest Failing to Retrieve Data - Error Code 202

Currently, I am immersed in a project that involves using a webservice (specifically, VB.Net and Javascript). While debugging the code, I encountered an issue with the XmlHttpRequest.status returning as 202. Upon comparison with my previous webservice proj ...

What steps should I take to ensure my .js.erb files are compatible with Rails 7?

I have been following a Rails Tutorial on Building a Link Shortener with Rails 6 and Ruby 2.xx to create an app. However, I am using Rails 7.0.4 and Ruby 3.0.0. I encountered an issue with my create.js.erb file not functioning properly. After some research ...

Before installing npm packages, ensure to gracefully stop the process during pre-installation

Is there a way to stop the npm install process conditionally within a preinstall script? At the moment, I have a preinstall script named preinstall.js: if (someCondition) { process.kill(process.ppid, 'SIGKILL'); } The content of my package.js ...

Having trouble scrolling to the top in Flickr Search using AngularJS, the results are restricting my movement

I recently followed a tutorial on creating a Flickr Search App with AngularJS (https://www.youtube.com/watch?v=lvGAgul5QT4). I managed to show the search results on my page, but encountered an issue: I couldn't scroll all the way back up to the search ...

What is the best way to send multiple PHP variables to an ajax function when clicked?

I'm encountering an issue while trying to pass variables to a function in my controller using AJAX. The error message at the bottom of the image is preventing the variables from being passed successfully. My setup involves the use of the CodeIgniter ...

Display tables side by side using Material-UI

Presently, I am utilizing NextJs and MaterialUI to display a table with data fetched from an API created in Strapi. Challenge The current issue lies in using a table component with props that are imported into a page, where the props are mapped to an API ...

Transformed the Next.js Pages Router into an Application Router

Looking to make a change in my API written with Nextjs's Pages Router. Currently, it serves as a proxy for downloads and I am interested in converting it to the App Router method. Does anyone have any guidance on how to go about implementing this? imp ...

Waiting for the result of an AngularJS promise

When I click a button in my AngularJS app, the following code is executed: if (!$scope.isChecked) { $scope.getExistingName($scope.userName).then(function (data) { $scope.userName = data; }); } // Additional processing code foll ...

Tips for gradually increasing numerical values line by line

Plunker. After implementing the Plunker provided above, I noticed that the rowId is increasing with alphabets, as shown below: The component in the Plunker contains buttons labeled with +, ++, and -. When you press the + button, the rowId starts from the ...

Are there npm dependencies missing from the package.json file because of no comments provided?

Are there any ways to add comments to package.json dependencies? We currently have a large package.json file and are struggling to keep track of our dependencies. In other languages (besides JavaScript), it's easy to include comments with the code. H ...