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.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.
Example 1:
Input: arr = [3,2,2,4,3], target = 3 Output: 2 Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.
Example 2:
Input: arr = [7,3,4,7], target = 7 Output: 2 Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
Example 3:
Input: arr = [4,3,2,6,2,3,4], target = 6 Output: -1 Explanation: We have only one sub-array of sum = 6.
Constraints:
1 <= arr.length <= 1051 <= arr[i] <= 10001 <= target <= 108Problem summary: You are given an array of integers arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Binary Search · Dynamic Programming · Sliding Window
[3,2,2,4,3] 3
[7,3,4,7] 7
[4,3,2,6,2,3,4] 6
find-subarrays-with-equal-sum)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
class Solution {
public int minSumOfLengths(int[] arr, int target) {
Map<Integer, Integer> d = new HashMap<>();
d.put(0, 0);
int n = arr.length;
int[] f = new int[n + 1];
final int inf = 1 << 30;
f[0] = inf;
int s = 0, ans = inf;
for (int i = 1; i <= n; ++i) {
int v = arr[i - 1];
s += v;
f[i] = f[i - 1];
if (d.containsKey(s - target)) {
int j = d.get(s - target);
f[i] = Math.min(f[i], i - j);
ans = Math.min(ans, f[j] + i - j);
}
d.put(s, i);
}
return ans > n ? -1 : ans;
}
}
// Accepted solution for LeetCode #1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
func minSumOfLengths(arr []int, target int) int {
d := map[int]int{0: 0}
const inf = 1 << 30
s, n := 0, len(arr)
f := make([]int, n+1)
f[0] = inf
ans := inf
for i, v := range arr {
i++
f[i] = f[i-1]
s += v
if j, ok := d[s-target]; ok {
f[i] = min(f[i], i-j)
ans = min(ans, f[j]+i-j)
}
d[s] = i
}
if ans > n {
return -1
}
return ans
}
# Accepted solution for LeetCode #1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
d = {0: 0}
s, n = 0, len(arr)
f = [inf] * (n + 1)
ans = inf
for i, v in enumerate(arr, 1):
s += v
f[i] = f[i - 1]
if s - target in d:
j = d[s - target]
f[i] = min(f[i], i - j)
ans = min(ans, f[j] + i - j)
d[s] = i
return -1 if ans > n else ans
// Accepted solution for LeetCode #1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
struct Solution;
use std::collections::HashMap;
impl Solution {
fn min_sum_of_lengths(arr: Vec<i32>, target: i32) -> i32 {
let n = arr.len();
let mut hm: HashMap<i32, i32> = HashMap::new();
let mut dp: Vec<i32> = vec![std::i32::MAX; n];
*hm.entry(0).or_default() = -1;
let mut prev = 0;
let mut res = std::i32::MAX;
let mut min = std::i32::MAX;
for i in 0..n {
prev += arr[i];
if let Some(&j) = hm.get(&(prev - target)) {
if j > -1 && dp[j as usize] != std::i32::MAX {
res = res.min(i as i32 - j + dp[j as usize]);
}
min = min.min(i as i32 - j);
}
dp[i] = min;
*hm.entry(prev).or_default() = i as i32;
}
if res == std::i32::MAX {
-1
} else {
res
}
}
}
#[test]
fn test() {
let arr = vec![3, 2, 2, 4, 3];
let target = 3;
let res = 2;
assert_eq!(Solution::min_sum_of_lengths(arr, target), res);
let arr = vec![7, 3, 4, 7];
let target = 7;
let res = 2;
assert_eq!(Solution::min_sum_of_lengths(arr, target), res);
let arr = vec![4, 3, 2, 6, 2, 3, 4];
let target = 6;
let res = -1;
assert_eq!(Solution::min_sum_of_lengths(arr, target), res);
let arr = vec![5, 5, 4, 4, 5];
let target = 3;
let res = -1;
assert_eq!(Solution::min_sum_of_lengths(arr, target), res);
let arr = vec![3, 1, 1, 1, 5, 1, 2, 1];
let target = 3;
let res = 3;
assert_eq!(Solution::min_sum_of_lengths(arr, target), res);
let arr = vec![1, 6, 1];
let target = 7;
let res = -1;
assert_eq!(Solution::min_sum_of_lengths(arr, target), res);
}
// Accepted solution for LeetCode #1477: Find Two Non-overlapping Sub-arrays Each With Target Sum
function minSumOfLengths(arr: number[], target: number): number {
const d = new Map<number, number>();
d.set(0, 0);
let s = 0;
const n = arr.length;
const f: number[] = Array(n + 1);
const inf = 1 << 30;
f[0] = inf;
let ans = inf;
for (let i = 1; i <= n; ++i) {
const v = arr[i - 1];
s += v;
f[i] = f[i - 1];
if (d.has(s - target)) {
const j = d.get(s - target)!;
f[i] = Math.min(f[i], i - j);
ans = Math.min(ans, f[j] + i - j);
}
d.set(s, i);
}
return ans > n ? -1 : ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
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: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
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.