
Java Programming
May 27, 2025 at 09:50 AM
*Java Coding Challenge: Part 14*
*Challenge:*
Given an array of integers and a target number, print all unique pairs that sum up to the target.
*Example:*
Input: {2, 4, 3, 5, 7, 8, -1}, Target = 7
*Output:*
(2, 5)
(4, 3)
(-1, 8)
*Approach:*
Use a HashSet to store visited numbers and check if the complement (target - num) exists.
*Java Code:*
import java.util.HashSet;
public class PairSum {
public static void main(String[] args) {
int[] arr = {2, 4, 3, 5, 7, 8, -1};
int target = 7;
findPairs(arr, target);
}
public static void findPairs(int[] arr, int target) {
HashSet seen = new HashSet<>();
for (int num : arr) {
int complement = target - num;
if (seen.contains(complement)) {
System.out.println("(" + complement + ", " + num + ")");
}
seen.add(num);
}
}
}
This solution avoids duplicates and has O(n) time complexity.
If you want to return all pairs as a list or array, just store them instead of printing.
*React ❤️ for Part-15*
❤️
👍
❤
🇮🇳
♥
😂
💙
🖕
😢
😮
143