Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Pairs with sum greater than 0 in an array
Next article icon

Pairs with sum greater than 0 in an array

Last Updated : 29 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[] of size N, the task is to find the number of distinct pairs in the array whose sum is > 0.

Examples: 

Input: arr[] = { 3, -2, 1 } 
Output: 2 
Explanation: There are two pairs of elements in the array {3, -2}, {3, 1} whose sum is positive.

Input: arr[] = { -1, -1, -1, 0 } 
Output: 0 
Explanation: There are no pairs of elements in the array whose sum is positive. 

Table of Content

  • [Naive Approach] - Using Nested Loops - O(n^2) Time and O(1) space
  • [Expected Approach] - Using Sorting and Two Pointer - O(n * log(n)) Time and O(1) Space  

[Naive Approach] - Using Nested Loops - O(n^2) Time and O(1) space

The idea for this naive approach is to use nested loops to check all possible pairs to find the unique pairs of elements in the array with the sum greater than 0.

C++
#include <bits/stdc++.h> using namespace std;  int findNumOfPair(vector<int>& arr) {     int count = 0;     int n = arr.size();      // Checking each pair     for (int i = 0; i < n; i++) {         for (int j = i + 1; j < n; j++) {             if (arr[i] + arr[j] > 0) {                 count++;             }         }     }     return count; }  int main() {     vector<int> arr = {3, -2, 1};     cout << findNumOfPair(arr) << endl;     return 0; } 
Java
import java.util.Arrays;  public class Main {     public static int findNumOfPair(int[] arr) {         int count = 0;         int n = arr.length;          // Checking each pair         for (int i = 0; i < n; i++) {             for (int j = i + 1; j < n; j++) {                 if (arr[i] + arr[j] > 0) {                     count++;                 }             }         }         return count;     }      public static void main(String[] args) {         int[] arr = {3, -2, 1};         System.out.println(findNumOfPair(arr));     } } 
Python
def findNumOfPair(arr):     count = 0     n = len(arr)      # Checking each pair     for i in range(n):         for j in range(i + 1, n):             if arr[i] + arr[j] > 0:                 count += 1                      return count  arr = [3, -2, 1] print(findNumOfPair(arr)) 
C#
using System;  class Program {     public static int FindNumOfPair(int[] arr) {         int count = 0;         int n = arr.Length;          // Checking each pair         for (int i = 0; i < n; i++) {             for (int j = i + 1; j < n; j++) {                 if (arr[i] + arr[j] > 0) {                     count++;                 }             }         }         return count;     }      static void Main() {         int[] arr = {3, -2, 1};         Console.WriteLine(FindNumOfPair(arr));     } } 
JavaScript
function findNumOfPair(arr) {     let count = 0;     const n = arr.length;      // Checking each pair     for (let i = 0; i < n; i++) {         for (let j = i + 1; j < n; j++) {             if (arr[i] + arr[j] > 0) {                 count++;             }         }     }     return count; }  const arr = [3, -2, 1]; console.log(findNumOfPair(arr)); 

Output
2 

[Expected Approach] - Using Sorting and Two Pointer - O(n * log(n)) Time and O(1) Space  

The idea is to use the concept of sorting and two pointer technique. The approach first sorts the array, traverses array from both ends, i = 0, j = arr.size() - 1

  • If (arr[i] + arr[j]) > 0, then arr[j] forms a pair with all elements from i to j-1.
  • If (arr[i] + arr[j]) <= 0, then arr[i] cannot form a pair with sum greater than 0 with any element from index i+1 to j. So we simply do i = i + 1.
C++
#include <bits/stdc++.h> using namespace std;  int countPairs(vector<int>& arr) {          // Sort the array     sort(arr.begin(), arr.end());          // Traverse from both corners using two     // pointers     int i = 0, j = arr.size() - 1, res = 0;     while (i < j) {         if (arr[i] + arr[j] > 0) {             res += (j - i);             j--;         } else {             i++;         }     }     return res; }  int main() {     vector<int> arr = {3, -2, 1};     cout << countPairs(arr) << endl;      return 0; } 
Java
import java.util.Arrays;  public class Main {     public static int countPairs(int[] arr) {                  // Sort the array         Arrays.sort(arr);                  // Traverse from both corners using two pointers         int i = 0, j = arr.length - 1, res = 0;         while (i < j) {             if (arr[i] + arr[j] > 0) {                 res += (j - i);                 j--;             } else {                 i++;             }         }         return res;     }      public static void main(String[] args) {         int[] arr = {3, -2, 1};         System.out.println(countPairs(arr));     } } 
Python
def count_pairs(arr):          # Sort the array     arr.sort()          # Traverse from both corners using two pointers     i, j, res = 0, len(arr) - 1, 0     while i < j:         if arr[i] + arr[j] > 0:             res += (j - i)             j -= 1         else:             i += 1     return res  if __name__ == '__main__':     arr = [3, -2, 1]     print(count_pairs(arr)) 
C#
using System; using System.Linq;  class Program {     public static int CountPairs(int[] arr) {                  // Sort the array         Array.Sort(arr);                  // Traverse from both corners using two pointers         int i = 0, j = arr.Length - 1, res = 0;         while (i < j) {             if (arr[i] + arr[j] > 0) {                 res += (j - i);                 j--;             } else {                 i++;             }         }         return res;     }      static void Main() {         int[] arr = {3, -2, 1};         Console.WriteLine(CountPairs(arr));     } } 
JavaScript
function countPairs(arr) {          // Sort the array     arr.sort((a, b) => a - b);          // Traverse from both corners using two pointers     let i = 0, j = arr.length - 1, res = 0;     while (i < j) {         if (arr[i] + arr[j] > 0) {             res += (j - i);             j--;         } else {             i++;         }     }     return res; }  const arr = [3, -2, 1]; console.log(countPairs(arr)); 

Output
2

Next Article
Pairs with sum greater than 0 in an array

S

shivamsinghal1012
Improve
Article Tags :
  • Greedy
  • Searching
  • Sorting
  • Competitive Programming
  • DSA
  • Arrays
  • two-pointer-algorithm
Practice Tags :
  • Arrays
  • Greedy
  • Searching
  • Sorting
  • two-pointer-algorithm

Similar Reads

    Number of pairs in an array such that product is greater than sum
    Given a array a[] of non-negative integers. Count the number of pairs (i, j) in the array such that a[i] + a[j] < a[i]*a[j]. (the pair (i, j) and (j, i) are considered same and i should not be equal to j) Examples: Input : a[] = {3, 4, 5} Output : 3 Pairs are (3, 4) , (4, 5) and (3,5) Input : a[]
    8 min read
    Print all pairs in an unsorted array with equal sum
    Given an unsorted array A[]. The task is to print all unique pairs in the unsorted array with equal sum. Note: Print the result in the format as shown in the below examples. Examples: Input: A[] = { 6, 4, 12, 10, 22, 54, 32, 42, 21, 11} Output: Pairs : ( 4, 12) ( 6, 10) have sum : 16 Pairs : ( 10, 2
    13 min read
    Find all pairs with a given sum in two unsorted arrays
    Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to a given value X.Examples: Input: arr1[] = {-1, -2, 4, -6, 5, 7}, arr2[] = {6, 3, 4, 0} , x = 8Output: 4 4 5 3Input: arr1[] = {1, 2, 4, 5, 7}, arr2[] = {5, 6, 3, 4, 8}, x = 9Output: 1
    13 min read
    Check if a subarray exists with sum greater than the given Array
    Given an array of integers arr, the task is to check if there is a subarray (except the given array) such that the sum of its elements is greater than or equal to the sum of elements of the given array. If no such subarray is possible, print No, else print Yes.Examples: Input: arr = {5, 6, 7, 8} Out
    7 min read
    2 Sum - Count Pairs with given Sum in Sorted Array
    Given a sorted array arr[] and an integer target, the task is to find the number of pairs in the array whose sum is equal to target.Examples: Input: arr[] = [-1, 1, 5, 5, 7], target = 6Output: 3Explanation: Pairs with sum 6 are (1, 5), (1, 5) and (-1, 7). Input: arr[] = [1, 1, 1, 1], target = 2Outpu
    9 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