Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Triplets summing up to a target value

/*
  This implementation demonstrates how to
  find all triplets in an array that sum 
  up to some target value. 

  Let n be the size of the input array.

  Time complexity: O(n^2)
  Space complexity: O(n)
*/

function tripletsSum(arr, targetSum) {
  // Sort elements in ascending order
  arr.sort((a, b) => a - b);
  const triplets = [];
  // Find the triplets by scanning through array
  for (let idx = 0; idx < arr.length; idx++) {
    let left = idx + 1;
    let right = arr.length - 1;
    // Find two elements that equals
    // target minus the one at idx
    while (left < right) {
      const currentSum = arr[idx] + arr[left] + arr[right];
      if (currentSum === targetSum) {
        triplets.push([arr[idx], arr[left], arr[right]]);
        left++;
        right--;
      } else if (currentSum < targetSum) {
        // Look for a larger left value
        left++;
      } else {
        // Look for a smaller right value
        right--;
      }
    }
  }
  return triplets;
}

const arr = [12, 3, 1, 2, -6, 5, -8, 6];
const targetSum = 0;
// Below outputs:[ [ -8, 2, 6 ], [ -8, 3, 5 ], [ -6, 1, 5 ] ]
console.log(tripletsSum(arr, targetSum));
Comment

PREVIOUS NEXT
Code Example
Javascript :: onload multiple functions 
Javascript :: how to cheack if a number is an integer or float in javascript 
Javascript :: mongodb filter empty array 
Javascript :: js string startswith ignore case 
Javascript :: connecting mongoose with express js 
Javascript :: get element by tag name 
Javascript :: getkey by value js 
Javascript :: nodejs recursively read directory 
Javascript :: how to display items quantity into select input field 
Javascript :: jquery remove click event 
Javascript :: javascript maximum date 
Javascript :: vue router default page not loaded 
Javascript :: discount calculations javaScript 
Javascript :: jquery on dom change 
Javascript :: parse int into 2 digits format javascript 
Javascript :: js add style to each class 
Javascript :: get value of div jquery 
Javascript :: iterate formData 
Javascript :: statusbar.sethidden(true) in react native 
Javascript :: javascript trim spaces 
Javascript :: create textbox using javascript 
Javascript :: clear textbox js 
Javascript :: set image as background react 
Javascript :: how to set/get cookie in JavaScript 
Javascript :: scrollheight jquery 
Javascript :: difference between backtick and quotes 
Javascript :: /on in jquery 
Javascript :: convert milliseconds to minutes and seconds javascript 
Javascript :: splidejs pauseOnHover 
Javascript :: ajax get form data 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =