Algorithm:
1.start using two pointer p1 & p2 which pints 1st & next element repectively
2.initialize p1=0 & p2=1;
3.loop down over array
a.check if their difference a[p2]-a[p1]==num if yes the print then & increment
both p1 & p2;
b.else if their difference a[p2]-a[p1]>num is less then number then increment j
only.
c.else if their difference a[p2]-a[p1]
int main()
{
int arr[9]={10, 14, 17, 22, 23, 25, 26, 27, 45};
int i = 0;
int j = 1;
int num = 2;
while(j<9) { if(arr[j] - arr[i] == num) { printf("two numbers whose difference is equal to num are %d %d",arr[i],arr[j]); i++;j++; } else if((arr[j]-arr[i])>num)
i++;
else if((arr[j]-arr[i])
}
}
Suggested by Rajcools
Time Complexity O(N)
Space complexity O(1)
Run Here https://ideone.com/zbdDh
1 comment :
This solution works only if your array is sorted
Post a Comment