Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count pairs from a given array whose sum lies from a given range
Next article icon

C++ Program to Count pairs with given sum

Last Updated : 15 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of integers, and a number 'sum', find the number of pairs of integers in the array whose sum is equal to 'sum'.


Examples:  

Input  :  arr[] = {1, 5, 7, -1},            sum = 6 Output :  2 Pairs with sum 6 are (1, 5) and (7, -1)  Input  :  arr[] = {1, 5, 7, -1, 5},            sum = 6 Output :  3 Pairs with sum 6 are (1, 5), (7, -1) &                      (1, 5)           Input  :  arr[] = {1, 1, 1, 1},            sum = 2 Output :  6 There are 3! pairs with sum 2.  Input  :  arr[] = {10, 12, 10, 15, -1, 7, 6,                     5, 4, 2, 1, 1, 1},            sum = 11 Output :  9


Expected time complexity O(n)
 

Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.


Naive Solution - A simple solution is to traverse each element and check if there's another number in the array which can be added to it to give sum. 
 

C++
// C++ implementation of simple method to find count of // pairs with given sum. #include <bits/stdc++.h> using namespace std;  // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount(int arr[], int n, int sum) {     int count = 0; // Initialize result      // Consider all possible pairs and check their sums     for (int i = 0; i < n; i++)         for (int j = i + 1; j < n; j++)             if (arr[i] + arr[j] == sum)                 count++;      return count; }  // Driver function to test the above function int main() {     int arr[] = { 1, 5, 7, -1, 5 };     int n = sizeof(arr) / sizeof(arr[0]);     int sum = 6;     cout << "Count of pairs is "          << getPairsCount(arr, n, sum);     return 0; } 

Output
Count of pairs is 3


Time Complexity: O(n2) 
Auxiliary Space: O(1)
  

Efficient solution - 
A better solution is possible in O(n) time. Below is the Algorithm - 

  1. Create a map to store frequency of each number in the array. (Single traversal is required)
  2. In the next traversal, for every element check if it can be combined with any other element (other than itself!) to give the desired sum. Increment the counter accordingly.
  3. After completion of second traversal, we'd have twice the required value stored in counter because every pair is counted two times. Hence divide count by 2 and return.

Below is the implementation of above idea : 
 

C++
// C++ implementation of simple method to find count of // pairs with given sum. #include <bits/stdc++.h> using namespace std;  // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount(int arr[], int n, int sum) {     unordered_map<int, int> m;      // Store counts of all elements in map m     for (int i = 0; i < n; i++)         m[arr[i]]++;      int twice_count = 0;      // iterate through each element and increment the     // count (Notice that every pair is counted twice)     for (int i = 0; i < n; i++) {         twice_count += m[sum - arr[i]];          // if (arr[i], arr[i]) pair satisfies the condition,         // then we need to ensure that the count is         // decreased by one such that the (arr[i], arr[i])         // pair is not considered         if (sum - arr[i] == arr[i])             twice_count--;     }      // return the half of twice_count     return twice_count / 2; }  // Driver function to test the above function int main() {     int arr[] = { 1, 5, 7, -1, 5 };     int n = sizeof(arr) / sizeof(arr[0]);     int sum = 6;     cout << "Count of pairs is "          << getPairsCount(arr, n, sum);     return 0; } 

Output
Count of pairs is 3

Time Complexity: O(n)

Auxiliary Space: O(n)

The extra space is used to store the elements in the map.

Please refer complete article on Count pairs with given sum for more details!


Next Article
Count pairs from a given array whose sum lies from a given range
author
kartik
Improve
Article Tags :
  • Hash
  • C++ Programs
  • C++
  • DSA
  • Arrays
  • Amazon
  • Accolite
  • Hike
  • FactSet
Practice Tags :
  • Accolite
  • Amazon
  • FactSet
  • Hike
  • CPP
  • Arrays
  • Hash

Similar Reads

  • C++ Program for Number of pairs with maximum sum
    Given an array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i Example : Input : arr[] = {1, 1, 1, 2, 2, 2} Output : 3 Explanation: The maximum possible pair sum where i Method 1 (Naive) Traverse a loop i from 0 to n, i.e length of the array and another loop j
    3 min read
  • C++ Program to Count triplets with sum smaller than a given value
    Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input :
    4 min read
  • Count number of pairs with positive sum in an array
    Given an array arr[] of N integers, the task is to count the number of pairs with positive sum. Examples: Input: arr[] = {-7, -1, 3, 2} Output: 3 Explanation: The pairs with positive sum are: {-1, 3}, {-1, 2}, {3, 2}. Input: arr[] = {-4, -2, 5} Output: 2 Explanation: The pairs with positive sum are:
    9 min read
  • C++ Program for Two Pointers Technique
    Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Let’s see the naive so
    4 min read
  • Count pairs from a given array whose sum lies from a given range
    Given an array arr[] consisting of N integers and two integers L and R, the task is to count the number of pairs whose sum lies in the range [L, R]. Examples: Input: arr[] = {5, 1, 2}, L = 4, R = 7Output: 2Explanation:The pairs satisfying the necessary conditions are as follows: (5, 1): Sum = 5 + 1
    13 min read
  • Count of even sum triplets in the array for Q range queries
    Given an array arr[] of size N and Q queries of the form (L, R), the task is to count number of triplets with even sum for the elements in the range L and R for each query. Examples: Input: N = 6, arr[ ] = {1, 2, 3, 4, 5, 6}, Q[ ] = {{1, 3}, {2, 5}}Output: 1 2Explanation:For Query (1, 3): only tripl
    9 min read
  • Number of pairs whose sum is a power of 2
    Given an array arr[] of positive integers, the task is to count the maximum possible number of pairs (arr[i], arr[j]) such that arr[i] + arr[j] is a power of 2. Note: One element can be used at most once to form a pair. Examples: Input: arr[] = {3, 11, 14, 5, 13} Output: 2 All valid pairs are (13, 3
    9 min read
  • Count of elements which cannot form any pair whose sum is power of 2
    Given an array arr[] of length N, the task is to print the number of array elements that cannot form a pair with any other array element whose sum is a power of two.Examples: Input: arr[] = {6, 2, 11} Output: 1 Explanation: Since 6 and 2 can form a pair with sum 8 (= 23). So only 11 has to be remove
    8 min read
  • How to Create a Set of Pairs in C++?
    In C++, sets are associative containers that store unique elements. On the other hand, pairs allow the users to store two data of different or the same type into a single object. In this article, we will learn how we can create a set of pairs in C++. Example Input: p1={1, 2} p2 ={3, 4} Output: Eleme
    2 min read
  • C++ Program for Counting sets of 1s and 0s in a binary matrix
    Given a n × m binary matrix, count the number of sets where a set can be formed one or more same values in a row or column. Examples: Input: 1 0 1 0 1 0 Output: 8 Explanation: There are six one-element sets (three 1s and three 0s). There are two two- element sets, the first one consists of the first
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences