1. Understand the Goal: The user wants a program to find all pairs in an array that sum up to a specific target value.
Identify Key Concepts:
Input: An array of numbers (integers) and a target sum (integer).
Output: Pairs of numbers from the array that add up to the target.
Constraints/Edge Cases:
Are duplicates allowed? (Usually yes, but need to handle how they are reported).
Is the array sorted? (Not usually assumed).
Do we return indices or values? (Values are standard, sometimes indices).
Time complexity vs. Space complexity.
Determine Approaches:
Approach 1: Brute Force (Nested Loops)
Iterate through each element i.
Iterate through each element j (where j>i).
Check if arr[i] + arr[j] == target.
Pros: Simple, no extra space (O(1)).
Cons: Slow (O(N2)).
Approach 2: Sorting + Two Pointers
Sort the array.
Use a left pointer at start and right pointer at end.
Sum = arr[left] + arr[right].
If Sum == Target, found pair. Move both (or handle duplicates).
If Sum < Target, increment left.
If Sum > Target, decrement right.
Pros:O(NlogN) time.
Cons: Modifies original array (unless copied). O(N) or O space depending on sort.
Approach 3: Hash Map (HashSet/Dictionary)
Iterate through the array.
Calculate difference = target - current_element.
Check if difference exists in the Set.
If yes, found pair.
Add current_element to Set.
Pros: Fast (O(N) time).
Cons: Uses extra space (O(N)).
Select the Best Approach for Demonstration:
The Hash Map approach is generally preferred for interview/algorithm questions due to its linear time complexity.
I will provide the Hash Map solution as the primary efficient solution, but I might mention the Sorting approach as an alternative. Let's stick to Python, Java, and C++ as they are the most common languages requested.
Drafting the Code (Mental or Scratchpad):
Python:
python
def find_pairs(arr, target):
pairs = []
seen = set()
for num in arr:
complement = target - num
if complement in seen:
pairs.append((complement, num)) # Order matters for output consistency
seen.add(num)
return pairs
Java:
java
import java.util.*;
public class PairSum {
public static List<int[]> findPairs(int[] arr, int target) {
List<int[]> result = new ArrayList<>();
Set<Integer> seen = new HashSet<>();
for (int num : arr) {
int complement = target - num;
if (seen.contains(complement)) {
result.add(new int[]{complement, num});
}
seen.add(num);
}
return result;
}
}
The user didn't specify a language. It's best to provide a Python solution (most readable) and perhaps a Java or C++ one for completeness.
I should explain the logic (Time/Space complexity).
I need to decide how to handle duplicates (e.g., [2, 2, 2] target 4). The standard hash set approach usually prints the pair once per valid partner found. If the input is [2, 2, 2] and target is 4:
2, set={}, complement=2. Not in set. Add 2.
2, set={2}, complement=2. In set. Pair found. Add 2.
2, set={2}, complement=2. In set. Pair found. Add 2.
Wait, if I keep adding 2 to the set, does it create multiple pairs?
Yes.
If I want unique pairs, the Set needs to store counts or I need a logic change.
Standard problem usually implies finding pairs based on indices, so [2, 2, 2] usually yields (2,2) at index 0,1 and (2,2) at index 0,2 and (2,2) at index 1,2. The O(N) hash map approach yields pairs as it iterates.
Refined Python Logic: Iterate num. Complement = target - num. If complement in seen: append pair. Add num to seen.
1, comp 5. Match (5,1). add 1.
Wait, step 4 finds a match with the second 5.
Is this desired? Usually, yes. The elements exist.
If we want unique pairs of values (ignoring indices), we'd need a frequency map or sorting.
However, the "HashSet Complement" trick is the standard "Two Sum" variant solution. I will proceed with that but clarify that it finds pairs based on the current element matching a previously seen element.
Let's write the Python code clearly.
python
def find_pairs_with_sum(arr, target):
pairs = []
seen = set()
for num in arr:
complement = target - num
if complement in seen:
pairs.append((complement, num))
seen.add(num)
return pairs
This looks solid. I will generate the response based on this.
Here are three different solutions in Python, Java, and C++.
The most efficient approach uses a Hash Set (or Hash Map). This allows us to find the pairs in O(N) time complexity, which is much faster than checking every possible pair combination (which would be O(N2)).
1. Python Solution
This solution uses a Python set to store numbers we have seen so far. As we iterate through the array, we calculate the complement needed to reach the target. If that complement is already in our set, we have found a pair.
python
def find_pairs(arr, target):
seen = set()
pairs = []
for num in arr:
complement = target - num
# Check if the complement exists in the set
if complement in seen:
pairs.append((complement, num))
# Add the current number to the set for future checks
seen.add(num)
return pairs
# Example Usage
if __name__ == "__main__":
my_array = [1, 5, 7, -1, 5]
target_sum = 6
result = find_pairs(my_array, target_sum)
print(f"Array: {my_array}")
print(f"Target Sum: {target_sum}")
print(f"Found Pairs: {result}")
2. Java Solution
In Java, we use a HashSet to achieve the same logic.
java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PairSum {
public static List<String> findPairs(int[] arr, int target) {
Set<Integer> seen = new HashSet<>();
List<String> pairs = new ArrayList<>();
for (int num : arr) {
int complement = target - num;
if (seen.contains(complement)) {
pairs.add("(" + complement + ", " + num + ")");
}
seen.add(num);
}
return pairs;
}
public static void main(String[] args) {
int[] myArray = {1, 5, 7, -1, 5};
int targetSum = 6;
List<String> result = findPairs(myArray, targetSum);
System.out.println("Target Sum: " + targetSum);
System.out.println("Found Pairs: " + result);
}
}
3. C++ Solution
In C++, we use std::unordered_set from the Standard Template Library (STL).
cpp
#include <iostream>
#include <vector>
#include <unordered_set>
#include <string>
void findPairs(const std::vector<int>& arr, int target) {
std::unordered_set<int> seen;
std::cout << "Pairs with sum " << target << ":" << std::endl;
for (int num : arr) {
int complement = target - num;
// Check if complement is already in the set
if (seen.find(complement) != seen.end()) {
std::cout << "(" << complement << ", " << num << ")" << std::endl;
}
// Insert current number into set
seen.insert(num);
}
}
int main() {
std::vector<int> myArray = {1, 5, 7, -1, 5};
int targetSum = 6;
findPairs(myArray, targetSum);
return 0;
}
Logic Explanation
Initialize an empty Set: This will store numbers we have iterated over.
Iterate: Loop through each number in the array.
Calculate Complement: For the current number x, calculate complement = target - x.
Check: Does the complement exist in our Set?
Yes: We have found a pair (complement, x). Add it to our list of results.
No: Do nothing yet.
Update: Add the current number x to the Set so it can act as a complement for future numbers.
Complexity Analysis
Time Complexity:O(N), where N is the number of elements in the array. We traverse the array once, and set operations take O(1) on average.
Space Complexity:O(N), because in the worst case (no pairs found), we might store all N elements in the set.