easyArraysPattern: Two Pointers
Pairs With Sum 947 Solution
Problem Statement
Given an array of integers `nums` and a target integer `targetSum`, find all pairs of integers in the `nums` array that add up to `targetSum`. Return the pairs of indices of the integers in the `nums` array that satisfy the condition.
Examples
Example 1:
Input:{"weights":[1,2,3,4,5],"targetWeight":947}
Output:[]
Explanation: No pairs add up to 947
Example 2:
Input:{"weights":[47,900,10],"targetWeight":947}
Output:[[0,1]]
Explanation: Pair at indices 0 and 1 (47 + 900) adds up to 947
Example 3:
Input:{"weights":[0,947,1,2],"targetWeight":947}
Output:[[0,1]]
Explanation: Pair at indices 0 and 1 (0 + 947) adds up to 947
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- nums contains only integers
Time: O(n) Space: O(n)
Use a hash table to store the elements and their indices, and then iterate through the array to find the pairs
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def pairs_with_sum_947(nums):\n num_to_index = {}\n result = []\n for i, num in enumerate(nums):\n complement = 947 - num\n if complement in num_to_index:\n result.append([num_to_index[complement], i])\n num_to_index[num] = i\n return result