Find Pairs in Array with Given Sum in Java

Pairs in Array with Given Sum in Java

On this page, we will look into a coding question where we will learn how to Find Pairs in Array with Given Sum in Java Programing Language. There might be different approaches to solve this question, one you will find here. If your approach is a bit different post it in the comment section.

Pair Symbol

Find Pairs in Array with given Sum in Java

To find pairs in an array with a given sum in Java, we can use two methods

  1. Brute Force (Time complexity: O(n^2) )
  2. Using Sorting (Time complexity: O(n log n) )
Both methods have their own pros and cons. The brute force method can be slow for large arrays but it is very simple and easy to implement . The sorting method is faster for large arrays, but requires extra space for sorting and modifying the original array.
Find-Pairs-in-Array-with-given-Sum-in-Java

Method 1 : Brute Force Method

  • In this approach, we check every pair of elements in the array to see if their sum is equal to the given target sum.
  • This method has a time complexity of O(n^2) as we have to compare each element with every other element

Java code for brute force

Run
// Java implementation to
// print pairs with given sum.

public class Main
{
    static void pairssum(int a[], int size, int sum)
    {
        System.out.print("The pairs present are : ");
        //traverse through the array to find pairs
        for (int i = 0; i < size; i++)
            for (int j = i + 1; j < size; j++)
                if (a[i] + a[j] == sum)
                    System.out.print("(" + a[i] + ", " + a[j]+ ") ");
    }

    // Driver Code
    public static void main(String[] arg)
    {
        int a[] = { 5, 2, 3, 4, 1, 6, 7 };
        int size = a.length;
        int sum = 7;
        pairssum(a, size, sum);
    }
}

OUTPUT:
The pairs present are : (5, 2) (3, 4) (1, 6)

Method 2 : Sorting Method

  • The array is first sorted in ascending order in the sorting technique.
  • Then, we employ two pointers, one of which points to the first element and the other to the last element.
  • These two pointers values are added, and we then check to see if the result equals the specified sum.
    The left pointer is increased if the value is less than the total, and the right pointer is decreased if the value is higher.
  • This method has a time complexity of O(n log n) due to the sorting algorithm used.

Java code for sorting method

Run
import java.util.*;

public class Main
{
    public static void findPairs(int arr[], int n, int targetSum)
    {
        Arrays.sort(arr);
        int left = 0, right = n - 1;
        System.out.print("The pairs present are : ");
        while (left < right)
        {
            int currSum = arr[left] + arr[right];
            if(currSum == targetSum)
	        {
	            System.out.print("(" + arr[left] + ", "+ arr[right] + ") ");
	            left++;
	            right--;
	        }
            else if (currSum < targetSum)
	        {
	            left++;
	        }
            else
	        {
	            right--;
	        }
        }
    }
    
    public static void main(String args[])
    {
        int arr[] = { 5, 8, 1, 4, 6, 3, 2, 7 };
        int n = arr.length;
        int targetSum = 10;
        findPairs (arr, n, targetSum);
    }
}
OUTPUT:
The pairs present are : (2, 8) (3, 7) (4, 6)

Prime Course Trailer

Related Banners

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Arrays

  • Introduction to Arrays – CC++ | Java
  • Introduction to 2-D Arrays – CC++ Java
  • Sorting of Array – C | C++ | Java
  • Array Rotation – CC++ | Java
  • Reverse an array or string- CC++ | Java
  • Find pairs in array with given sum – CC++ | Java
  • Sort the array in Waveform – CC++ | Java
  • Majority Element in Array – CC++ | Java
  • Boyer-Moore’s Voting Algorithm – CC++ | Java
  • K-pairs with smallest sum in 2 arrays – C | C++ | Java
  • Largest Sum Contigous SubArray – CC++ | Java
  • Maximum Average Sub-array of K length – CC++ | Java
  • Size of sub-array with max sum – CC++ | Java
  • Sub-array with given sum – CC++ | Java
  • Triplet that sum to a given value – CC++ | Java
  • Segregate 0’s and 1’s in array – CC++ | Java
  • Segregate 0’s 1’s and 2’s in array – CC++ | Java
  • Sort elements in array by frequency – CC++ | Java
  • Finding pythagorean triplets in an array – CC++ | Java
  • Reorder array using given indexes – CC++ | Java
  • Merging two sorted arrays – CC++ | Java
  • Minimum number of Merge Operations to make an Array Palindrome – CC++ | Java
  • Find Zeros to be Flipped so that number of Consecutive 1’s is maximized – CC++ | Java