Count pairs in a sorted array whose sum is less than x

Given a sorted integer array and number x, the task is to count pairs in array whose sum is less than x.

Examples:

Input  : arr[] = {1, 3, 7, 9, 10, 11}
         x = 7
Output : 1
There is only one pair (1, 3)

Input  : arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
         x = 7
Output : 6
Pairs are (1, 2), (1, 3), (1, 4), (1, 5)
          (2, 3) and (2, 4)  



A simple solution of this problem run two loops to generate all pairs and one by one and check if current pair’s sum is less than x or not.

An Efficient solution of this problem is take initial and last value of index in l and r variable.

1) Initialize two variables l and r to find the candidate 
   elements in the sorted array.
       (a) l = 0
       (b) r = n - 1
2) Initialize : result = 0
2) Loop while l < r.

    // If current left and current
    // right have sum smaller than x,
    // the all elements from l+1 to r
    // form a pair with current
    (a) If (arr[l] + arr[r] < x)  
          result = result + (r - l)      
   
    (b) Else
            r--;
       
3) Return result

Below is the implementation of above steps.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count pairs in an array
// whose sum is less than given number x
#include<bits/stdc++.h>
using namespace std;
  
// Function to count pairs in array
// with sum less than x.
int findPairs(int arr[],int n,int x)
{
    int l = 0, r = n-1;
    int result = 0;
  
    while (l < r)
    {
        // If current left and current
        // right have sum smaller than x,
        // the all elements from l+1 to r
        // form a pair with current l.
        if (arr[l] + arr[r] < x)
        {
            result += (r - l);
            l++;
        }
  
        // Move to smaller value
        else
            r--;
    }
  
    return result;
}
  
// Driven code
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int n = sizeof(arr)/sizeof(int);
    int x = 7;
    cout << findPairs(arr, n, x);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count pairs in an array
// whose sum is less than given number x
class GFG {
      
    // Function to count pairs in array
    // with sum less than x.
    static int findPairs(int arr[], int n, int x)
    {
          
        int l = 0, r = n - 1;
        int result = 0;
      
        while (l < r)
        {
              
            // If current left and current
            // right have sum smaller than x,
            // the all elements from l+1 to r
            // form a pair with current l.
            if (arr[l] + arr[r] < x)
            {
                result += (r - l);
                l++;
            }
      
            // Move to smaller value
            else
                r--;
        }
      
        return result;
    }
      
    // Driver method
    public static void main(String[] args)
    {
          
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
        int n = arr.length;
        int x = 7;
          
        System.out.print(findPairs(arr, n, x));
    }
}
  
// This code is contributed by Anant Agarwal.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count pairs
# in an array whose sum is less
# than given number x
  
# Function to count pairs in array
# with sum less than x.
def findPairs(arr, n, x):
  
    l = 0; r = n-1
    result = 0
  
    while (l < r):
      
        # If current left and current
        # right have sum smaller than x,
        # the all elements from l+1 to r
        # form a pair with current l.
        if (arr[l] + arr[r] < x):
          
            result += (r - l)
            l += 1
          
  
        # Move to smaller value
        else:
            r -= 1
  
    return result
      
# Driver Code
arr = [1, 2, 3, 4, 5, 6, 7, 8]
n = len(arr)
x = 7
print(findPairs(arr, n, x))
  
# This code is contributed by Anant Agarwal.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count pairs in 
// an array whose sum is less
// than given number x
using System;
  
class GFG {
      
    // Function to count pairs in array
    // with sum less than x.
    static int findPairs(int []arr, int n,
                         int x)
    {
          
        int l = 0, r = n - 1;
        int result = 0;
      
        while (l < r)
        {
              
            // If current left and current
            // right have sum smaller than x,
            // the all elements from l+1 to r
            // form a pair with current l.
            if (arr[l] + arr[r] < x)
            {
                result += (r - l);
                l++;
            }
      
            // Move to smaller value
            else
                r--;
        }
      
        return result;
    }
      
    // Driver code
    public static void Main(String[] args)
    {
          
        int []arr = {1, 2, 3, 4, 5, 6, 7, 8};
        int n = arr.Length;
        int x = 7;
          
        Console.Write(findPairs(arr, n, x));
    }
}
  
// This code is contributed by parashar...

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to count pairs in an array
// whose sum is less than given number x
  
// Function to count pairs in array
// with sum less than x.
function findPairs($arr,$n,$x)
{
    $l = 0; 
    $r = $n - 1;
    $result = 0;
  
    while ($l < $r)
    {
          
        // If current left and current
        // right have sum smaller than x,
        // the all elements from l+1 to r
        // form a pair with current l.
        if ($arr[$l] + $arr[$r] < $x)
        {
            $result += ($r - $l);
            $l++;
        }
  
        // Move to smaller value
        else
            $r--;
    }
  
    return $result;
}
  
    // Driver Code
    $arr = array(1, 2, 3, 4, 5, 6, 7, 8);
    $n = sizeof($arr) / sizeof($arr[0]);
    $x = 7;
    echo findPairs($arr, $n, $x);
    return 0;
  
// This code is contributed by nitin mittal.
?>

chevron_right



Output:

6

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

Extension:
If array is unsorted, then we can sort the array first and then apply above method to solve in O(n Log n) time.

Related Articles:
Count all distinct pairs with difference equal to k
Count pairs with given sum

Reference: https://www.quora.com/Given-a-sorted-integer-array-and-number-z-count-all-pairs-x-y-in-the-array-so-that-x-+-y-z-Can-it-be-done-in-O-n

This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : parashar, nitin mittal



Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.