Coding Challenge Day- 17: Problem 1: How to find all pairs in array integer whose sum is equal to a given number

Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 17: Problem 1! Be sure to post your answers, queries etc in the comments!

Problem: How to find all pairs in array integer whose sum is equal to a given number

Sample input:

int array[]= {1,2,3,4};
int sum=5;


Output:

Integr Array: [1, 2, 3, 4]
Pairs having sum = 5
(3, 2)
(4, 1)

Solutions:

So I solved this in two ways:

Approach 1: By adding each number with all other elements and checking if their sum is equal to the given number.

package array;

import java.util.Arrays;

public class Program011find_sum_pair_2 {
	
	public static void find_pair (int [] array, int sum){
		
		int length= array.length;
		for(int i=0; i<length; i++){
			int a= array[i];
			for(int j=0; j<length; j++){
				if(array[j]+a==sum){
					System.out.printf("( %d, %d ) %n", a,array[j]);
				}
			}
		}
	}
	
	public static void main (String [] args){
		int array[]= {1,2,3,4};
		int sum=5;
		
		System.out.println("Integr Array: "+ Arrays.toString(array));
    	System.out.println("Pairs having sum = " + sum);
    	
    	find_pair(array, sum);
	}

}

Approach 2: By using HashSet

package array;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


public class Program011find_sum_pair {

	    public static void find_pair(int[] array, int sum){
	        if(array.length < 2){
	            return;
	        }        
	        Set set = new HashSet(array.length);
	        
	        for(int i : array){
	            int target = sum - i;
	            if(!set.contains(target)){
	                set.add(i);
	            }else {
	                System.out.printf("(%d, %d) %n", i, target);
	            }
	        }
	    }
	    
	    public static void main(String args[]) {
	    	int array[]= {1,2,3,4};
	    	int sum=5;
	    	
	    	System.out.println("Integr Array: "+ Arrays.toString(array));
	    	System.out.println("Pairs having sum = " + sum);
	    	
	    	find_pair(array, sum);
	  
	 }

}

Download Code (Approach 1)
Download Code(Approach 2)

Happy Learning!!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close