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

Ways to import a library in JavaScript/TypeScript on a web browser?

I'm currently working on a project that involves a TypeScript file and an HTML page. Right now, I am loading the necessary libraries for the TypeScript file in the HTML Page using script tags like <script src="https://unpkg.com/<a href="/cd ...

Tips for creating a stylish ReactJs Header component that stays fixed at the top of the page

Having an issue with my Header component - I want it to remain fixed at the top while scrolling down. Here's the current code: I've attempted using "position = fixed", but it caused my header to resize. Then, I tried setting its width to "width ...

What are some tips for managing the hover effect using CSS3?

Here's a demonstration of my current setup. When you hover over the black box, a transition occurs and reveals my tooltip. However, I only want the tooltip to appear when hovering over the black box itself. Currently, the transition also triggers if y ...

Performing a GET call within the configuration settings of AngularJS

I found a similar question here but unfortunately it didn't solve my issue. I am currently using Angular-UI's Google Maps API, which requires configuration as follows: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider ...

steps for including a JS file into Next.js pages

Is it possible to directly import the bootstrap.bundle.js file from the node_modules/bootstrap directory? import "bootstrap/dist/css/bootstrap.rtl.min.css"; function MyApp({ Component, pageProps }) { return ( <> <Script src="node_m ...

Fulfill a pledge after a function has been run five times

I'm struggling to understand why my promise is not working as expected and how to resolve the issue. Here is the code snippet: let count = 0; function onLoad(){ count++ console.log(count); return new Promise((resolve) => { ...

Express & React: Be cautious of client checksum and style while server-side rendering

Recently delving into the world of React server side rendering, I'm currently working on a small demo utilizing technologies such as React, Redux, React Router, and Material UI. The main issue I'm encountering is the following warning. I am uncer ...

I am looking to implement custom styles to a navigation bar element upon clicking it

When I attempted to use useState(false), it ended up applying the styles to all the other elements in the navbar. import React, { useState } from 'react'; import { AiOutlineMenu } from 'react-icons/ai'; import { Navbar, NavContainer, Na ...

Iterate through the array and generate a ListItem component for every element

Currently, I am facing an issue where only the ListSubheader is being displayed in my code. Despite passing an array named tools and trying to loop through it to create ListItem elements based on each item's properties, no buttons are displaying. I su ...

Find the nearest iframe relative to a parent element

I am attempting to find the nearest iframe element to a parent element in order to pinpoint the specific iframe that I want to customize using CSS: <div class ="accroche"> <iframe></iframe> <iframe></iframe> &l ...

Convert the PHP datetime and timezone function to a JavaScript function

I have a helpful function in my solution that I'd like to share: public static function formatTime($time, $timezone) { $timezone = new \DateTimeZone($timezone); $time = $time->setTimezone($timezone); return \Locale::getDefaul ...

Retrieving detailed information from MongoDB in a Node.js environment

I am currently developing a nodejs server using mongoDB. I have some sample data that looks like this: { "_id": ObjectId("555f1c0c7f4b820758b439b0"), "user": "Guest1", "friend": [{ "myfriend": "Guest2", "in ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

The internet explorer browser does not support the keypress event

i have the following code snippet: <input class="any" type="text" id="myId" name="myName" /> this specific input is using a jquery datepicker plugin.. (http://jqueryui.com/datepicker/) Here is my JavaScript for this element: $('#myId'). ...

Prevent a function from executing using ClearTimeout()

Looking for a way to control the progress of my progress bar using two buttons. Here's the code snippet: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0 /jquery.min.js"></scr ...

Implementing Pagination for a JSON Object using Javascript and Jquery

I am looking for the most effective way to implement pagination in my current situation: I am using "$('body').append(htmlText);" to display the items from a JSON object. How can I set up pagination so that each page displays only one item based ...

Drag and Drop in Angular with Dragula - Trigger Confirmation on Drop Event

I need to implement a confirm modal dialog (UI Kit) when an element is dragged into a new bag using angular 1.4.8 and angular-dragula. If the user clicks ok, the process should continue, but if they click NO, the element should return to its original bag. ...

The form features a "Select all" button alongside a series of checkboxes for multiple-choice options

I am facing difficulties trying to get the "Select all" and "Remove all" buttons to function properly within my form. Whenever I remove the "[]" (array) from the name attribute of the checkboxes, the JavaScript code works perfectly fine. However, since I n ...

Utilize a solo input field to upload either a video or image, and showcase a preview of the uploaded content in a

I'm currently working on creating an input field that allows for the upload of both images and videos. Although I am able to successfully upload the files, I'm encountering an error when trying to display a preview. The code snippet below outline ...

Using a JSON key as a parameter in a function

Would it be achievable to specify the key of an object as a function parameter? For instance, if I were to develop a filter function that could sort multiple map markers by marker.element.country or marker.element.population? This approach would allow me ...