Google Interview Challenge: Finding Pairs that Sum Up

My approach to solving this problem involved iterating through the array and checking if there exists an item such that the sum equals array[i] + item. If such a pair is found, I return true; otherwise, I return false.

Now, my main inquiry is: How can I modify the code to return not just true, but also the indices of the numbers that add up to the given sum? Can this be accomplished within the same code snippet provided below?

function hasPairsWithSum(array,sum) {
  for (let i = 0; i < array.length; i++) {
    if (array.find((item) => {return sum === array[i] + item}
    ));
    return true;
  };
  return false;
};
console.log(hasPairsWithSum([1,2,4,4],8))

Please note that the time complexity needs to be less than O(n ^ 2).

Answer №1

Solving the Pair Sum Problem in JavaScript with O(n) Time Complexity.

function findPairsWithSum(arr, targetSum) {
  const numMap = new Map();
  
  for(let j = 0; j < arr.length; j++) {
    let currentNum = arr[j];
    
    if (numMap.has(currentNum)) {
      return [numMap.get(currentNum), j];
    }
    
    let difference = targetSum - currentNum;
    numMap.set(difference, j);
  }
};

console.log(findPairsWithSum([2, 2, 4, 4], 8));

Answer №2

Kindly review the following code snippet.

function findPairsWithSum(array,sum) {
    let result = [];
  for (let i = 0; i < array.length; i++) {
    if (array.some((item, index) => {return i === index ? false : sum === array[i] + item}))
        result.push(i);
  };
  return result;
};
console.log(findPairsWithSum([1,2,4,4],8))
console.log(findPairsWithSum([3,2,4],6))
console.log(findPairsWithSum([0,4,3,0],0))

Answer №3

O(n) Solution ... utilizing the mathematical concept a+b = n, where if a is present in our array then we need to determine if b = n - a is also present or not.

def hasPairsWithSum(array,sum):
    d = {} 
    for i in range(len(array)):
        if(array[i] in d):
            d[array[i]].append(i)
        else:
            d[array[i]] = [i]
    ans  = []
    for i in range(len(array)):
        val = sum - array[i]
        if(val in d):
            if(d[val][0] == i):
                if(len(d[val])  > 1):
                    ans.append((i,d[val][1]))
                    break
                else:
                    continue
            else:
                ans.append((i,d[val][0]))
                break
    return ans
print(hasPairsWithSum([4, 4, 4, 4], 8))

O(nlogn) solution ... by storing indexes with elements and sorting them by their values, followed by running a loop using the Two Pointers concept.

def hasPairsWithSum(array,sum):
    arr = []
    for i in range(len(array)):
        arr.append((array[i],i))
    arr.sort()
    i = 0
    j = len(array)-1
    ans = []
    while(i<j):
        tmp_sum = arr[i][0] + arr[j][0]
        if(tmp_sum == sum):
            ans.append((arr[i][1] , arr[j][1]))
            #add your logic if you want to find all possible indexes instead of break
            break
        elif(tmp_sum < sum):
            i = i + 1
        elif(tmp_sum > sum):
            j = j - 1
    return ans
print(hasPairsWithSum([1,2,4,4],8))
  • Note: If you aim to find all possible solutions, these approaches may not suffice. You can either add your own logic in the while loop or consider using binary search with traversal on every element and storing the indexes in a set (which could lead to worst-case scenario of O(n^2) as all possible values need to be found). For example, with input [4,4,4,4,4,4] and sum = 8, trying to print all possible indexes will require running it up to n^2 (why? Reason being total possible solutions are 5+4+3+2+1 = n*(n-1)/2 ≈ n^2).

Answer №4

To find the indexes of elements in an array that add up to a specified sum, you can iterate through each element and compare it with the rest of the elements in the array like this:

function findIndexes(array, sum) {
    const result = [];

    for (let i = 0; i < array.length -1; ++i) {
        for (let j = i + 1; j < array.length; ++j) {
            if ((array[i] + array[j]) === sum)  {
                result.push([i, j]);
            }
        }
    }

    return result;
}

console.log(findIndexes([1, 2, 4, 4], 8));
console.log(findIndexes([3, 2, 4], 6));

Update:

Another approach to achieve linear O(n) complexity is by using a Map structure to store indexes of elements equal to the target sum like below:

function findIndexes(array, sum) {
    const map = new Map();
    const result = [];

    for (let i = 0; i < array.length; ++i) {
        const a = array[i];
        const b = sum - a;
        
        if (map.has(b)) {
            for (const index of map.get(b)) {
                result.push([index, i]);
            }
        }
        
        const l = map.has(a) ? map.get(a) : [];
        l.push(i);
        map.set(a, l);      
    }

    return result;
}


console.log(findIndexes([1, 2, 4, 4], 8));
console.log(findIndexes([3, 2, 4], 6));
console.log(findIndexes([1, 1, 1], 2));

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

Looping through a JSON array

Currently, I am working with asp.net in Visual Studio and using jQuery to call a web method. In asp.net, I am generating a dynamic datatable and then returning it by using JsonConvert.SerializeObject(dt). $.ajax({ type: 'POST', url: &apo ...

Create a new JSON file to preserve the value of a JSON object

I am working with a JSON file that looks like this: { "soils": [{ "mukey": "658854", "mukeyName": "Meggett-Kenansville-Garcon-Eunola-Blanton-Bigbee (s1517)", "sl_source": "Fl soil map", "cokey": "3035468", "soilName": "Eunola", " ...

What is the correct way to change the v-model value of a child component within a parent component

Currently, I am in the process of mastering Vue.js and I have a specific goal. I want to modify the binding value of the child component's v-model and then trigger an event in the parent component. As I delve into the Element UI documentation, I aim ...

What is the best way to retrieve values from a nested array?

I am currently working on extracting data from an Array that originates from an RSS feed, which I have converted into a json format. The structure of the array is as follows: <channel> <item> <title> Title A </title> <de ...

Ways to eliminate existing information when conducting a search

Recently, I was tasked with integrating a search engine into a website that already has a list of data displayed on the first page. The challenge I faced was figuring out how to hide or remove this existing data when a new search request is made. You can v ...

Tips for confirming schedule accuracy

Trying to determine if a specific time falls between two others is the task at hand. Allow me to illustrate: Presently, it's Thursday, and the time reads 11:39 PM. Establishment X operates from 12:00 AM to 11:59 PM on Thursdays (a regular occurrence ...

Tips for locating and substituting a string in Javascript

Is there a way to locate a particular word within a string and substitute it using JavaScript? For instance Here is a lengthy sentence I want to locate the word "sentence" and modify it to "phrase", resulting in: Here is a lengthy phrase ...

Two separate ajax functions executed sequentially both yield identical results

I am encountering a strange issue with 2 different ajax functions being called consecutively. Each function fetches a different value and populates different text boxes, but they both return the value of the first function called. Here is the code snippet ...

verified firebase/firestore requests

I've been struggling with the process of sending authenticated firebase/firestore calls. I set up firestore in my web app using Next.js as shown below: import { initializeApp } from "firebase/app"; import { getFirestore } from 'firebase ...

How to pass an item as a parameter to a computed property in Vue.js, and have it return a sorted child array within a

After spending some time searching on Google, I am still struggling to find a solution for this issue. I have a list of "Intents" that contain nested lists of "Entities" created using v-for loops. The Intents are already computed, but now I need to dynam ...

CrossBrowser - Obtain CSS color information

I'm attempting to retrieve the background color of an element: var bgcolor = $('.myclass').first().css('background-color') and then convert it to hex function rgbhex(color) { return "#" + $.map(color.match(/\b(\d+ ...

Is AngularJS known for its ability to bind variables across different components effortlessly

In the beginning of my Angular controller, I use Promises to download JSON data and then store it in variables: app.controller('mainController', ['$scope', '$http', '$q', function($scope, $http, $q) { var req1 = $ ...

Is it possible to change %20 in a URL to a hyphen?

Is there a way for my search form to display %20 in the URL when I fill the input field with spaces? For example: Basketball coach Current output: basketball%20coach Desired output: basketball-coach <form action="/tag/" id="form-hockey_v1" name=" ...

I am experiencing an issue with my service provider when it comes to displaying multiple navigator stacks

Currently, I am developing a provider to manage the user's state across different views. The primary function of this provider is to display either one stack navigator or another based on whether a certain variable is filled or empty. This setup allow ...

Is there a way to reset useQuery cache from a different component?

I am facing an issue with my parent component attempting to invalidate the query cache of a child component: const Child = () => { const { data } = useQuery('queryKey', () => fetch('something')) return <Text>{data}& ...

Fetch data dynamically with jQuery AJAX

I am working on a jQuery Ajax form submission to a PHP page with the goal of dynamically returning values instead of all at once. For instance, in my jQuery code: jQuery.ajax({ type: "POST", url: "$PathToActions/Accounts.php", dataType: ...

Can you provide instructions on how to display data in two lines within a mat-select field?

Is it possible to show selected options in mat-select with long strings in two lines within the same dropdown? Currently, the string appears incomplete. You can see an example of this issue here: incomplete string example <mat-form-field class="f ...

What is the best way to determine the operational schedule of online stores that have varying business days?

Struggling to automatically calculate the working days for various online stores that operate on different schedules. The challenge lies in some of these stores being open on weekends. It's important to note that JavaScript starts counting days of the ...

Can you rely on a specific order when gathering reactions in a discord.js bot?

Imagine a scenario where a bot is collecting reactions to represent event registrations. To prevent any potential race conditions, I have secured the underlying data structure with a mutex. However, the issue of priority still remains unresolved as user # ...

The issue with Array.prototype.join in Internet Explorer 8

In my current working scenario, I encountered an issue with the following code snippet. It performs well in the latest versions of Internet Explorer (IE), but the join function fails to work correctly in IE 8 Version. <!DOCTYPE html> <html xmlns= ...