Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an integer array nums and an integer goal.
You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).
Return the minimum possible value of abs(sum - goal).
Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.
Example 1:
Input: nums = [5,-7,3,5], goal = 6 Output: 0 Explanation: Choose the whole array as a subsequence, with a sum of 6. This is equal to the goal, so the absolute difference is 0.
Example 2:
Input: nums = [7,-9,15,-2], goal = -5 Output: 1 Explanation: Choose the subsequence [7,-9,-2], with a sum of -4. The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.
Example 3:
Input: nums = [1,2,3], goal = -7 Output: 7
Constraints:
1 <= nums.length <= 40-107 <= nums[i] <= 107-109 <= goal <= 109Problem summary: You are given an integer array nums and an integer goal. You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal). Return the minimum possible value of abs(sum - goal). Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Dynamic Programming · Bit Manipulation
[5,-7,3,5] 6
[7,-9,15,-2] -5
[1,2,3] -7
minimize-the-difference-between-target-and-chosen-elements)partition-array-into-two-arrays-to-minimize-sum-difference)minimum-operations-to-form-subsequence-with-target-sum)find-the-sum-of-subsequence-powers)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1755: Closest Subsequence Sum
class Solution {
public int minAbsDifference(int[] nums, int goal) {
int n = nums.length;
List<Integer> lsum = new ArrayList<>();
List<Integer> rsum = new ArrayList<>();
dfs(nums, lsum, 0, n / 2, 0);
dfs(nums, rsum, n / 2, n, 0);
rsum.sort(Integer::compareTo);
int res = Integer.MAX_VALUE;
for (Integer x : lsum) {
int target = goal - x;
int left = 0, right = rsum.size();
while (left < right) {
int mid = (left + right) >> 1;
if (rsum.get(mid) < target) {
left = mid + 1;
} else {
right = mid;
}
}
if (left < rsum.size()) {
res = Math.min(res, Math.abs(target - rsum.get(left)));
}
if (left > 0) {
res = Math.min(res, Math.abs(target - rsum.get(left - 1)));
}
}
return res;
}
private void dfs(int[] nums, List<Integer> sum, int i, int n, int cur) {
if (i == n) {
sum.add(cur);
return;
}
dfs(nums, sum, i + 1, n, cur);
dfs(nums, sum, i + 1, n, cur + nums[i]);
}
}
// Accepted solution for LeetCode #1755: Closest Subsequence Sum
func minAbsDifference(nums []int, goal int) int {
n := len(nums)
lsum := make([]int, 0)
rsum := make([]int, 0)
dfs(nums[:n/2], &lsum, 0, 0)
dfs(nums[n/2:], &rsum, 0, 0)
sort.Ints(rsum)
res := math.MaxInt32
for _, x := range lsum {
t := goal - x
l, r := 0, len(rsum)
for l < r {
m := int(uint(l+r) >> 1)
if rsum[m] < t {
l = m + 1
} else {
r = m
}
}
if l < len(rsum) {
res = min(res, abs(t-rsum[l]))
}
if l > 0 {
res = min(res, abs(t-rsum[l-1]))
}
}
return res
}
func dfs(nums []int, sum *[]int, i, cur int) {
if i == len(nums) {
*sum = append(*sum, cur)
return
}
dfs(nums, sum, i+1, cur)
dfs(nums, sum, i+1, cur+nums[i])
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #1755: Closest Subsequence Sum
class Solution:
def minAbsDifference(self, nums: List[int], goal: int) -> int:
n = len(nums)
left = set()
right = set()
self.getSubSeqSum(0, 0, nums[: n // 2], left)
self.getSubSeqSum(0, 0, nums[n // 2 :], right)
result = inf
right = sorted(right)
rl = len(right)
for l in left:
remaining = goal - l
idx = bisect_left(right, remaining)
if idx < rl:
result = min(result, abs(remaining - right[idx]))
if idx > 0:
result = min(result, abs(remaining - right[idx - 1]))
return result
def getSubSeqSum(self, i: int, curr: int, arr: List[int], result: Set[int]):
if i == len(arr):
result.add(curr)
return
self.getSubSeqSum(i + 1, curr, arr, result)
self.getSubSeqSum(i + 1, curr + arr[i], arr, result)
// Accepted solution for LeetCode #1755: Closest Subsequence Sum
/**
* [1755] Closest Subsequence Sum
*
* You are given an integer array nums and an integer goal.
* You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).
* Return the minimum possible value of abs(sum - goal).
* Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.
*
* Example 1:
*
* Input: nums = [5,-7,3,5], goal = 6
* Output: 0
* Explanation: Choose the whole array as a subsequence, with a sum of 6.
* This is equal to the goal, so the absolute difference is 0.
*
* Example 2:
*
* Input: nums = [7,-9,15,-2], goal = -5
* Output: 1
* Explanation: Choose the subsequence [7,-9,-2], with a sum of -4.
* The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.
*
* Example 3:
*
* Input: nums = [1,2,3], goal = -7
* Output: 7
*
*
* Constraints:
*
* 1 <= nums.length <= 40
* -10^7 <= nums[i] <= 10^7
* -10^9 <= goal <= 10^9
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/closest-subsequence-sum/
// discuss: https://leetcode.com/problems/closest-subsequence-sum/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/closest-subsequence-sum/solutions/5557655/rust-filter-out-out-of-bound-values/
pub fn min_abs_difference(nums: Vec<i32>, goal: i32) -> i32 {
let mut nums = nums;
let mut pos_sum = nums.iter().filter(|&&x| x > 0).sum::<i32>();
let mut neg_sum = nums.iter().filter(|&&x| x < 0).sum::<i32>();
nums.sort_unstable_by_key(|&x| -x.abs());
let mut v = vec![-goal];
let mut v2 = Vec::<i32>::new();
let mut result = goal.abs();
for &x in nums.iter() {
if x > 0 {
pos_sum -= x;
} else {
neg_sum -= x;
}
for y in v.drain(..).flat_map(|val| [val, val + x]) {
result = y.abs().min(result);
if y >= -neg_sum {
result = result.min(y + neg_sum);
} else if -y >= pos_sum {
result = result.min(-y - pos_sum);
} else {
v2.push(y);
}
if result == 0 {
return 0;
}
}
std::mem::swap(&mut v, &mut v2);
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1755_example_1() {
let nums = vec![5, -7, 3, 5];
let goal = 6;
let result = 0;
assert_eq!(Solution::min_abs_difference(nums, goal), result);
}
#[test]
fn test_1755_example_2() {
let nums = vec![7, -9, 15, -2];
let goal = -5;
let result = 1;
assert_eq!(Solution::min_abs_difference(nums, goal), result);
}
#[test]
fn test_1755_example_3() {
let nums = vec![1, 2, 3];
let goal = -7;
let result = 7;
assert_eq!(Solution::min_abs_difference(nums, goal), result);
}
}
// Accepted solution for LeetCode #1755: Closest Subsequence Sum
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1755: Closest Subsequence Sum
// class Solution {
// public int minAbsDifference(int[] nums, int goal) {
// int n = nums.length;
// List<Integer> lsum = new ArrayList<>();
// List<Integer> rsum = new ArrayList<>();
// dfs(nums, lsum, 0, n / 2, 0);
// dfs(nums, rsum, n / 2, n, 0);
//
// rsum.sort(Integer::compareTo);
// int res = Integer.MAX_VALUE;
//
// for (Integer x : lsum) {
// int target = goal - x;
// int left = 0, right = rsum.size();
// while (left < right) {
// int mid = (left + right) >> 1;
// if (rsum.get(mid) < target) {
// left = mid + 1;
// } else {
// right = mid;
// }
// }
// if (left < rsum.size()) {
// res = Math.min(res, Math.abs(target - rsum.get(left)));
// }
// if (left > 0) {
// res = Math.min(res, Math.abs(target - rsum.get(left - 1)));
// }
// }
//
// return res;
// }
//
// private void dfs(int[] nums, List<Integer> sum, int i, int n, int cur) {
// if (i == n) {
// sum.add(cur);
// return;
// }
//
// dfs(nums, sum, i + 1, n, cur);
// dfs(nums, sum, i + 1, n, cur + nums[i]);
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.