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:
O(n)a[i], find a[i]+k in the array using binary search :O(log n)Total Time: O(n logn)
O(n) Solution:
O(n)O(1)Total Time: O(n)
Space: O(n)
But he wants an O(n) solution with O(1) extraspace. Anyone have any idea?
Make two index pointers - Left and Right, initialize both to the start of array (0). If a[Left] + k > a[Right], increment Right, else increment Left. Stop when equal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With