Thursday, February 4, 2021

How to find pair of two numbers whose difference equivalent to given key less than N square time complexity


  
public class DifferencePair {

	public static void main(String[] args) {
		int arr[] = {1,8,10,40,30,60,50}; 
		int n = 10;  
		findPair(arr,n);

	}

	private static void findPair(int[] arr, int n) {
		ArrayList<Integer> numbers = new ArrayList<>();
		boolean status = false;
		for(int num : arr) {
			
			if(numbers.contains((num-n))){
				status=true;
				System.out.println("Pair Found: "+"( "+(num-n)+", "+ num+" )"); 
			}
			
			if (numbers.contains((num+n))) {
				status=true;
				System.out.println("Pair Found: "+"( "+(num+n)+", "+ num+" )"); 
			}

			numbers.add(num);
		}
		if(!status)
			System.out.print("No such pair"); 
	}

}

Output:-
Pair Found: ( 40, 30 )
Pair Found: ( 40, 50 )
Pair Found: ( 60, 50 )

No comments:

Post a Comment

How to find middle node of LinkedList without using extra memory in java

To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This al...