Skip to content

Instantly share code, notes, and snippets.

@deyindra
Last active August 29, 2017 21:46
Show Gist options
  • Save deyindra/9bb4d808712563e6044280d93bb31893 to your computer and use it in GitHub Desktop.
Save deyindra/9bb4d808712563e6044280d93bb31893 to your computer and use it in GitHub Desktop.
Find pair from Sorted Array
//Time complexity O(N), Space Complexity O(1)
public static List<Pair<Integer, Integer>> getPairs(int[] array, final int sum){
int start = 0;
int end = array.length-1;
List<Pair<Integer, Integer>> list = new ArrayList<>();
while (start < end){
int resultSum = array[start] + array[end];
if(resultSum < sum){
start++;
}else if (resultSum > sum){
end --;
}else{
list.add(Pair.of(array[start], array[end]));
start ++ ;
end --;
}
}
return list;
}
package org.idey.algo.ds;
import java.util.Map;
public interface Pair<K,V> extends Map.Entry<K,V> {
@Override
default V setValue(V value) {
throw new UnsupportedOperationException("Invalid operation");
}
static <K,V> Pair<K,V> of(K key, V value) {
return new PairImpl<>(key,value);
}
class PairImpl<K,V> implements Pair<K,V>{
private K key;
private V value;
private PairImpl(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment