All practice tasks

Coding (Algo)

Closest Pair Total

Two pointers · Medium

A batch planner chooses two different entries whose combined size is as close as possible to a requested total. The entries can have signed adjustments and are not guaranteed to be sorted. Only the absolute gap is needed.

Return the minimum absolute difference between target and the sum of two entries at distinct indexes.

Input

Call

  • Implement solve(input) and return the result. The provided adapter handles JSON input and output.

Input shape

A JSON object { "nums": number[], "target": number }.

Fields

  • nums is an unsorted integer array. target is an integer in [-2000000000,2000000000].

Output

Return value

  • Return a non-negative number, or null when fewer than two entries exist.
  • Equal values at different indexes may form a pair. The same index cannot be reused.
  • Return the gap, not a pair or its sum. Exact equality returns 0.

Constraints

  • At most 100000 values, each an integer in [-1000000000,1000000000].

Examples

Example 1

{
  "nums": [
    -4,
    1,
    5,
    8
  ],
  "target": 6
}

Returns

0

1+5 equals the target.

Example 2

{
  "nums": [
    2,
    2
  ],
  "target": 5
}

Returns

1

Two equal values at different indexes are valid.

Required complexity

O(n log(n + 1)) time and O(n) extra space for a non-mutating sort

What this task practices

Closest Pair Total is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as medium difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.

Sign in to startThe workspace and evaluation open after sign in.