skip to Main Content

Given an array of integers arr and a target sum target, find all pairs of distinct integers that add up to the target sum. Return an array of arrays containing these pairs sorted in ascending order. If there are no such pairs, return an empty array.

I have tried this, but it doesn’t work

function findPairs(arr, target) {
  let arr1 = []
  for (let i = 0; i <= arr.length - 1; i++) {
    for (let j = i + 1; j < arr.length - 1; j++) {
      if (arr[i] + arr[j] === target) {
        arr1.unshift(arr[i], arr[j])

      }

    }

  }
  return new Array(arr1)
}
console.log(findPairs([3, 7, 8, 4, 5, 9], 12)) // [[3,9],[4,8],[5,7]]

console.log(findPairs([1, 2, 3, 4], 8)) // []

2

Answers


  1. Here is a corrected version of your code:

    function findPairs(arr, target) {
      let arr1 = []
      for (let i = 0; i <= arr.length - 1; i++) {
        for (let j = i + 1; j <= arr.length - 1; j++) {
          if (arr[i] + arr[j] === target) {
            arr1.unshift([arr[i], arr[j]])
          }
        }
      }
      return arr1.sort((a,b) => a.sort() && b.sort() && (a[0] - b[0]));
    }
    console.log(findPairs([3, 7, 8, 4, 5, 9], 12)) // [[3,9],[4,8],[5,7]]
    
    console.log(findPairs([1, 2, 3, 4], 8)) // []

    You can also use Array#reduce and Array#sort methods as follows:

    function findPairs(arr, target) {
        return arr.reduce(
          (acc,cur,i) => 
          [
              ...acc,
              ...(
                  i >= arr.length ? 
                    [] : 
                    arr.slice(i+1).map(b => [cur,b]).filter(([x,y]) => x+y === target)
              )
          ],
          []
        )
        .sort((a,b) => a.sort() && b.sort() && (a[0] - b[0]));
    }
    console.log(findPairs([3, 7, 8, 4, 5, 9], 12)); // [[3,9],[4,8],[5,7]]
    
    console.log(findPairs([1, 2, 3, 4], 8)); // []
    Login or Signup to reply.
  2. Following commented solution might help the OP getting (re)started with the OP’s own approach.

    Since the implementation is based on mutating/emptying an array entirely, it firstly creates a shallow copy of the array which was passed to it.

    It then stepwise empties the array until no to be processed item is left. With each iteration a currentValue gets shifted from the array. A flag which indicates whether a match was found is set to its initial false value, and the array’s current length gets assigned to an index variable.

    The now following nested iteration counts the index down whilst accessing the next possibly matching value from the array’s current state, until either the array iteration was completed or a matching value was found. As for the latter case one does create the array of the matching pair which then gets pushed to the result array. One also needs to update the current array by spliceing the matching value from it (thus further emptying the array). Finally one needs to flag/indicate the matching pair in order to exit early from the inner while iteration.

    function findPairs(arr, targetValue) {
      // - create a shallow copy in order to
      //   not mutate the original reference.
      arr = [...arr];
    
      const result = [];
    
      let currentValue, possibleMatch, isMatch, idx;
    
      // - empty the array until no to be processed item is left.
      while ((currentValue = arr.shift()) || (arr.length > 0)) {
    
        isMatch = false;
        idx = arr.length;
    
        // - iterate the constantly emptying array ...
        //   (... unless a match was found before
        //    or the array has been entirely iterated.)
        while (!isMatch && (possibleMatch = arr[--idx]) && (idx >= 0)) {
    
          // ... in order to find a matching pair ...
          if (currentValue + possibleMatch === targetValue) {
    
            // ... where one then would create the pair ...
            result.push([currentValue, possibleMatch]);
            // ... and update/empty the processed array ...
            arr.splice(idx, 1);
    
            // ... and indicate/flag the match.
            isMatch = true;
          }
        }
      }
      return result;
    }
    console.log(
      'findPairs([3, 7, 8, 4, 5, 9], 12) ...',
      // [[3, 9], [4, 8], [5, 7]]
      findPairs([3, 7, 8, 4, 5, 9], 12)
    ); 
    console.log(
      'findPairs([1, 2, 3, 4], 5) ...',
      // [[1, 4], [2, 3]]
      findPairs([1, 2, 3, 4], 5)
    );
    console.log(
      'findPairs([1, 2, 3, 4], 8) ...',
      // []
      findPairs([1, 2, 3, 4], 8)
    );
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search