Like 2Sum, instead of maintaining a hashmap (which would be memory), try to use constant space. Now, unlike 2Sum the input array is sorted. Sure you can sort the array in the original 2Sum too, but it’s a famous problem for hashmaps.
Here, you must find a pair of numbers that would sum up to the target
. Since the array is sorted, you know that the elements on the LHS of array are smaller than the elements in the RHS. That’s what we want. We can use the two pointer
technique and initialize a pointer at the start and a pointer at the end of the array.
Code:
Java
Big O Analysis
-
Runtime
The runtime complexity here is
O(N)
as since we would be iterating the array atleast once. -
Memory
The memory usage is
O(1)
since we are not using any extra datastructure.
— A