Revise and optimize the solution for an algorithm using JavaScript

I recently participated in a technical interview for a software development company. The question presented to me was as follows:

Given an array of numbers (n), find two numbers that sum up to a target number (k) and display them.
Example:

Input: n = [2,6,4,5,7,1], k = 8   
Output: result=(2,6),(7,1)   

Here is the solution I provided:

function findSum(n,k){
    let aux = []
    for (let i = 0; i < n.length; i++) {
        for (let j = i+1; j < n.length; j++) {
            if (n[i] + n[j] == k) {
                aux.push({ first: n[i], second: n[j] })
            }
        }
    }
    return aux;
}

After presenting my solution, they mentioned that it might be possible to solve the problem using some sort of key or mapping. Does anyone know how to achieve this with only one loop?

Answer №1

To efficiently solve a problem like this while maintaining low time complexity, it is essential to have the ability to search through the data structure effectively. Many solutions involve reorganizing the array to optimize searching. Alternatively, using a data structure with fast search capabilities can also be beneficial.

Data structures such as Sets and Maps offer O(1) time complexity for searches, making them ideal choices where efficient searching is crucial for enhanced performance.

In my approach, I utilize a new Map by traversing the array and adding each element as a key while setting the value to represent the frequency of that particular number. I opted for a map over a new Set because I wanted to keep track of the instances of each number as well.

The algorithm involves searching for pairs of numbers that sum up to a given target k, calculated as (k - num). Upon finding a valid pair, both numbers are added to the results data structure, and the value associated with the first number is decremented to indicate its usage.

In terms of time complexity, the solution operates at O(n), with memory complexity being O(2n) due to having separate keys and values stored in the Map.

function pairSums(arr, k){
    const map = new Map
    const matches = []
    for (let num of arr) {
        const search = k - num 
        if (map.get(search) > 0) {
            matches.push([num, k - num])
            map.set(search, map.get(search) - 1)
        } else if (!map.has(num)){
            map.set(num, 1)
        } else {
            map.set(num, map.get(num) + 1)
        }
    }
    return matches
}

console.log(pairSums([2, 6, 6, 6, 2, 4, 4, 4, 5, 7, 1, 4, 2], 8))

Answer №2

Identify a number y from the array and associate it with a specific key Math.max(y, k - y). Proceed to iterate through the entire array, storing each number in a hash table using this designated key. If the key you are about to add already exists in the hash table, compare the stored value with the current number to see if they add up to the desired sum.

function calculateSum(n, k){
  let hashTable = {};
  for(let j = 0; j < n.length; ++j){
    let y = n[j], newKey = Math.max(y, k - y);
    if((newKey in hashTable) && hashTable[newKey] + y == k)
      return [hashTable[newKey], y];
    else hashTable[newKey] = y;
  }
}

Answer №3

When it comes to tasks like this, the level of complexity is entirely up to you. Take a look at the following solution:

const findPairs = (arr, target) => {
    return arr.reduce((pairs, current, index) => pairs.concat(
        arr.slice(index + 1)
            .filter(num => current + num === target)
            .map(num => [current, num])
    ),
    []
);
}

If you input [2, 6, 4, 5, 7, 1] and 8, the output will be [[2, 6], [7, 1]].

Answer №4

According to a source from this website:

  1. Arranging the array in ascending order is the first step.
  2. Start by identifying two index variables for pinning down potential elements within the sorted array. Assign l as the leftmost index: l = 0, and set r to be the rightmost index: r = n.length - 1
  3. Continue iterating while l < r.
    1. If (n[l] + n[r] == k), then return 1
    2. Else if( n[l] + n[r] < k ), increment l++
    3. Or, decrement r--
  4. If no contenders found throughout the whole array - return 0

Answer №5

If you're looking to achieve this, sorting could be the way to go.

var n = [2,6,4,5,7,1];
var k = 8 ;
n.sort();


let start = 0, end = n.length-1;
while(start < n.length && end >= 0) {
    let current_sum = (n[start] + n[end]);
    if(current_sum == k) {
        console.log('Found sum with '+ n[start] +' and '+ n[end]);
        break;
    }
    else if(current_sum > k) {
        end--;
    } else {
        start++;
    }
}
if(start == n.length || end < 0) {
    console.log('Not Found');
}

However, during the process of writing this code, I stumbled upon another approach as well.

const set = new Set([2,6,4,5,7,1]);
var k = 8;
let found = false;
for (let item of set) {
    let another = k - item;
    if(set.has(another)){ 
        console.log('found with '+item +' and ' +another);
        found = true;   
        break;
    }
}
if(!found) {
    console.log('Not found');
}

Answer №6

If all the numbers in the array are non-negative and the target value falls within the JavaScript array limit:

function findSums(arr, target){
    var results = [];
    var hashTable = [];
    arr.forEach(function(num){
      if(num <= target){
        if(hashTable[target - num]){
          results.push([target - num, num]);
        }
        hashTable[num] = true;
      }
    });
    return results;
}

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

A similar strategy could also be implemented using a bitfield or a sparse array of bitfields.

Answer №7

Here is a condensed version that closely resembles @Andrew's solution, but under the assumption that all numbers are greater than 0:

var findPairs = (array, target) => array.reduce((accumulator, number) => 
  (accumulator[number - target]-- ? accumulator.push([number, target - number]) : accumulator[-number] = accumulator[-number] | 0 + 1, accumulator), []);

console.log(JSON.stringify( findPairs([2,6,4,5,7,1], 8) ));

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

Having trouble with the pagination feature while filtering the list on the vue-paginate node

In my current project, I have integrated pagination using the vue-paginate node. Additionally, I have also implemented filtering functionality using vue-pagination, which is working seamlessly. Everything works as expected when I enter a search term that d ...

Guide to incorporating a jade file into a node.js application after executing an Ajax request

While working on my node.js application, I encountered an issue with loading a new HTML file using Ajax on a button click. Despite everything else working perfectly, the new HTML file was not being loaded. This is how I am making the ajax call in my main. ...

Employ Javascript to display a list of all messages sent through Twilio

I'm referencing the Twilio Node.js documentation available at: My goal is to display a list of all messages in the message log for an account. I'm following this example: var accountSid = 'your_sid'; var authToken = "your_auth_token ...

Guide on importing a React.Component from a Content Delivery Network (CDN) and displaying it within a separate React

Note: None of the solutions provided are effective [DO NOT REMOVE THIS NOTE] Here's a simple question for you - I have a project named Project Y, created using the command npx create-react-app react-project. Now, in the App.js file of Project Y, I h ...

Unable to retrieve the parent element using jQuery

I am facing an issue with my html structure that is generated dynamically through a foreach loop. I have attempted to remove the entire <a> element by accessing it from its ACTIVE HYPERLINK. However, all my efforts seem to be in vain as I am unable t ...

In React js, automatically insert a new row into a table once the Dialog window has

I am currently exploring Reactjs and using Material UI Dialog to implement a dialog box for users to input information and interact with a POST API. After the process is completed, the dialog closes but I would like to dynamically display the added informa ...

What causes inability for JavaScript to access a property?

My current coding project involves the usage of typescript decorators in the following way: function logParameter(target: any, key : string, index : number) { var metadataKey = `__log_${key}_parameters`; console.log(target); console.log(metadataKey ...

What could be causing the issue with my validation for alphabetical input?

I am currently working on a registration form that only accepts alphabetical input. However, I am facing an issue where my error message appears regardless of whether I input an alphabetical or special character. According to my understanding, the code sho ...

Utilizing Object-Oriented Programming in jQuery/JavaScript to effectively pass a value out of a function that is compatible across different browsers

While this question may have been asked before, I urgently need a solution for a production environment. I am feeling quite overwhelmed trying to figure out which objects I should create and utilize. function scroll(min, max) { // perform actions } fun ...

Set the style of the mat-select element

I'm having an issue with my select option in Angular Material. The options look fine, but when I select one, the strong tag disappears. Can anyone help me style only that part? Thank you in advance. <mat-select formControlName="projectId" ...

"An error occurred while trying to access the data for a new user on the snapshot object while navigating to the screen. It seems that the object is

When I navigate to the screen, I use componentDidMount to trigger fetchNewUser which is meant to detect a new user and update it if necessary. However, I encounter an issue where on initial navigation to the screen, it returns undefined is not an object ...

What is the best way to manage the browser tab close event specifically in Angular, without it affecting a refresh?

I am trying to delete user cookies when the browser tab is closed. Is this achievable? Can I capture the browser tab close event without affecting refreshing? If I attempt to use beforeunload or unload events, the function gets triggered when the user ref ...

Having Trouble with Your Instafeed Script

I've been working on a project that involves integrating an Instagram feed into a website. However, I'm facing difficulties getting it to function properly. Here's the code that I have implemented. <script type="text/javascript"> ...

What makes it possible for Vue v3 to handle variables that are undefined?

We are in the process of developing a web application that monitors analytical changes and updates them in real time. While this may not be crucial information, we thought it would be worth mentioning. If you visit Vue.js's official website at https: ...

javascript retrieving JSON data through an API request from a redirected URL

I am retrieving JSON data from the Glitch API. Upon opening the link, it redirects to a different domain (the domain was changed from gomix.me to glitch.me) When using Postman for both HTTP requests, I receive identical JSON data. However, there is a d ...

Sending a file stream with specific file name and extension in NodeJS: A comprehensive guide

Currently, I am utilizing nodejs to transmit file streams to express response var fileReadStream = fs.createReadStream(filePath); fileReadStream.pipe(res); However, the issue arises on the front-end where the file is solely downloadable with the "download ...

Dynamic content in a CSS animation that rolls credits as they scroll

Currently, I'm working on creating a credit scrolling effect that pulls data from the JustGiving API to display a list of donors. I have successfully populated the list of donors and connected to the API without any issues. However, the challenge lies ...

Events for focusing and blurring top level windows

I'm encountering an issue with a basic frameset setup <frameset rows="100, 200"> <FRAME name="listener" src="frame1.html"> <FRAME name="content" src="http://www.someexternalurl.com/"> </frameset> Within the listener ...

The controller in ng-controller returns an undefined error when loaded using RequireJs

I have encountered an issue while loading the Angular application using requirejs. The ng-controller written in main.html loads directly but ends up being undefined. app.js define(['sfongApp', 'ng-grid', 'angular-bootstrap'] ...

Are the charts missing from the Django admin interface?

I am working on incorporating charts into my admin view by extending the admin/base.html file. Instead of using libraries like charts.js, I prefer to use a template for displaying the charts. Ideally, I want my view to resemble this example (). You can fin ...