Find a pair of elements with sum k (a+b=k) in unsorted array
class FindAPairWithSumK {
static int[] array;
// Time complexity : O(n^2). Assuming +ve numbers
// n-1 + n-2 + n-3 + .......+ 3 + 2 + 1 = n*(n-1)/2 = (n^2-n)/2 = n^2
static void findPair_bruteForce(int k) {
for(int i = 0; i < array.length-1; i++) {
for(int j = i+1; j < array.length; j++) {
if(array[i] + array[j] == k) {
System.out.println("Found pair (" + array[i] + ", " + array[j] + ")");
}
}
}
}
static void findPair_dp(int k) {
int largest = getMax();
int[] dp = new int[largest + 1];
for(int i = 0; i < array.length; i++) {
// Check if pair available
int pairIndex = k-array[i];
if(array[i] < k && dp[pairIndex] > 0) {
System.out.println("Found pair (" + array[i] + ", " + (k-array[i]) + ")");
}
dp[array[i]]++;
}
}
static int getMax() {
int largest = Integer.MIN_VALUE;
for(int i = 0; i < array.length; i++) {
if(array[i] > largest) {
largest = array[i];
}
}
return largest;
}
public static void main (String[] args) {
array = new int[] {6, 3, 8, 10, 16, 7, 5, 2, 9, 14};
int k = 10;
findPair_bruteForce(k);
findPair_dp(k);
}
}
Comments
Post a Comment