Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Problem Statement
1.2.
Algorithm
1.2.1.
Example
1.2.2.
Implementation in Java:
1.2.3.
Test Case
1.2.4.
Implementation in C++
1.2.5.
Complexity Analysis 
2.
Frequently Asked Questions
2.1.
What is a hashtable?
2.2.
How do we store data in a hashmap?
2.3.
What is reduced form?
2.4.
Why is HashMap used?
2.5.
Which is better: HashMap or ArrayList?
3.
Conclusion
Last Updated: Apr 30, 2024
Easy

Count pairs with given sum

Author Amit Singh
2 upvotes

Introduction

In this article, we will learn how to write a program to count the number of pairs of integers in the given array whose sum is equal to the ‘sum’ that is given using Hashing Method. 

Before we start with our problem, let us discuss what is a Hash Table? 

A Hash table is one of the essential data structures that uses a particular function known as a hash function which will map a given value with a key to retrieve the elements faster.

A hash table is a data-structure used to store information. The information is composed mainly of keys and values. The effectiveness of the hash function used for mapping determines how efficient the mapping process is.

No, let us right jump into the Problem Statement:

Problem Statement

The problem statement is that we are given an array of ‘n’ elements and a ‘sum’ integer; we have to count the number of pairs in the array whose sum is equal to the ‘sum’ that is given.

Sample Input

5 6

1 2 3 4 5

Sample Output:

2

Explanation: 

All pairs whose sum is equal is 6:

The sum of (1, 5) is 6.  

The sum of (2, 4) is 6. 

Algorithm

  1. We will start by making a hash table that will store the count of each element of the array.
  2. Then we iterate that array for 'i' in range '0' to 'n-1'.
    1. Then we will check if arr[i] is equal to 'k-arr[i]', then find (count_of(k-arr[i])-1) and add it to the result.
    2. If arr[i] is not equal to k-arr[i], then find (count_of(k-arr[i]) and add it to the result.
  3. Then we will return the result.
     

Example

1.Let us take an array {1, 2, 4, 5, 6} as an input.

2. Create an empty hashmap ‘test’.

3. Insert all elements of the array into ‘Hash’ with their frequency.

4. Iterate that array for 'i' in range '0' to 'n-1'.

5. Now, we will check if arr[i] is equal to 'sum-arr[i]', 

7. Then find (count_of(sum-arr[i])-1) and add it to the result.

8. If arr[i] is not equal to sum-arr[i], then find (count_of(sum-arr[i]) and add it to the result.

9. Then we will return the result.

 

Implementation in Java:

import java.util.*;
public class CodingNinjas
{
  public static void main(String[] args) {
        Scanner scn= new Scanner(System.in);
        int n = scn.nextInt();
        int sum = scn.nextInt();
        int[] arr = new int[n];
        HashMap<Integer, Integer> test = new HashMap<Integer, Integer>();
        for(int i=0;i<n;i++){
            arr[i] = scn.nextInt();
            Integer j = test.get(arr[i]);
            test.put(arr[i], (j == null) ? 1 : j + 1);
        }
        int result = 0;
        for (int i = 0; i < n; i++)
        {
            if (arr[i] == sum - arr[i])
            {
                result += (test.get(arr[i]) - 1);
            }
            else
            {
                Integer j = test.get(sum - arr[i]);
                if(j!=null)
                    result += j;
            }
        }
        result /= 2;
    System.out.println("Number of pairs with the given sum are: "+result);
  }
}
You can also try this code with Online Java Compiler
Run Code

Test Case

Input:

5 6

1 2 3 4 5

Output:


Implementation in C++

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n, sum;
    cin >> n >> sum;
    unordered_map<int, int> test;
    vector<int> arr(n);
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
        test[arr[i]]++;
    }
    int result = 0;
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == sum - arr[i])
        {
            result += (test[arr[i]] - 1);
        }
        else
        {
            result += (test[sum - arr[i]]);
        }
    }
    result /= 2;
    cout << "Number of pairs with the given sum are: "<<result << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Complexity Analysis 

Time Complexity: O(N), as we iterate over the array only once.

Space Complexity: O(N), as we are maintaining a hash table.

You can also read about the Longest Consecutive Sequence.

Frequently Asked Questions

What is a hashtable?

A Hash table is one of the essential data structures that uses a particular function which is known as a hash function that maps a given value with a key to retrieve the elements faster.

How do we store data in a hashmap?

In hashmap, data is stored in the form of the key-value pair. This means every key will have some value or data mapped to it.

What is reduced form?

The reduced form is replacing the elements in an array with 0 to n-1 according to the order of the elements means the smallest element will be 0, and the largest element will be n-1.

Why is HashMap used?

Hashmaps can be said to as the most commonly used implementation of the concept of a map. Hashmaps allow arbitrary objects to be associated with other arbitrary objects. This can be very useful for doing things like grouping or joining data together by some common attribute.

Which is better: HashMap or ArrayList?

ArrayList stores the elements only as values and maintains the indexing for every element. While HashMap stores elements with key and value pairs, that means two objects. So HashMap takes more memory comparatively.

Conclusion

In this article, we have studied how to write a program to count pairs whose sum is equal to the ‘sum’ that is given. We hope that this article has provided you with the help to enhance your knowledge regarding hashmap and if you would like to learn more, check out our articles on ArraysHashmap and Problems on hashmap.

Check out this problem - Pair Sum In Array.

Recommended Readings:

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, Javascript, System Design, etc. Enrol in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Merry Learning!

Live masterclass