mediumArraysPattern: Two Pointers

Target Sum Pairs Solution

Problem Statement

Given an array of integers `masses` and a target integer `targetPull`, find all pairs of indices in `masses` whose corresponding values add up to `targetPull`. Return a list of these pairs, where each pair is represented as an array of two indices.

Examples

Example 1:
Input:{"masses":[12345],"targetPull":7}
Output:[[24]]
Explanation: The only pair of celestial body masses that add up to the target pull of 7 are at indices 2 and 4.

Constraints

  • {"name":"masses length","type":"integer","min":2,"max":1000}
  • {"name":"masses values","type":"integer","min":-1000,"max":1000}
  • {"name":"targetPull","type":"integer","min":-2000,"max":2000}
Time: O(n log n) Space: O(1)
The optimal approach is to sort the list of celestial body masses and then use the two pointers technique to find pairs of masses that add up to the target gravitational pull, resulting in a time complexity of O(n log n).

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.