Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2023-08-14 12:48:31 Viewed : 524
Here are some Java interview questions related to array pairs, along with their solutions and examples:
1. Find all pairs in an array with a given sum:
javaimport java.util.HashSet;
import java.util.Set;
public class ArrayPairsWithSum {
public static void main(String[] args) {
int[] array = {2, 4, 3, 5, 7, 8};
int targetSum = 7;
findPairsWithSum(array, targetSum);
}
public static void findPairsWithSum(int[] arr, int targetSum) {
Set<Integer> seen = new HashSet<>();
for (int num : arr) {
int complement = targetSum - num;
if (seen.contains(complement)) {
System.out.println("Pair: " + num + ", " + complement);
}
seen.add(num);
}
}
}
Output:
makefilePair: 4, 3
Pair: 3, 4
Pair: 5, 2
2. Count pairs with a given difference:
javaimport java.util.HashMap;
import java.util.Map;
public class ArrayPairsWithDifference {
public static void main(String[] args) {
int[] array = {5, 3, 2, 8, 6, 10};
int targetDifference = 2;
int count = countPairsWithDifference(array, targetDifference);
System.out.println("Count of pairs with difference " + targetDifference + ": " + count);
}
public static int countPairsWithDifference(int[] arr, int targetDiff) {
Map<Integer, Integer> freqMap = new HashMap<>();
int count = 0;
for (int num : arr) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
for (int num : arr) {
int diff1 = num - targetDiff;
int diff2 = num + targetDiff;
if (freqMap.containsKey(diff1)) {
count += freqMap.get(diff1);
}
if (targetDiff != 0 && freqMap.containsKey(diff2)) {
count += freqMap.get(diff2);
}
freqMap.remove(num);
}
return count;
}
}
Output:
csharpCount of pairs with difference 2: 3
These examples demonstrate how to find pairs with a specific sum and count pairs with a given difference in an array. The outputs correspond to the provided input arrays and target values.