The Wayback Machine - https://web.archive.org/web/20240818163941/https://www.geeksforgeeks.org/count-pairs-with-given-sum/
Open In App

Count pairs with given sum

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of N integers, and an integer K, the task is to find the number of pairs of integers in the array whose sum is equal to K.

Examples:  

Input: arr[] = {1, 5, 7, -1}, K = 6
Output:  2
Explanation: Pairs with sum 6 are (1, 5) and (7, -1).

Input: arr[] = {1, 5, 7, -1, 5}, K = 6
Output:  3
Explanation: Pairs with sum 6 are (1, 5), (7, -1) & (1, 5).         

Input: arr[] = {1, 1, 1, 1}, K = 2
Output:  6
Explanation: Pairs with sum 2 are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1).

Input: arr[] = {10, 12, 10, 15, -1, 7, 6, 5, 4, 2, 1, 1, 1}, K = 11
Output:  9
Explanation: Pairs with sum 11 are (10, 1), (10, 1), (10, 1), (12, -1), (10, 1), (10, 1), (10, 1), (7, 4), (6, 5).

Naïve Approach: 

A simple solution is to user nested loops, one for traversal of each element and other for checking if there’s another number in the array which can be added to it to give K.

Illustration:

Consider an array arr [ ] = {1 ,5 ,7 ,1} and K = 6

  • initialize count = 0
  • First iteration
    • i = 0
    • j = 1
      • arr[i]+arr[j] == K
      • count = 1
    • i = 0
    • j = 2
      • arr[i] + arr[j] != K
      • count = 1
    • i = 0
    • j = 3
      • arr[i] + arr[j] != K
      • count = 1
  • Second iteration
    • i = 1
    • j = 2
      • arr[i] + arr[j] != K
      • count = 1
    • i = 1
    • j = 3
      • arr[i] + arr[j] == K
      • count = 2
  • Third iteration
    • i = 2
    • j = 3
      • arr[i] + arr[j] != K
      • count = 2
  • Hence Output is 2 .

Follow the steps below to solve the given problem:

Follow the steps below for implementation:

  • Initialize the count variable with 0 which stores the result.
  • Use two nested loop and check if arr[i] + arr[j] == K, then increment the count variable.
  • Return the count.

Below is the implementation of the above approach.

C++
// C++ implementation of simple method to find count of
// pairs with given sum K.
#include <bits/stdc++.h>
using namespace std;

// Returns number of pairs in arr[0..n-1] with sum equal
// to 'K'
int getPairsCount(int arr[], int n, int K)
{
    // Initialize result
    int count = 0;

    // 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] == K)
                count++;

    return count;
}

// Driver function to test the above function
int main()
{
    int arr[] = { 1, 5, 7, -1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 6;
    cout << "Count of pairs is "
         // Function Call
         << getPairsCount(arr, n, K);
    return 0;
}

// This code is contributed by Aditya Kumar (adityakumar129)
C
// C implementation of simple method to find count of
// pairs with given sum.
#include <stdio.h>

// Returns number of pairs in arr[0..n-1] with sum equal
// to 'sum'
int getPairsCount(int arr[], int n, int K)
{
   // Initialize result
    int count = 0;

    // 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] == K)
                count++;

    return count;
}

// Driver function to test the above function
int main()
{
    int arr[] = { 1, 5, 7, -1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 6;
    printf("Count of pairs is %d",
           // Function Call
           getPairsCount(arr, n, K));
    return 0;
}

// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java implementation of simple method to find count of
// pairs with given sum.
public class find {
    public static void main(String args[])
    {
        int[] arr = { 1, 5, 7, -1, 5 };
        int K = 6;
      // Function Call
        getPairsCount(arr, K);
    }

    // Prints number of pairs in arr[0..n-1] with sum equal
    // to 'sum'
    public static void getPairsCount(int[] arr, int K)
    {
        // Initialize result
        int count = 0; 

        // Consider all possible pairs and check their sums
        for (int i = 0; i < arr.length; i++)
            for (int j = i + 1; j < arr.length; j++)
                if ((arr[i] + arr[j]) == K)
                    count++;

        System.out.printf("Count of pairs is %d", count);
    }
}

// This code is contributed by Aditya Kumar (adityakumar129)
Python
# Python3 implementation of simple method
# to find count of pairs with given sum.

# Returns number of pairs in arr[0..n-1]
# with sum equal to 'sum'


def getPairsCount(arr, n, K):

    count = 0  # Initialize result

    # Consider all possible pairs
    # and check their sums
    for i in range(0, n):
        for j in range(i + 1, n):
            if arr[i] + arr[j] == K:
                count += 1

    return count


# Driver function
arr = [1, 5, 7, -1]
n = len(arr)
K = 6
print("Count of pairs is",
      getPairsCount(arr, n, K))

# This code is contributed by Smitha Dinesh Semwal
C#
// C# implementation of simple
// method to find count of
// pairs with given sum.
using System;

class GFG {
    public static void getPairsCount(int[] arr, int sum)
    {

        int count = 0; // Initialize result

        // Consider all possible pairs
        // and check their sums
        for (int i = 0; i < arr.Length; i++)
            for (int j = i + 1; j < arr.Length; j++)
                if ((arr[i] + arr[j]) == sum)
                    count++;

        Console.WriteLine("Count of pairs is " + count);
    }

    // Driver Code
    static public void Main()
    {
        int[] arr = { 1, 5, 7, -1, 5 };
        int sum = 6;
        getPairsCount(arr, sum);
    }
}

// This code is contributed
// by Sach_Code
JavaScript
<script>

// Javascript implementation of simple method to find count of
// pairs with given sum.

// Returns number of pairs in arr[0..n-1] with sum equal
// to 'sum'
function getPairsCount(arr, n, sum)
{
    let count = 0; // Initialize result

    // Consider all possible pairs and check their sums
    for (let i = 0; i < n; i++)
        for (let j = i + 1; j < n; j++)
            if (arr[i] + arr[j] == sum)
                count++;

    return count;
}

// Driver function to test the above function
    let arr = [ 1, 5, 7, -1, 5 ];
    let n = arr.length;
    let sum = 6;
    document.write("Count of pairs is "
        + getPairsCount(arr, n, sum));
    
// This code is contributed by Mayank Tyagi

</script>
PHP
<?php
// PHP implementation of simple 
// method to find count of
// pairs with given sum.

// Returns number of pairs in 
// arr[0..n-1] with sum equal
// to 'sum'
function getPairsCount($arr, $n, $sum)
{
    // Initialize result
    $count = 0; 

    // Consider all possible pairs 
    // and check their sums
    for ($i = 0; $i < $n; $i++)
        for ($j = $i + 1; $j < $n; $j++)
            if ($arr[$i] + $arr[$j] == $sum)
                $count++;

    return $count;
}

    // Driver Code
    $arr = array(1, 5, 7, -1, 5) ;
    $n = sizeof($arr);
    $sum = 6;
    echo "Count of pairs is "
         , getPairsCount($arr, $n, $sum);
         
// This code is contributed by nitin mittal.
?>

Output
Count of pairs is 2

Time Complexity: O(n2), traversing the array for each element
Auxiliary Space: O(1)

Count pairs with given sum using Binary Search.

If the array is sorted then for each array element , we can find the number of pairs by searching all the values (K – arr[i]) which are situated after ith index using Binary Search.

Illustration:

Given arr[ ] = {1, 5, 7, -1} and K = 6

  • sort the array = {-1,1,5,7}
  • initialize count = 0
  • At index = 0:
    • val = K – arr[0] = 6 – (-1) = 7
    • count = count + upperBound(1, 3, 7) – lowerBound(1, 3, 7)
    • count = 1
  • At index = 1:
    • val = K – arr[1] = 6 – 1 = 5
    • count = count + upperBound(2, 3, 5) – lowerBound(2, 3, 5)
    • count = 2
  • At index = 2:
    • val = K – arr[2] = 6 – 5 = 1
    • count = count + upperBound(3, 3, 1) – lowerBound(3, 3, 1)
    • count = 2
  • Number of pairs = 2

Follow the steps below to solve the given problem:

  • Sort the array arr[] in increasing order.
  • Loop from i = 0 to N-1.
    • Find the index of the first element having value same or just greater than (K – arr[i]) using lower bound.
    • Find the index of the first element having value just greater than (K – arr[i]) using upper bound.
    • The gap between these two indices is the number of elements with value same as (K – arr[i]).
    • Add this with the final count of pairs.
  • Return the final count after the iteration is over.

Below is the implementation of the above approach.

C++
// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function to find the count of pairs
int getPairsCount(int arr[], int n, int k)
{
    sort(arr, arr + n);
    int x = 0, c = 0, y, z;
    for (int i = 0; i < n - 1; i++) {
        x = k - arr[i];

        // Lower bound from i+1
        int y = lower_bound(arr + i + 1, arr + n, x) - arr;

        // Upper bound from i+1
        int z = upper_bound(arr + i + 1, arr + n, x) - arr;
        c = c + z - y;
    }
    return c;
}

// Driver code
int main()
{
    int arr[] = { 1, 5, 7, -1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 6;

    // Function call
    cout << "Count of pairs is "
         << getPairsCount(arr, n, k);
    return 0;
}
Java
// Java code for the above approach
import java.io.*;
import java.util.*;

class GFG {

  // lowerBound implementation
  public static int lowerBound(int[] arr, int start,
                               int end, int key)
  {
    while (start < end) {
      int mid = start + (end - start) / 2;
      if (arr[mid] < key) {
        start = mid + 1;
      }
      else {
        end = mid;
      }
    }
    return start;
  }

  // upperBound implementation
  public static int upperBound(int[] arr, int start,
                               int end, int key)
  {
    while (start < end) {
      int mid = start + (end - start) / 2;
      if (arr[mid] <= key) {
        start = mid + 1;
      }
      else {
        end = mid;
      }
    }
    return start;
  }

  // Function to find the count of pairs
  public static int getPairsCount(int[] arr, int n, int k)
  {
    Arrays.sort(arr);
    int c = 0;
    for (int i = 0; i < n - 1; i++) {
      int x = k - arr[i];
      int y = lowerBound(arr, i + 1, n, x);
      int z = upperBound(arr, i + 1, n, x);
      c = c + z - y;
    }
    return c;
  }

  public static void main(String[] args)
  {
    int[] arr = { 1, 5, 7, -1};
    int n = arr.length;
    int k = 6;

    // Function call
    System.out.println("Count of pairs is "
                       + getPairsCount(arr, n, k));
  }
}

// This code is contributed by lokeshmvs21.
Python
# Python code to implement the approach
import bisect

# Function to find the count of pairs


def getPairsCount(arr, n, k):
    arr.sort()
    x, c = 0, 0
    for i in range(n-1):
        x = k-arr[i]

        # Lower bound from i+1
        y = bisect.bisect_left(arr, x, i+1, n)

        # Upper bound from i+1
        z = bisect.bisect(arr, x, i+1, n)
        c = c+z-y
    return c


# Driver function
arr = [1, 5, 7, -1]
n = len(arr)
k = 6

# Function call
print("Count of pairs is", getPairsCount(arr, n, k))

# This code is contributed by Pushpesh Raj
C#
// C# code for the above approach

using System;
using System.Collections;

public class GFG {

    // lowerBound implementation
    public static int lowerBound(int[] arr, int start,
                                 int end, int key)
    {
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (arr[mid] < key) {
                start = mid + 1;
            }
            else {
                end = mid;
            }
        }
        return start;
    }

    // upperBound implementation
    public static int upperBound(int[] arr, int start,
                                 int end, int key)
    {
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (arr[mid] <= key) {
                start = mid + 1;
            }
            else {
                end = mid;
            }
        }
        return start;
    }

    // Function to find the count of pairs
    public static int getPairsCount(int[] arr, int n, int k)
    {
        Array.Sort(arr);
        int c = 0;
        for (int i = 0; i < n - 1; i++) {
            int x = k - arr[i];
            int y = lowerBound(arr, i + 1, n, x);
            int z = upperBound(arr, i + 1, n, x);
            c = c + z - y;
        }
        return c;
    }

    static public void Main()
    {

        // Code
        int[] arr = { 1, 5, 7, -1};
        int n = arr.Length;
        int k = 6;

        // Function call
        Console.WriteLine("Count of pairs is "
                          + getPairsCount(arr, n, k));
    }
}

// This code is contributed by lokesh.
JavaScript
// JavaScript code for the above approach

// lowerBound implementation
function lowerBound(arr, start, end, key) {
  while (start < end) {
    var mid = start + Math.floor((end - start) / 2);
    if (arr[mid] < key) {
      start = mid + 1;
    } else {
      end = mid;
    }
  }
  return start;
}

// upperBound implementation
function upperBound(arr, start, end, key) {
  while (start < end) {
    var mid = start + Math.floor((end - start) / 2);
    if (arr[mid] <= key) {
      start = mid + 1;
    } else {
      end = mid;
    }
  }
  return start;
}

// Function to find the count of pairs
function getPairsCount(arr, n, k) {
  arr.sort((a, b) => a - b);
  var c = 0;
  for (var i = 0; i < n - 1; i++) {
    var x = k - arr[i];
    var y = lowerBound(arr, i + 1, n, x);
    var z = upperBound(arr, i + 1, n, x);
    c = c + z - y;
  }
  return c;
}

var arr = [1, 5, 7, -1];
var n = arr.length;
var k = 6;

// Function call
console.log("Count of pairs is " + getPairsCount(arr, n, k));

Output
Count of pairs is 2

Time Complexity: O(n * log(n) ), applying binary search on each element
Auxiliary Space: O(1)

Count pairs with given sum using Hashing

  • Check the frequency of K – arr[i] in the arr
  • This can be achieved using Hashing.

Illustration:

Given arr[] = {1, 5, 7, -1} and K = 6

  • initialize count = 0
  • At index = 0:
    • freq[K – arr[0]] = freq[6 – 1] = freq[5] = 0
    • count = 0
    • freq[arr[0]] = freq[1] = 1
  • At index = 1:
    • freq[K – arr[1]] = freq[6 – 5] = freq[1] = 1
    • count = 1
    • freq[arr[1]] = freq[5] = 1
  • At index = 2:
    • freq[K – arr[2]] = freq[6 – 7] = freq[-1] = 0
    • count = 1
    • freq[arr[2]] = freq[7] = 1
  • At index = 3:
    • freq[K – arr[3]] = freq[6 – (-1)] = freq[7] = 1
    • count = 2
    • freq[arr[3]] = freq[-1] = 1
  • Number of pairs  = 2

Follow the steps below to solve the given problem: 

  • Create a map to store the frequency of each number in the array.
  • Check if (K – arr[i]) is present in the map, if present then increment the count variable by its frequency.
  • After traversal is over, return the count.

Below is the implementation of the above idea : 

C++
#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> mp;
    int count = 0;
    
    for (int i = 0; i < n; i++) {
        // Check if there exists an element in the map which can be paired with arr[i] to form the sum
        if (mp.find(sum - arr[i]) != mp.end()) {
            count += mp[sum - arr[i]];
        }
        // Increment the count of the current element in the map
        mp[arr[i]]++;
    }
    return count;
}

// Driver code
int main()
{
    int arr[] = { 1, 5, 7, -1, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = 6;

    // Function Call
    cout << "Count of pairs is " << getPairsCount(arr, n, sum);
    return 0;
}
Java
import java.util.HashMap;

public class Main {

    // Function to return the number of pairs in the array with the given sum
    public static int getPairsCount(int[] arr, int sum) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int count = 0;

        for (int num : arr) {
            // Check if (sum - num) exists in the hashmap
            if (map.containsKey(sum - num)) {
                count += map.get(sum - num);
            }

            // Add num to the hashmap or update its count
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        return count;
    }

    public static void main(String[] args) {
        int[] arr = { 1, 5, 7, -1, 5 };
        int sum = 6;

        System.out.println("Count of pairs is " + getPairsCount(arr, sum));
    }
}
Python
def get_pairs_count(arr, sum):
    count = 0
    freq = {}

    for num in arr:
        # Check if (sum - num) exists in the dictionary
        if (sum - num) in freq:
            count += freq[sum - num]

        # Add num to the dictionary or update its count
        if num in freq:
            freq[num] += 1
        else:
            freq[num] = 1

    return count

# Driver code
arr = [1, 5, 7, -1, 5]
sum = 6

print("Count of pairs is", get_pairs_count(arr, sum))
C#
using System;
using System.Collections.Generic;

class Program
{
    // Function to return the number of pairs in the array with the given sum
    static int GetPairsCount(int[] arr, int sum)
    {
        Dictionary<int, int> map = new Dictionary<int, int>();
        int count = 0;

        foreach (int num in arr)
        {
            // Check if (sum - num) exists in the dictionary
            if (map.ContainsKey(sum - num))
            {
                count += map[sum - num];
            }

            // Add num to the dictionary or update its count
            if (map.ContainsKey(num))
            {
                map[num]++;
            }
            else
            {
                map[num] = 1;
            }
        }

        return count;
    }

    static void Main()
    {
        int[] arr = { 1, 5, 7, -1, 5 };
        int sum = 6;

        Console.WriteLine("Count of pairs is " + GetPairsCount(arr, sum));
    }
}
JavaScript
function getPairsCount(arr, sum) {
    let map = new Map();
    let count = 0;

    arr.forEach(num => {
        // Check if (sum - num) exists in the map
        if (map.has(sum - num)) {
            count += map.get(sum - num);
        }

        // Add num to the map or update its count
        if (map.has(num)) {
            map.set(num, map.get(num) + 1);
        } else {
            map.set(num, 1);
        }
    });

    return count;
}

// Driver code
const arr = [1, 5, 7, -1, 5];
const sum = 6;

console.log("Count of pairs is " + getPairsCount(arr, sum));

Output
Count of pairs is 3

Time Complexity: O(n), to iterate over the array
Auxiliary Space: O(n), to make a map of size n



Previous Article
Next Article

Similar Reads

Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X &amp; Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X &amp; Y) = M, where ⊕ denotes the Bitwise XOR and &amp; denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array
Given an array arr[] consisting of N strings, the task is to find the pair of strings that is not present in the array formed by any pairs (arr[i], arr[j]) by swapping the first characters of the strings arr[i] and arr[j]. Examples: Input: arr[] = {"good", "bad", "food"}Output: 2Explanation:The possible pairs that can be formed by swapping the firs
13 min read
Count of pairs in a given range with sum of their product and sum equal to their concatenated number
Given two numbers A and B, the task is to find the count of pairs (X, Y) in range [A, B], such that (X * Y) + (X + Y) is equal to the number formed by concatenation of X and YExamples: Input: A = 1, B = 9 Output: 9 Explanation: The pairs (1, 9), (2, 9), (3, 9), (4, 9), (5, 9), (6, 9), (7, 9), (8, 9) and (9, 9) are the required pairs.Input: A = 4, B
5 min read
Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs
Given an integer K and a square matrix mat[][] of size N * N with elements from the range[1, K], the task is to count ways to remove pairs of distinct matrix elements such that remaining elements can be arranged in pairs vertically or horizontally. Examples: Input: mat[][] = {{1, 2}, {3, 4}}, K = 4Output: 4Explanation:Remove the row {1, 2}. Therefo
10 min read
Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND
Given an array arr[] consisting of N positive integers, replace pairs of array elements whose Bitwise AND exceeds Bitwise XOR values by their Bitwise AND value. Finally, count the maximum number of such pairs that can be generated from the array. Examples: Input: arr[] = {12, 9, 15, 7}Output: 2Explanation:Step 1: Select the pair {12, 15} and replac
9 min read
Maximize count of pairs whose bitwise XOR is even by replacing such pairs with their Bitwise XOR
Given an array arr[] of size N, the task is to replace a pair of array elements whose Bitwise XOR is even by their Bitwise XOR. Repeat the above step as long as possible. Finally, print the count of such operations performed on the array Examples: Input: arr[] = { 4, 6, 1, 3 }Output: 3Explanation:Step 1: Remove the pair (4, 6) and replace them by t
11 min read
Maximum count of pairs such that element at each index i is included in i pairs
Given an array arr[] and an integer N, the task is to find the maximum number of pairs that can be formed such that ith index is included in almost arr[i] pairs. Examples: Input: arr[] = {2, 2, 3, 4} Output: 51 32 42 43 43 4Explanation: For the given array, a maximum of 5 pairs can be created where 1st index is included in 1 pair, 2nd index in 2 pa
6 min read
Count the number of pairs that have column sum greater than row sum
Given a matrix of size NxN. The task is to count the number of pair of indices (i, j) such that the sum of j-th column is greater than the sum of i-th row. Examples: Input : N = 2, mat[][] = {{1, 2}, {3, 4}} Output : 2 The 2 valid pairs are (1, 1) and (1, 2). Input : N = 3, mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Output : 4 Approach: T
6 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Count pairs of indices having sum of indices same as the sum of elements at those indices
Given an array arr[] consisting of N integers, the task is to find the number of pairs (i, j) whose sum of indices is the same as the sum elements at the indices. Examples: Input: arr[] = {0, 1, 7, 4, 3, 2}Output: 1Explanation: There exists only pair that satisfies the condition is {(0, 1)}. Input: arr[] = {1, 6, 2, 4, 5, 6}Output: 0 Naive Approach
9 min read
Count pairs in an array having sum of elements with their respective sum of digits equal
Given an array arr[] consisting of N positive integers, the task is to count the number of pairs in the array, say (a, b) such that sum of a with its sum of digits is equal to sum of b with its sum of digits. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Following are the pairs that satisfy the given criteria: (1, 1): The difference bet
8 min read
Minimize sum of absolute difference between all pairs of array elements by decrementing and incrementing pairs by 1
Given an array arr[] ( 1-based indexing ) consisting of N integers, the task is to find the minimum sum of the absolute difference between all pairs of array elements by decrementing and incrementing any pair of elements by 1 any number of times. Examples: Input: arr[] = {1, 2, 3}Output: 0Explanation:Modify the array elements by performing the foll
5 min read
Generate pairs in range [0, N-1] with sum of bitwise AND of all pairs K
Given an integer N (which is always a power of 2) denoting the length of an array which contains integers in range [0, N-1] exactly once, the task is to pair up these elements in a way such that the sum of AND of the pair is equal to K. i.e ∑ (ai &amp; bi) = K. Note: Each element can be part of only one pair. Examples: Input: N = 4, K = 2Output: [[
10 min read
Count pairs in a binary tree whose sum is equal to a given value x
Given a binary tree containing n distinct numbers and a value x. The problem is to count pairs in the given binary tree whose sum is equal to the given value x. Examples: Input : 5 / \ 3 7 / \ / \ 2 4 6 8 x = 10 Output : 3 The pairs are (3, 7), (2, 8) and (4, 6). 1) Naive Approach: One by one get each node of the binary tree through any of the tree
15+ min read
Given two arrays count all pairs whose sum is an odd number
Given two arrays of N and M integers. The task is to find the number of unordered pairs formed of elements from both arrays in such a way that their sum is an odd number. Note: An element can only be one pair.Examples: Input: a[] = {9, 14, 6, 2, 11}, b[] = {8, 4, 7, 20} Output: 3 {9, 20}, {14, 7} and {11, 8}Input: a[] = {2, 4, 6}, b[] = {8, 10, 12}
7 min read
Count of replacements required to make the sum of all Pairs of given type from the Array equal
Given an integer array arr of length N and an integer K, the task is to find the number of array elements to be replaced by a value from the range [1, K] such that each pair (arr[i], arr[N - 1 - i] have equal sum. Examples : Input: arr[] = {1, 2, 2, 1}, K = 3 Output: 1 Explanation: Replace arr[0] with 3, so that the array becomes {3, 2, 2, 1}. Now,
12 min read
Maximum Count of pairs having equal Sum based on the given conditions
Given an array arr[] of length N containing array elements in the range [1, N], the task is to find the maximum number of pairs having equal sum, given that any element from the array can only be part of a single pair. Examples: Input: arr[] = {1, 4, 1, 4} Output: 2 Explanation: Pairs {{1, 4}, {1, 4}} have equal sum 5. Input: arr[] = {1, 2, 4, 3, 3
8 min read
Count pairs from a given range whose sum is a Prime Number in that range
Given two integers L and R, the task is to count the number of pairs from the range [L, R] whose sum is a prime number in the range [L, R]. Examples: Input: L = 1, R = 5Output: 4Explanation: Pairs whose sum is a prime number and in the range [L, R] are { (1, 1), (1, 2), (1, 4), (2, 3) }. Therefore, the required output is 4. Input: L = 1, R = 100Out
14 min read
Count pairs from a given range having even sum
Given two positive integers L and R, the task is to find the count of ordered pairs in the range [L, R] such that the sum of elements of each pair is even. Examples: Input: L = 1, R =3Output: 5Explanation:Pairs whose sum of elements are even and lies in the range [1, 3] are { (1, 3), (1, 1), (2, 2), (3, 3), (3, 1) } Input: L = 1, R = 1Output: 1 App
8 min read
Count even sum pairs possible by selecting two integers from two given ranges respectively
Given two positive integers X and Y, the task is to count pairs with even sum possible by choosing any integer from the range 1 to X and another integer from the range 1 to Y. Examples: Input : X = 2, Y = 3 Output : 3 Explanation : All such possible pairs are {1, 1}, {1, 3}, {2, 2}. Approach: Follow the steps below to solve the problem: Initialize
6 min read
Count distinct sum of pairs possible from a given range
Given two positive integers L and R ( where L ? R ), the task is to count the number of distinct integers that can be obtained by adding any pair of integers from the range [L, R]. Examples: Input: L = 3, R = 5Output: 11Explanation: All possible distinct sum of pairs are as follows: (3, 3). Sum = 6.(3, 4). Sum = 7.(3, 5). Sum = 8.(4, 5). Sum = 9.(5
3 min read
Count pairs having distinct sum from a given range
Given two positive integers L and R, the task is to find the number of pairs with elements from the range [L, R], whose sums are distinct. Examples: Input: L = 2, R = 3Output: 3Explanation: All possible pairs with elements from the range [2, 3] are {(2, 2), (2, 3), (3, 2), (3, 3)}. Since sum of the pairs (2, 3) and (3, 2) are equal, the count of pa
5 min read
Count of pairs in given Array with product of their values equal to sum of their indices (arr[i]*arr[j] = i+j)
Given an array arr[] of length N with distinct integers from 1 to 2*N, the task is to count the number of pairs of indices (i, j) such that (i &lt; j) and arr[i] * arr[j] = i + j, i.e. calculate the number of pairs such that their product is equal to their sum of indices. Examples: Input: N = 5, arr[] = {3, 1, 5, 9, 2}Output: 3Explanation: There ar
12 min read
Count of Pairs in given Array having both even or both odd or sum as K
Given an array arr[] of distinct integers of size N and an integer K, The task is to find the total no of possible pairs in the array such that, either both are even or both are odd or the sum of the pair is K Note: No element is part of more than one pair. Examples: Input: N = 6, K = 7, arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Possible pair
7 min read
Maximum count of adjacent pairs with even sum in given Circular Array
Content Removed
1 min read
Count of adjacent pairs in given Array with even sum
Given an array arr[] of N integers, the task is to find the count of pairs of adjacent elements whose sum is even where each element can belong to at most one pair. Example: Input: arr[] = {1, 12, 1, 3, 5}Output: 1Explanation: 1 pair can be formed with arr[3] and arr[4]. Input: arr[] = {1, 2, 3, 4, 5, 6, 8, 9}Output: 0 Approach: The given problem c
4 min read
Count pairs in given Array having sum of index and value at that index equal
Given an array arr[] containing positive integers, count the total number of pairs for which arr[i]+i = arr[j]+j such that 0≤i&lt;j≤n-1. Examples: Input: arr[] = { 6, 1, 4, 3 }Output: 3Explanation: The elements at index 0, 2, 3 has same value of a[i]+i as all sum to 6 {(6+0), (4+2), (3+3)}. Input: arr[] = { 8, 7, 6, 5, 4, 3, 2, 1 }Output: 28 Naive
8 min read
Count of possible pairs whose sum and bitwise XOR is given
Given two integers S and X representing the sum and bitwise XOR respectively of two integers, the task is to find the count of all such possible pairs such that their sum is equal to S and bitwise XOR is equal to X. Examples: Input: S = 9, X = 5Output: 4Explanation: (2, 7), (3, 6), (6, 3), (7, 2) completely satisfies the given conditions.It can als
9 min read
Count of Pairs with given sum in Rotated Sorted Array
Given an array arr[] of distinct elements size N that is sorted and then around an unknown point, the task is to count the number of pairs in the array having a given sum X. Examples: Input: arr[] = {11, 15, 26, 38, 9, 10}, X = 35Output: 1Explanation: There is a pair (26, 9) with sum 35 Input: arr[] = {11, 15, 6, 7, 9, 10}, X = 16Output: 2 Approach
13 min read
Count pairs from two BSTs whose sum is equal to a given value x
Given two BSTs containing n1 and n2 distinct nodes respectively. Given a value x. The problem is to count all pairs from both the BSTs whose sum is equal to x. Examples: Input : BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 10 / \ 6 15 / \ / \ 3 8 11 18 x = 16 Output : 3 The pairs are: (5, 11), (6, 10) and (8, 8)Recommended PracticeBrothers From Differen
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg