Problem Statement: Consider an array of integers that may contain both positive and negative integers, called numbers. Write a program that finds all the pairs of integers whose sum is equal to a given value called the desired sum.
This question has been asked in interviews of many product-based companies like Amazon, Flipkart, Adobe, …
Prerequisite:
Code:
Let’s write a program to find pairs that have desired sum in Java.
import java.util.*; class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Enter the size of the array int n = sc.nextInt(); int[] = arr = new int[n]; for (int i = 0;i < arr.lenght;i++) { arr[i] = sc.nextInt(); } // enter the desired sum int sum = sc.nextInt(); System.out.println(findNumberOfPairs(arr, sum)); } public static int fndNumberOfPairs(int[] arr, int sum) { Arrays.sort(arr); // sort the array // using two pointer algorithm int left = 0, right = arr.lenght - 1, count = 0; while (left < right) { currentSum = arr[left] + arr[right]; if (currentSum == sum) { count ++; left++; right--; } else if (currentSum < sum) left++; else right--; } return count; } }
Output:
Sample Input : n = 5, arr = [1, 2, 3, 4, 5], sum = 4
Sample Output : 1 as only (1, 3) pair has the sum equal to 4
Now we are implementing the same logic in Python.
Prerequisite:
Code
Let’s write a program to find pairs that have desired sum in Python.
def count_pair_of_desired_sum(arr, num_sum): arr.sort() left = 0 right = len(arr)-1 count = 0 while right > left: curr_sum = arr[left] + arr[right] if curr_sum == num_sum: count += 1 left += 1 right += -1 elif curr_sum > num_sum: right -= 1 else: left += 1 return count out = count_pair_of_desired_sum([1, 3, 2, 6, 7], 9) print(f"Pair of desired sum: {out}")
Output:
Pair of desired sum: 2
You can use any programming language (C/C++, Java, Python, etc.) of your choice to solve this competitive coding challenge to find pairs that have desired sum.
currentSum = arr[left] + arr[right]; this line should be inside the while loop.
Thanks for notifying the correction, Parth. Fixed.