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
01+5 equals the target.
Example 2
{
"nums": [
2,
2
],
"target": 5
}Returns
1Two 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