![]() |
VOOZH | about |
Given an array arr[] of n integers and a target value, find the number of pairs of integers in the array whose sum is equal to target.
Examples:
Input: arr[] = [1, 5, 7, -1, 5], target = 6
Output: 3
Explanation: Pairs with sum 6 are (1, 5), (7, -1) & (1, 5).Input: arr[] = [1, 1, 1, 1], target = 2
Output: 6
Explanation: Pairs with sum 2 are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1) and (1, 1).Input: arr[] = [10, 12, 10, 15, -1], target = 125
Output: 0
Explanation: There is no pair with sum = target
Table of Content
The very basic approach is to generate all the possible pairs and check if any pair exists whose sum is equals to given target value, then increment the count variable.
3
The idea is to sort the input array and use two-pointer technique. Maintain two pointers, say left and right and initialize them to the first and last element of the array respectively. According to the sum of left and right pointers, we can have three cases:
- arr[left] + arr[right] < target: Increase the pair sum by moving the left pointer towards right.
- arr[left] + arr[right] > target: Decrease the pair sum by moving the right pointer towards left.
- arr[left] + arr[right] = target: We have found a pair whose sum is equal to target. We can find the product of the count of both the elements and add them to the result.
3
HashMap or Dictionary provides a more efficient solution to the 2Sum problem. Instead of checking every pair of numbers, we keep each number in a map as we go through the array. For each number, we calculate its complement (i.e., target - current number) and check if itβs in the map. If it is, increment the count variable by the occurrences of complement in map.
3
Related Problems: