i = 1; j = n; while(i != j) { if(A[i] + A[j] == M) break; else if(A[i] + A[j] < M) i++; else j--; }
i=1; j=n; if((a[1]+a[2]>M) OR (A[n]+a[n-1]<M)) print Element not found else { while(a[i]+a[j]!=M) { if(a[i]+[J]<M) i++; else j--; } print i ,j }
can u explain ur logic once again ,its really hard for me to understand.
what is the meaning of this line:
First use hash table, to has first half no of this array.
First use hash table, to has first half no of this array. You can do it using O(1) time.
Then check for a-A[k], where n/2<=k<=n, by lookup using Hash table. You can do this is O(1) each lookup( Ideal Time compexity).
Suppose there are 10 elements in an array and only by adding A[1] and A[2] we are getting a.
Your code will output there is no such pair exist.
Sir, I think both of your points are wrong. But the time complexity will be O(n). I tried to explain with code.
our works become simpler when we read the word its in increasing order...keep on adding the 2 consecutive numbers
case 1:the sum is less than given element then continue
case 2:the sum is greater than given element then terminate and return -1
case 3:the sum is equal to given element then terminate and return the position of i and j
64.3k questions
77.9k answers
243k comments
79.7k users