Problem: Given an array of integers, write a function to determine if there exists a pair of integers in the array such that their sum is equal to a given target value. If such a pair exists, return True; otherwise, return False.
Function signature: fun has_pair_with_sum(nums: List[int], target: int) -> bool:
Explanation: The problem asks us to find if there is a pair of integers in the given array that adds up to the target value. We can solve this problem by using a hash set to store the visited values. As we iterate over the array, we check if the difference between the current element and the target value exists in the hash set. If it does, it means that we have found a pair of integers that adds up to the target value, and we can return True. Otherwise, we add the current element to the hash set and continue iterating over the array. If we reach the end of the array without finding a pair, we can return False.
Test case 1:
Input: nums = [2, 7, 11, 15], target = 9
Output: True
Explanation: The pair (2, 7) adds up to the target value of 9.
Test case 2:
Input: nums = [3, 6, 8, 12], target = 5
Output: False
Explanation: There is no pair of integers in the array that adds up to the target value of 5.
here’s the Kotlin code for the problem:
fun hasPairWithSum(nums: List<Int>, target: Int): Boolean {
val visited = mutableSetOf<Int>()
for (num in nums) {
val complement = target - num
if (complement in visited) {
return true
}
visited.add(num)
}
return false
}
fun main() {
val nums = listOf(2, 7, 11, 15)
val target = 9
val hasPair = hasPairWithSum(nums, target)
if (hasPair) {
println("There exists a pair of integers in $nums that adds up to $target")
} else {
println("There does not exist a pair of integers in $nums that adds up to $target")
}
}