Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find pair of numbers whose difference is an input value 'k' in an unsorted array

As mentioned in the title, I want to find the pairs of elements whose difference is K

example k=4 and a[]={7 ,6 23,19,10,11,9,3,15}
output should be :
   7,11
   7,3
   6,10
   19,23
   15,19
   15,11

I have read the previous posts in SO " find pair of numbers in array that add to given sum"

In order to find an efficient solution, how much time does it take? Is the time complexity O(nlogn) or O(n)? I tried to do this by a divide and conquer technique, but i'm not getting any clue of exit condition...

If an efficient solution includes sorting the input array and manipulating elements using two pointers, then I think I should take minimum of O(nlogn)...

Is there any math related technique which brings solution in O(n). Any help is appreciated..

like image 519
Imposter Avatar asked May 04 '12 14:05

Imposter


People also ask

How do I find a number in an unsorted array?

Sequential Search. If you want to find the position in an unsorted array of n integers that stores a particular value, you cannot really do better than simply looking through the array from the beginning and move toward the end until you find what you are looking for. This algorithm is called sequential search.

How do you find the difference between numbers in an array?

Solution StepsDeclare an extra memory diff[n-1] of size n-1 to store differences of adjacent elements from index 0 to n-1. We run a loop from 0 to n - 2 to store differences in diff[n - 1]. Now we calculate and return the maximum subarray sum of diff[] array. We can find this value in O(n) time and O(1) space.

How do you find a pair in an array?

In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1.

How do you find the two numbers whose difference is minimum among the set of numbers?

Find smallest and largest element in the list. The difference smallest-largest will be minimum.


1 Answers

You can do it in O(n) with a hash table. Put all numbers in the hash for O(n), then go through them all again looking for number[i]+k. Hash table returns "Yes" or "No" in O(1), and you need to go through all numbers, so the total is O(n). Any set structure with O(1) setting and O(1) checking time will work instead of a hash table.

like image 148
Sergey Kalinichenko Avatar answered Oct 08 '22 21:10

Sergey Kalinichenko