17. Count pairs with given sum

17. Count pairs with given sum


Problem link :- click here


package programs;

import java.util.*;

public class Array__17
{

	static int getPairsCount(int arr[], int n, int sum)
	{
		HashMap<Integer, Integer> frequencyMap = new HashMap<>();
		
		for(int i=0; i<n; i++)
		{
			if(!frequencyMap.containsKey(arr[i]))
				frequencyMap.put(arr[i], 1);
			else
				frequencyMap.put(arr[i], frequencyMap.get(arr[i])+1);
		}
		
		int twiceCount =0;
		for(int i=0; i<n; i++)
		{
			if(  frequencyMap.containsKey(sum - arr[i]) )
				twiceCount += frequencyMap.get(sum - arr[i]);
			if( sum-arr[i] == arr[i] )
				twiceCount--;
		}
		return twiceCount/2;
	}
	
	public static void main(String[] args)
	{
		int i, n, ans, sum;
		
		Scanner s = new Scanner(System.in);
		System.out .print("Enter the size of the array : ");
		n = s.nextInt();
		int array[] = new int[n];
		System.out.println("Enter the elements of the array\n");
		for(i=0; i<n; i++)
			array[i] = s.nextInt();
		System.out.print("Enter the sum : ");
		sum = s.nextInt();
		
		System.out.println("Given array :");
		print_array(array, n);
		System.out.println("\n");

		ans = getPairsCount(array, n, sum);
		System.out.println("Count of pairs is : " + ans);
	}

	static void print_array(int[] arr, int n)
	{
		for(int i=0; i<n; i++)
			System.out.print(arr[i] + " ");
	}
}

Time complexity :- O(n)
Space complexity :- O(n)



Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree