Determine all subarrays within two integer arrays whose sum matches a specified target number

Given two integer arrays, find all subarrays whose sum equals a specified target number. For example, if array1 = [1,2,3,4] and array2 = [7,3,4], with the sumToFind being 5, the function findSubArrays(array1, array2, num) should output [[1,4],[2,3]].

I initially approached this problem using a nested loop, resulting in a time complexity of O(N2). Is there a way to optimize this function to achieve an O(N) complexity?


function findSubArray(array1, array2, sumToFind){
  var len1 = array1.length;
  var len2 = array2.length;
  var result=[];
  for(var i=0;i<len1;i++){
     for(var j=0;j<len2;j++){
        if(array1[i] + array2[j] === sumToFind){
            result.push([array1[i], array2[j]]);
        }
    }
  }
  return result;
}

Answer №1

It is uncertain if achieving O(N) is possible, but I have a solution that has a complexity of O(nlgn) (which corresponds to the sort algorithm time complexity).

var findSubArray2 = function(arr1, arr2, sumToFind) {
  var result = [];
  var sortedArr1 = arr1.sort(); // O(nlgn)
  var sortedArr2 = arr2.sort(); // O(mlgm)

  // Using two pointers to iterate through each array.
  // O(n + m)
  for (var i = 0, j = arr2.length - 1; i < arr1.length && j >= 0;) {
    var temp = sortedArr1[i] + sortedArr2[j];
    if (temp > sumToFind) {
      j--;
    } else if (temp < sumToFind) {
      i++;
    } else {
      result.push([sortedArr1[i], sortedArr2[j]]);
      i++;
    }
  }

  return result;
}

Note1: If your array1 and array2 are already sorted arrays, the complexity could be O(m + n).

Note2: It's not clear which algorithm the default sort method uses, but it's unlikely to be O(N2). Refer to this link.

I hope you find this information helpful.

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

What could be causing the "10 $digest error" to appear in my code?

My goal was to create a basic app that could detect the size of the browser and display it. But, I encountered an error message saying "Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!" app.controller('AppCtrl',function($win ...

What is the best approach to transpiling TypeScript aliased paths to JavaScript?

I am currently facing an issue with my TypeScript project where I need to transpile it into executable JavaScript while using path aliases for my NPM package development. One specific scenario involves importing a method from the lib directory without spe ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...

What are the methods for incorporating reflection into three.js?

While working on a WebGL project using Three.js, I am aiming to incorporate a reflective cube surface that mimics the appearance of a mobile phone display. The surface should be able to reflect light while maintaining a black color scheme. ...

Submitting a POST request to paginate and sort the results

Currently, I have a system in place where a GET request is used to query the database and display the results. While this method works well, I am looking to transition it into a POST request. This would allow for a more flexible approach by handling JSON b ...

Retrieving Browser URL using Node.js

Currently, I am trying to extract the browser URL from a user who has integrated my external JavaScript file into their website. The process involves them including the JS file, which triggers an Ajax call using jQuery to communicate with my Node server. ...

What is causing these dynamic carousels to malfunction in Chrome?

After using Agile Carousel successfully for a while, I am now experiencing issues with it not working properly in Safari and Chrome, although it functions fine on Firefox and Safari for iPad. On this specific page, the carousel stops at the second image, ...

Infuse the theme into the sx prop of MUI 5

The code snippet above was originally written using MUI v4: const useStyles = makeStyles(theme => ({ toolbarMargin: { ...theme.mixins.toolbar } })) To update this code to MUI v5 and utilize the sx prop, I attempted the following implementation: ...

The jQuery div enclosure technique

I am trying to wrap HTML around an existing div, here is what I have attempted: HTML: <input type="text" data-placeholder="username" /> It should look like this when rendered: <div class="placeholding-input"> <input type="text" data-pl ...

Execute a JavaScript function daily for each new user

Can someone help me understand how to execute a JavaScript/jQuery function that triggers a PopUp once for each new user visiting a webpage? Below is the code I need assistance with. $(window).load(function() { $('#index9').fadeIn("slow"); ...

Converting JavaScript objects into a JSON string and then into a PHP array via POST

Hello everyone, I could really use some assistance with this issue. I am passing a JSON object to PHP like so: var x = {}; x.xt = {}; x.xt.id = id; x.xt.to = foo; somearray.push(x); To convert the object to JSON: $.toJSON(x); The resulting JSON string ...

Is it possible to set up a server with 'app' as the designated request handler?

When working with NodeJS, server creation can be done simply by using: http.createServer(function(req,res) { /* header etc. */}); However, as I delved into using express, the server was automatically created for me. Moving on to learning about sockets, I ...

Is there a way to dynamically create a Vue component for every tier of a nested JSON object without prior knowledge of the total number of tiers available?

I am working with JSON data that includes a list of retailers, some of which have subretailers that go multiple levels deep. My goal is to use Vue to generate markup that will show the parent retailer along with any nested subretailers underneath it, simi ...

why is my angular listing malfunctioning when I try to compare two fields?

<div ng-controller="SamsungServicesCtrl"> <ion-content> <li class="item item-checkbox" ng-repeat="item in items" > <img src="{{item.icon}}" style="float:left;height:30px;width:30px;padding-right:5px;" & ...

Mastering the Art of Accelerating getJSON Array Data

Currently, I am facing a challenge with retrieving a large array (4MB) of data from the server side. I have been utilizing the jQuery getJSON method to obtain the array data and display it on the browser. However, this process has proven to be quite slow ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

Choose the current parent item using Angular's ng-selected and $index

http://plnkr.co/edit/fwwAd4bn6z2vxVN2FUL7?p=preview On the Plunker page linked above, I am trying to achieve a specific functionality. I would like the 3 dropdown lists to display values A, B, and C initially. When a 4th dropdown option is added, it shoul ...

Refreshing select2 dropdown options dynamically with AJAX updates

I have a select dropdown for locations that is initialized using select2 on page load. I am looking to dynamically update the data in the dropdown at regular intervals using ajax calls. However, when I attempt to update the data in select2, the dropdown ...

What is the best way to add permissions to each role in JavaScript?

I have been attempting to dynamically add data to an HTML table using JavaScript. The data consists of roles and their corresponding permissions, which are retrieved using Laravel's ORM. I have tried utilizing a nested each jQuery function to append t ...

Dynamic filtering with Javascript

I am searching for inspiration on how to create a filter in the left sidebar that dynamically updates the page content when clicked, and if there are subcategories, displays them below the selected filter in the sidebar. I've discovered that AJAX is ...