โ† Deutsche Bank questions
CodingMediumReported in a candidate post, Aug 2021

Closest difference of two array numbers to a given number

Filed under Deutsche Bank

Free read 3 of 3

Confirm 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

  1. Confirm if elements can be repeated or if indices must be distinct (distinct elements required).

Solution

O(N log N) time, O(1) space

Python
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.