๐ง Find a Pair with a Given Sum
โ Simple Statement
Given an array of integers and a target value, check if there's a pair of elements in the array whose sum equals the target.
๐งฉ Example
Input: nums = [8, 7, 2, 5, 3, 1], target = 10
Output: True (Because 7 + 3 = 10)
๐งพ Pseudocode (Optimal โ Using Hash Map)
create empty map
for each number in array:
if (target - current number) exists in map:
return true
add current number to map
return false
๐งช Stack Trace (Optimal Method)
Input: [8, 7, 2, 5, 3, 1]
, target = 10
Step | Index | Value | Map | target - value | Found? |
---|---|---|---|---|---|
1 | 0 | 8 | {} | 2 | โ |
2 | 1 | 7 | {8} | 3 | โ |
3 | 2 | 2 | {8, 7} | 8 | โ |
๐ Python Code
Brute-force (O(nยฒ))
def find_pair_brute(nums, target):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return True
return False
Optimal (O(n))
def find_pair_optimal(nums, target):
seen = {}
for i, num in enumerate(nums):
if target - num in seen:
return True
seen[num] = i
return False
๐ JavaScript Code
Brute-force
function findPairBrute(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) return true;
}
}
return false;
}
Optimal
function findPairOptimal(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
if (seen.has(target - nums[i])) return true;
seen.set(nums[i], i);
}
return false;
}