Given an integer k and an sorted array A (can consist of both positive and negative numbers), output 2 integers from A such that a-b=k in O(n) time and O(1) space
O(n logn) Solution:
- Traverse the array:
O(n) - For element
a[i], finda[i]+kin the array using binary search :O(log n)
Total Time: O(n logn)
O(n) Solution:
- Store all elements of the array in a Hash Table:
O(n) - For element a[i], check whether a[i]+k in the hash table :
O(1)
Total Time: O(n)
Space: O(n)
But he wants an O(n) solution with O(1) extraspace. Anyone have any idea?
The idea is to use two pointers into the array say a and b.
Originally they both point to the beginning (
a=b=0).If
ar[a]+k < ar[b], then you advance a.If
ar[a]+k > ar[b], then you advance b.If
ar[a]+k == ar[b], then you have found a solution.That’s
O(n)time andO(1)space.