DailyCodingChallenge: Discover two elements in an array that add up to a specified value

As someone who is relatively new to coding, I recently signed up for the daily coding problem mailing list and received the following question:

If given a list of numbers and a specific number k, can you determine whether any two numbers from the list add up to k?

After searching on Stack Overflow, I came up with this solution:

function problemOne_Solve()
{
    const k = 17;
    const values = [11, 15, 3, 8, 2];
    for (i=0; i < values.length; i++) {
        if (values.find((sum) => { return k - values[i] === sum })) return true;
    }
    return false;
}

I am curious as to why this solution works. It seems like the fat-arrow function part closes the brackets within the conditional logic of the if statement. However, there are no subsequent brackets after the if statement, which I thought was necessary.

Additionally, I am interested in learning how I could display on the page the pair or pairs that add up to "k," so that I can further enhance my solution. For example, being able to output these pairs directly onto the page.

Answer №1

.find method utilizes a callback function to iterate over each item in an array until a match is found. The first argument passed to the callback is the current item being iterated over. If the callback returns a truthy value for any element, then the .find method will return that specific item.

During the initial iteration where i = 0 and values[i] equals to 11, the calculation

(sum) => { return k-values[i] === sum}
will first check if 17 - 11 === 11, followed by 17 - 11 === 15, and then 17 - 11 = 3, and so on.

This condition typically checks if two numbers in the given array add up to the defined k, however, there are bugs present. For instance, an array with only one element like [1] will compare 1 against itself during the first iteration, resulting in a sum of 2:

function problemOne_Solve() {
    const k = 2;
    const values = [1];
    for (i=0; i < values.length; i++) {
        if ( values.find( (sum) => { return k-values[i] === sum} ) ) return true;
    }
    return false;
}

console.log(problemOne_Solve());

This approach is incorrect. Furthermore, when using the .find method, it may return a found value, which could be 0 when dealing with number arrays, leading to a falsey result. As a result, even if two elements sum up to 0 (such as 0 and 0), it might still return false:

function problemOne_Solve() {
    const k = 0;
    const values = [0, 0];
    for (i=0; i < values.length; i++) {
        if ( values.find( (sum) => { return k-values[i] === sum} ) ) return true;
    }
    return false;
}

console.log(problemOne_Solve());

To achieve both correct results and reduce computational complexity from O(n ^ 2) to O(n), it's recommended to iterate through the array only once. Create an object where the keys represent the numbers being iterated over, and verify if a key corresponding to target - currNum exists during each iteration (where target is the desired sum and currNum is the current number from the array):

function problemOne_Solve() {
  const target = 17;
  const values = [11, 15, 3, 8, 2];
  const obj = {};
  for (const currNum of values) {
    if (obj.hasOwnProperty(target - currNum)) {
      return true;
    }
    obj[currNum] = true;
  }
  return false;
}
console.log(problemOne_Solve());

I was also wondering how I would go about outputting the pair or pairs that sum up to "k," to build further on the solution. I would like to be able to display the pairs on the page, for example.

Instead of immediately returning when a match is found, store the matches in an array and then return that array at the end of the function. Also, instead of setting the object values to true (or false), track the occurrences of each number found so far within the object (and decrement the matching number count when a match is identified):

function problemOne_Solve() {
  const target = 17;
  const values = [11, 15, 3, 8, 2, 17, 0, 0, 17];
  const obj = {};
  const matches = [];
  for (const currNum of values) {
    const otherNum = target - currNum;
    if (obj[otherNum]) {
      obj[otherNum]--;
      matches.push([currNum, otherNum]);
    }
    obj[currNum] = (obj[currNum] || 0) + 1;
  }
  return matches;
}
console.log(problemOne_Solve());

And there is no such brackets after the if statement, which I thought was required.

When there's a single statement following an if (or else if or else) condition, enclosing brackets are not mandatory, for example:

if (true) console.log('true');
else console.log('this will not log');

Answer №2

There are no brackets following the if statement, which I believed was necessary.

If there is only one statement after the if or else condition, the brackets are considered optional. It's best practice to avoid writing the code block on a single line for better readability.

For beginners, it is recommended to use simple for loops instead of complex methods like find.

You can achieve this by following these steps:

  • You need to calculate the sum of each element with every other element in the array using a nested loop structure.
  • The main loop starts from index zero and continues till the end of the array.
  • Create an inner loop starting from the index after the current index.
  • In each iteration of the inner loop, check if the sum of two elements equals the required sum.

function pairWithSum(givenArray, requiredSum){
  for(let i = 0; i < givenArray.length; i++){
    for(let j = i + 1; j < givenArray.length; j++){
      let sum = givenArray[i] + givenArray[j];
      if(sum === requiredSum){
        return [givenArray[i], givenArray[j]];
      }
    }
  }
  return false
}

console.log(pairWithSum([1, 4, 5, 8], 12));
console.log(pairWithSum([1, 4, 5, 8], 15));

Answer №3

I'm really curious about why this is effective

This works because the if statement requires an expression or statement to evaluate.

values.find( (sum) => { return k-values[i] === sum} ) 

It's important to note that this is a statement that will be assessed beforehand, and its result will be checked by the if condition.

When using Array.find, it returns either type T or null, where T represents any value in the array. So in the second iteration, when values[i] equals 15, it will output 2.

In JavaScript, 2 is considered truthy, causing it to enter the if block. For further information, please refer to All falsey values in JavaScript. Any value not on this list is deemed true.

Answer №4

In my approach to solving this problem using JavaScript, I utilized an object to store elements as we iterate through the array. This method may consume more memory due to storing elements, but it ensures that the time complexity remains at O(n).

function checkTwoSum(arr, sum) {
  const obj = {};
  const foundElement = arr?.find(item => {
    const target = sum - item;
    if (obj[target]) return true;
    else {
        obj[item] = 1;
    }
  });

  return !!(foundElement || foundElement === 0);
}

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

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

Is it possible to invoke a Javascript function from a coffeescript file?

Struggling to invoke a javascript function from a Coffeescript file within my $(document).ready(), but it seems like the function is not being executed. The function I intend to call originates from an external source that I have included in the head sect ...

SonarLint versus SonarTS: A Comparison of Code Quality Tools

I'm feeling pretty lost when it comes to understanding the difference between SonarLint and SonarTS. I've been using SonarLint in Visual Studio, but now my client wants me to switch to the SonarTS plugin. SonarLint is for analyzing overall pr ...

Solving problems with Vue.js by effectively managing array content and reactivity issues

In the past, it was considered a bad practice to use the following code snippet: array = []; This was because if the array was referenced elsewhere, that reference wouldn't be updated correctly. The recommended approach back then was to use array.le ...

Establishing Redux States within the Provider (error: Provider encountering useMemo issue)

Exploring redux for state management has been a new journey for me. I am hoping it will help reduce API calls and increase speed, but I've hit a roadblock with an error that I can't seem to figure out. To troubleshoot, I created a simplified vers ...

What is the method for transferring the value of a jQuery variable to a PHP variable without using AJAX?

Here is my JavaScript code: $('#affiliates_name').change(function(){ var id = $('#affiliates_name').val(); }); Below is the corresponding HTML: <select id="affiliates_name" style="display: none;" name="affiliates_name"> < ...

What steps can I take to rearrange my return statement within an asynchronous function?

Imagine having a function that fetches data from a database. findById(id) { return Model.findById(id) } The goal is to rearrange the output from the user data in this format: { name: "Tom", age: 57 } To something like this: { message: ...

Developing a dynamic horizontal bar chart in d3 using a multidimensional array or nested JSON dataset

I am in the process of creating a straightforward d3 bar chart () by utilizing this specific nested json file. { "clustername": "cluster1", "children": [ { "neighborhoodname": "Shaw", "children": [ { "totpop2000": "1005", "children": [ ...

Using jQuery to handle events across multiple elements

Could I achieve something similar to this? I currently have several variables assigned to DOM elements. Rather than querying the DOM again to set event handlers, I would like to utilize the variables I already have. var a = $("#foo"); var b = $("#bar"); ...

How can one properly iterate through an HTML Collection in JavaScript?

I need help with creating a slider using JavaScript. The code I have written below calculates the widths of the slides, but it's throwing an error in the console. Can someone advise on how to properly loop through and assign width to these elements? ...

Expanding interfaces dynamically in Typescript

Currently, I am facing a challenge while attempting to integrate an existing React Native module equipped with the following props: useComponent1: boolean useComponent2: boolean This is how the implementation looks like: render(){ if(useComponent1){ ...

What is causing this particular area to remain unaffected by the blur effect?

issue I followed a tutorial to create a mouse trailer from this video - https://www.youtube.com/watch?v=kySGqoU7X-s. However, when I tried adding text and other elements inside a div, the blur effect just didn't show up. I attempted using z-index but ...

What is the process for reversing the texture application direction on a CylinderGeometry object?

Is it possible to reverse the orientation of texture mapping on a CylinderGeometry object? var obj = new THREE.Mesh( new THREE.CylinderGeometry(20, 15, 1, 20), new THREE.MeshLambertMaterial({color: 0x000000}) //the material is later changed to the ...

I am currently seeking a way to validate if a variable corresponds to the choice made in the dropdown menu. Any suggestions on how to accomplish this task?

I have put together a simple drop down menu. My goal is to grab the currently selected value from the drop down list, store it in a variable, and display it in the console. The ultimate objective is to compare that variable with another one to determine if ...

Rails assets folder is not directed to the specified directory in the layout file

I have a dilemma in the application layout where I'm referencing assets (js, css, and img) in the public/assets/... directory. For example: <link href='assets/images/meta_icons/apple-touch-icon-144x144.png' rel='apple-touch-icon-pre ...

How can I add content using HTML or JavaScript?

How can I append a .txt file using HTML or Java without ActiveX prompts getting in the way? It's becoming quite annoying! Is there a simple way to script this task without having to deal with ActiveX? The current script snippet looks something like ...

Loading only specific HTML list elements in segments

Within my Angular4 application, I am faced with a challenge involving a large list of li elements. The browser struggles to handle the thousands of li's being displayed when the user interacts with the ul element. This results in slow loading times an ...

The functions.php file is failing to execute the JavaScript files located in the js folder

I've been attempting to incorporate a JS accordion into my Wordpress blog, but I seem to be encountering issues with the accordion.js file not loading through the functions.php file. Interestingly enough, when I manually add the js code in the header ...

"Encountering issues with createReadStream function when handling large files, performance is significantly

Currently, I am utilizing the DropBox API for file uploads. The process involves several steps: Begin by uploading the file from a form to a local directory on the server. Read the file from the local directory using fs.createReadStream. Transfer the fil ...

What are the implications of incorporating listeners in redux action creators?

While developing my app, I have a feature that involves constantly monitoring location changes and updating the store accordingly. One question that has arisen is whether it would be beneficial to keep the listeners inside the action creator rather than th ...