Closest difference of two array numbers to a given number
Filed under Deutsche Bank
Free read 3 of 3Confirm if elements can be repeated or if indices must be distinct (distinct elements required).
The question
Given a target number and an array of numbers, find two numbers from the array whose sum is closest to the given target.
Constraints
- 2 <= length of array <= 10^5
- -10^9 <= target, array elements <= 10^9
Examples
- Input
- arr = [10, 22, 28, 29, 30, 40], target = 54
- Output
- [22, 30]
- Why
- The sum of 22 and 30 is 52, which is closest to 54.
Approach
Confirm if elements can be repeated or if indices must be distinct (distinct elements required).
Check every possible pair of elements and find the minimum absolute difference to the target.
Sort the array and use two pointers (left at start, right at end). Move pointers inward based on whether the current sum is less than or greater than the target, tracking the closest difference.
Array with only two elements; exact match existing.
Solution
O(N log N) time, O(1) space
def closestTwoSum(arr, target):
arr.sort()
left, right = 0, len(arr) - 1
closest_diff = float('inf')
best_pair = ()
while left < right:
current_sum = arr[left] + arr[right]
diff = abs(current_sum - target)
if diff < closest_diff:
closest_diff = diff
best_pair = (arr[left], arr[right])
if current_sum < target:
left += 1
else:
right -= 1
return list(best_pair)
Tips
- What they are testing: Test with negative numbers, duplicates, and arrays with exactly two elements.
- Common mistake: Using a O(N^2) nested loop approach which fails on large inputs due to time limits.
Related Deutsche Bank questions
Collected from public candidate posts and coding forums. Updated Nov 2026.