What is the best way to identify a trio of items in an array whose combined total matches a specific target sum?

I am currently utilizing three loops to tackle this problem, but the complexity is O(n3). Is there a way to achieve this with a lower complexity level?

Sharing a JS Fiddle code snippet for the three loops approach:

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
var sum = 8;
find(arr, sum);

function find(arr, sum) {
  var found = false;
  for (var x = 0; x < arr.length - 3; x++) {
    for (var y = x + 1; y < arr.length - 2; y++) {
      for (var z = y + 1; z < arr.length; z++) {
        if (arr[x] + arr[y] + arr[z] == sum) {
          found = true;
          break;
        }
      }
    }
  }
  if (found) {
    console.log("found");
  } else {
    console.log("not found");
  }
}

Answer №1

A potential solution involves utilizing a hash table and implementing two loops - one for iterating through the array and another for calculating the sum of two items.

function find(array, sum) {
    var hash = Object.create(null);
    return array.some((v, i, a) => {
        a.slice(0, i).forEach(w => hash[v + w] = true);
        return hash[sum - v];
    });
}

console.log(find([1, 2, 3, 4, 5, 6, 7, 8], 8));
console.log(find([1, 2, 3, 4, 5, 6, 7, 8], 42));

If you prefer a more functional approach using a closure with a Set to handle the sum of two values, the following code snippet can also be effective.

function find(array, sum) {
    return array.some(
        (s => (v, i, a) => a.slice(0, i).reduce((t, w) => t.add(v + w), s).has(sum - v))
        (new Set)
    );
}

console.log(find([1, 2, 3, 4, 5, 6, 7, 8], 8));
console.log(find([1, 2, 3, 4, 5, 6, 7, 8], 42));

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

Best method for converting List of Objects to byte array in c# for efficient serialization and deserialization

Seeking a streamlined and memory-conscious method for serializing/deserializing a list of objects (such as converting List to byte[] and back). Heard about Google's use of Protobuf for this, along with similar ports for c#. Interested in discovering t ...

Using Raycaster in ThreeJS to pick out faces from models loaded with STL Loader

I am currently developing a .stl viewer using Three.js with the objective of selecting and calculating specific areas within the model. To achieve this area calculation, I need the capability to select faces (e.g. change color). Although I came across som ...

Angular authentication function not invoked

I am currently using Angular along with a JWT token for user authentication. However, I have encountered an issue where the login() function assigned to $scope is not being called. Any assistance on this matter would be greatly appreciated. app.js snippe ...

What could be causing my Three.js code to fail during testing?

Recently, I decided to delve into the world of Three.js by following a thorough tutorial. While everything seemed perfectly fine in my code editor of choice (Visual Studio Code 2019), I encountered a frustrating issue when I attempted to run the code and n ...

Error encountered in ASP.NET MVC application when using jQuery POST method: data is null

I am currently utilizing a PartialView and injecting it into a <div> from another PartialView to create a popup modal using the Bootstrap Modal. Although my Bootstrap Modal is displaying correctly, it is not functioning as intended. The following are ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

Error: Module not found - Imported Node Module

I have been struggling to make modifications to an npm package with little success. I have spent hours troubleshooting and would greatly appreciate some guidance. https://www.npmjs.com/package/dxf After forking the package into my Github account, I proce ...

Is there a way to link to mouseover and mouseleave actions while utilizing ng-options?

I am trying to create a directive that will handle the mouseover and mouseleave events for the option elements within this select element: <select class="form-control" custom-directive="" ng-model="vm.selectedPersonalInfo" ng-options="personalInfo as p ...

What could be causing my node-statsd client script to not terminate?

When attempting to log a metric to a StatsD server using the node-statsd library, I encountered an issue where the script did not exit automatically. The code snippet in question is as follows: var StatsD = require('node-statsd').StatsD; var cli ...

Leveraging TypeScript's declaration file

Greetings! I am currently facing an issue while utilizing a declaration file in my TypeScript project. Here is the declaration file that I am working with: // Type definitions for Dropzone 4.3.0 // Project: http://www.dropzonejs.com/ // Definitions ...

Error encountered: `unexpected token within ES6 map() function`

Do you see any issues with this code snippet? render(){ return ( var users= this.state.users.map(user => <li key={user.id}>{user.name}</li> ) <ul>{users}</ul> ) } I am receiving an error mes ...

React does not trigger a re-render when dynamically generated buttons are created

I am encountering an issue with displaying social media buttons on my website. I have implemented a tweet button and a Facebook like button to appear on every page, but they only load correctly on the initial page visit. Upon navigating to another page and ...

The life cycle of the request/response object in Express.js when using callbacks

Feel free to correct me if this question has already been asked. (I've done as much research as I can handle before asking) I'm really trying to wrap my head around the life cycle of request and response objects. Take a look at the following co ...

What are the steps to implement the "render" function from one class into another class within three.js?

As a newcomer to three.js, I have been working on creating a bowling game. However, I am encountering an issue where I need to access a function from my "Application" class within the physics class that I have created. Here is a snippet of the Application ...

Struggling to access data from a multi-dimensional array within a SwiftUI view

I am currently working on a project that involves a UserModel with nested arrays CityModel and TownModel. I believe my model is set up correctly, but I am having trouble with the syntax when referencing the nested arrays. Here is an example of my UserMode ...

How much memory is being used by a loop script?

I have developed a script in both PHP and Javascript that goes through a million iterations, breaking down a string into an array and storing the first element of that array into a new variable. Here is the PHP code: class First { public function Iterate ...

Is it possible to configure npm install to install "bin" executables directly into the local node_modules directory (rather than the .bin directory)?

In my Node project, I am able to package it into a tarball using npm pack, and then install it in another directory for testing purposes. This allows the files specified in the "bin" section of my package.json file to be symlinked correctly into the node_m ...

How to display only a portion of content using UI Bootstrap collapse feature

In my Angular.js application, I currently have a row of buttons that open up new routes to display partial views. Now, I need to modify some of these buttons to trigger a ui.bootstrap Collapse feature with the view inside it. The template code from the ui. ...

JavaScript detecting improper XHTML syntax

Is there an effective method to detect malformed XHTML within a string using JavaScript? Given that my page allows user-generated XHTML (from trusted users) to be inserted into the DOM, I aim to identify unclosed or overly closed tags. If found, I intend ...

Exploring the Power of Elasticsearch with Datatables

I'm attempting to utilize functions from an Elasticsearch instance in conjunction with datatables to exhibit results. Currently, I am only able to display 10 results, regardless of the query used. Even though there are 141,000 results in Elasticsearc ...