Improving Efficiency with Nested Loop Restructuring

Directions

If you have an array of integers, the task is to find the indices of two numbers that add up to a specific target.

There will be exactly one solution for each input, and you cannot use the same element twice.

For Example

Given nums = [2, 7, 11, 15], target = 9,

Since nums[0] + nums[1] = 2 + 7 = 9, you should return [0, 1].

Is there a way to achieve this without using nested for-loops? I want to lower the time complexity.

Sample Code

const twoSum = function(nums, target) {
    for(let i in nums){
      for(let j in nums) {
        if(nums[i] + nums[j] === target && nums[i] != nums[j]) {
            return [i, j];
        }
      }
    }
};

console.log(twoSum([2, 7, 11, 15], 9));

Answer №1

One approach is to store the difference between each element and the target value in an object, with the differences as keys and their corresponding indices as values. This allows for quick lookup without iterating through the entire array. Then, in a separate loop, check if the elements exist in the object - if they do, you have found a pair. To avoid comparing an element with itself, an additional condition is included.

const twoSum = function(nums, target) {  
  const temp = {};
  for(let i=0; i<nums.length; i++) {
    temp[target - nums[i]] = i;
  }

  for(let i=0; i<nums.length-1; i++) {
    if(temp[nums[i]] && temp[nums[i]] !== i) {
      return [i, temp[nums[i]]]
    }
  }
};

console.log(twoSum([2, 11, 7, 17], 9));
console.log(twoSum([1, 3, 4, 2], 6));

Answer №2

Given the nature of this assignment, I will offer some guidance while refraining from revealing a complete resolution:

  • Your existing code involves redundant index checks. Instead of looping over [0,1] and [1,0], where the sums will always be equal since a+b = b+a, consider having your loop for i range from 0 to len-1, and your loop for j range from i+1 to len-1 to avoid duplicates.
  • In your current condition check nums[i] != nums[j], note that it's not specified in the problem that array values can't be identical. Is it conceivable to use values like toSum([1, 4, 4], 8) with 4+4=8? If so, eliminating the nums[i] != nums[j] check could optimize processing time.
  • If the provided array isn't sorted, you may want to introduce a tracking mechanism to keep record of already assessed values and skip reevaluation on subsequent iterations. For instance, if 4 has been compared against all other values without success, encountering 4 later doesn't necessitate reexamination.

Answer №3

To efficiently tackle this issue, you can utilize an algorithm with a time complexity of O(n). The prerequisite for executing this approach is that the array needs to be in sorted order.

let twosum = (arr, x) => {
  let s = 0,
    e = arr.length - 1;
  let loc = [];

  while (s < e) {
    if (arr[s] + arr[e] === x) {
      loc.push([s,e]);
      s++;
      e--;
    } else if (arr[s] + arr[e] < x) {
      s++;
    } else {
      e--;
    }
  }

  return loc;
};

console.log(twosum([1, 2, 3, 4, 5, 7, 8], 9));
console.log(twosum([2, 7, 11, 15], 9));

The step-by-step breakdown of this algorithm:

1.   Set the initial value of 's' to 0.
2.   Set the final value of 'e' to the last index (arr.length - 1).
3.   While 's' is less than 'e' meaning they have not crossed each other yet:
4.   If arr[s] + arr[e] equals x, we have found a match.
4.1. Increment 's' by 1 as there are no possible combinations before the current 's'.
4.2. Decrement 'e' by 1 as there are no possible combinations after the current 'e'.
4.3. Save the indexes where the match was located.
5.   If arr[s] + arr[e] is less than x:
5.1. Increment 's' since there are no possible combinations before the current 's', but the possibility of a match still exists for 'e'.
6.   If arr[s] + arr[e] is greater than x:
6.1. Decrement 'e' as there are no possible combinations after the current 'e', but the possibility of a match still exists for 's'.

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

Implementing a parallax scroll effect using CSS and dynamically updating the background-position value with JavaScript

How can different Y position percentages be dynamically assigned to multiple layered background images in CSS using JavaScript so that they update as the page scrolls? <style> body { background-image: url(img/bg-pattern-01.png), ur ...

Can anyone assist me with this HTML/jQuery code?

Despite my efforts, I've been unable to achieve success. The challenge I'm facing is with duplicating controls for adding images. I have a button and a div where the user can choose an image by clicking the button. The selected image appears in ...

Crosswalk code unable to detect electronic devices

The implementation of a rails application involves the following code snippet: <div id="sourceSelectPanel" style="display:none"> <label for="sourceSelect"& gt;Change video source:& lt;/label> <select id=" ...

Ensure the item chosen is displayed on a single line, not two

I've encountered an issue with my select menu. When I click on it, the options are displayed in a single line. However, upon selecting an item, it appears on two lines - one for the text and another for the icon. How can I ensure that the selection re ...

Why is it that the HttpClient constructor in Angular doesn't require parameters when instantiated through the constructor of another class, but does when instantiated via the 'new' keyword?

I am trying to create a static method for instantiating an object of a class, but I have encountered a problem. import { HttpClient } from '@angular/common/http'; export MyClass { // Case 1 public static init(): MyClass { return this(new ...

Modifying the display toggle functions

How can I toggle between a button and an input type "file" when clicked? I am using jQuery to show and hide elements, but I need help changing back to the button when clicking somewhere else on the page. HTML: Upload<input type="button" id="upload" /& ...

An assortment of the most similar values from a pair of arrays

I am seeking an algorithm optimization for solving a specific problem that may be challenging to explain. My focus is not on speed or performance, but rather on simplicity and readability of the code. I wonder if someone has a more elegant solution than mi ...

What is the precise output of getFloatTimeDomainData function?

I'm puzzled about the return values of getFloatTimeDomainData. The range of possible values and their significance are unclear to me. According to the specs: This method copies the current down-mixed time-domain (waveform) data into a floating-poin ...

Designing the presentation of two overflowing text containers positioned next to each other

Hey there, I'm currently working on styling something that shows both the user's username and the title of an item on the same line, similar to how it's done on GitHub: username / title I want to make sure that if the combined width of the ...

Having trouble selecting the first element with cursor on Jquery TokenInput?

I'm currently using a Bootstrap (v5.1.3) card that features an autocomplete field powered by jQuery's TokenInput. Everything seems to be functioning properly, except for the fact that I'm unable to access the first element of the field usin ...

Troubles encountered when transferring JavaScript data to a PHP webpage using Ajax and jQuery

Greetings everyone After spending a week searching for a solution, I still haven't been able to figure out what's causing the issue. I have experience with jQuery AJAX calls and I am currently working on developing a Wordpress plugin. I am atte ...

JavaScript encoding and decoding challenges

Can anyone help me figure out what's wrong? I'm trying to encode and decode a simple input, but it just doesn't seem to work! Any ideas why? Thanks in advance for your assistance :) ENCODE: function encryption_encode(s, delta) { var te ...

Struggling with jQuery fadeIn and fadeOut in IE8?

I am struggling to understand why my fadeIn, fadeOut, and corner() functions are not working in IE8 on my website at . They were functioning properly before, but now they seem to be broken. Can anyone pinpoint the issue causing this problem? If you click ...

Combining Two DIVS Side by Side

Hey there, I am working on a timeline using two divs within a table cell. My goal is to have these divs overlap instead of appearing one below the other. The position attribute for all the DIVs inside the cell must remain unchanged due to the drag/drop fu ...

retrieving JSON information from a PHP endpoint

My PHP webpage is returning a JSON string. I created a function to retrieve this data and display it on a jQuery Mobile listview. function LoadJsonDataFunction() { $.getJSON("my_web_page.php", function(obj) { $.each(obj, function(key, value){ ...

Switching from a click event to a hover event in JavaScript

I've been experimenting with animating a burger bar on hover and came across an example online that I managed to adapt for mouseenter functionality. However, I'm struggling to make it revert back to the burger bar shape once the mouse leaves on m ...

Standardizing URLs with ExpressJS router

Seeking normalized/canonical URLs for a single page application running on an ExpressJS server. While the SPA is supported by a server-side router, templates can vary slightly for different app URLs. One particular difference is the presence of the <li ...

What are some creative ways to incorporate a MobX store into a utility function?

Exploring the use of a mobx store in a utility function I am faced with a situation where I have a mobx store and a utility function for making an axios call. How can I access the store value within the utility function? // Store example export defaul ...

Use Javascript to dynamically load a PHP file with the include function

I've been searching for a solution to this issue with no luck so far. Spending hours trying to figure it out. On my PHP page, I'm making an SQL call and dynamically building the content. There's a list of items with onClick JavaScript funct ...

Error: Could not locate local grunt on Windows 7 Professional

When attempting to initiate grunt, an error message is displayed: c:\repositories\kunde_1\themes-projekt_1\projekt_1-responsive\source>grunt grunt-cli: The grunt command line interface. (v0.1.13) Fatal error: Unable to find lo ...