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 two arrays nums and andValues of length n and m respectively.
The value of an array is equal to the last element of that array.
You have to divide nums into m disjoint contiguous subarrays such that for the ith subarray [li, ri], the bitwise AND of the subarray elements is equal to andValues[i], in other words, nums[li] & nums[li + 1] & ... & nums[ri] == andValues[i] for all 1 <= i <= m, where & represents the bitwise AND operator.
Return the minimum possible sum of the values of the m subarrays nums is divided into. If it is not possible to divide nums into m subarrays satisfying these conditions, return -1.
Example 1:
Input: nums = [1,4,3,3,2], andValues = [0,3,3,2]
Output: 12
Explanation:
The only possible way to divide nums is:
[1,4] as 1 & 4 == 0.[3] as the bitwise AND of a single element subarray is that element itself.[3] as the bitwise AND of a single element subarray is that element itself.[2] as the bitwise AND of a single element subarray is that element itself.The sum of the values for these subarrays is 4 + 3 + 3 + 2 = 12.
Example 2:
Input: nums = [2,3,5,7,7,7,5], andValues = [0,7,5]
Output: 17
Explanation:
There are three ways to divide nums:
[[2,3,5],[7,7,7],[5]] with the sum of the values 5 + 7 + 5 == 17.[[2,3,5,7],[7,7],[5]] with the sum of the values 7 + 7 + 5 == 19.[[2,3,5,7,7],[7],[5]] with the sum of the values 7 + 7 + 5 == 19.The minimum possible sum of the values is 17.
Example 3:
Input: nums = [1,2,3,4], andValues = [2]
Output: -1
Explanation:
The bitwise AND of the entire array nums is 0. As there is no possible way to divide nums into a single subarray to have the bitwise AND of elements 2, return -1.
Constraints:
1 <= n == nums.length <= 1041 <= m == andValues.length <= min(n, 10)1 <= nums[i] < 1050 <= andValues[j] < 105Problem summary: You are given two arrays nums and andValues of length n and m respectively. The value of an array is equal to the last element of that array. You have to divide nums into m disjoint contiguous subarrays such that for the ith subarray [li, ri], the bitwise AND of the subarray elements is equal to andValues[i], in other words, nums[li] & nums[li + 1] & ... & nums[ri] == andValues[i] for all 1 <= i <= m, where & represents the bitwise AND operator. Return the minimum possible sum of the values of the m subarrays nums is divided into. If it is not possible to divide nums into m subarrays satisfying these conditions, return -1.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Dynamic Programming · Bit Manipulation · Segment Tree
[1,4,3,3,2] [0,3,3,2]
[2,3,5,7,7,7,5] [0,7,5]
[1,2,3,4] [2]
minimum-cost-to-split-an-array)split-with-minimum-sum)find-subarray-with-bitwise-or-closest-to-k)find-x-value-of-array-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3117: Minimum Sum of Values by Dividing Array
class Solution {
private int[] nums;
private int[] andValues;
private final int inf = 1 << 29;
private Map<Long, Integer> f = new HashMap<>();
public int minimumValueSum(int[] nums, int[] andValues) {
this.nums = nums;
this.andValues = andValues;
int ans = dfs(0, 0, -1);
return ans >= inf ? -1 : ans;
}
private int dfs(int i, int j, int a) {
if (nums.length - i < andValues.length - j) {
return inf;
}
if (j == andValues.length) {
return i == nums.length ? 0 : inf;
}
a &= nums[i];
if (a < andValues[j]) {
return inf;
}
long key = (long) i << 36 | (long) j << 32 | a;
if (f.containsKey(key)) {
return f.get(key);
}
int ans = dfs(i + 1, j, a);
if (a == andValues[j]) {
ans = Math.min(ans, dfs(i + 1, j + 1, -1) + nums[i]);
}
f.put(key, ans);
return ans;
}
}
// Accepted solution for LeetCode #3117: Minimum Sum of Values by Dividing Array
func minimumValueSum(nums []int, andValues []int) int {
n, m := len(nums), len(andValues)
f := map[int]int{}
const inf int = 1 << 29
var dfs func(i, j, a int) int
dfs = func(i, j, a int) int {
if n-i < m-j {
return inf
}
if j == m {
if i == n {
return 0
}
return inf
}
a &= nums[i]
if a < andValues[j] {
return inf
}
key := i<<36 | j<<32 | a
if v, ok := f[key]; ok {
return v
}
ans := dfs(i+1, j, a)
if a == andValues[j] {
ans = min(ans, dfs(i+1, j+1, -1)+nums[i])
}
f[key] = ans
return ans
}
if ans := dfs(0, 0, -1); ans < inf {
return ans
}
return -1
}
# Accepted solution for LeetCode #3117: Minimum Sum of Values by Dividing Array
class Solution:
def minimumValueSum(self, nums: List[int], andValues: List[int]) -> int:
@cache
def dfs(i: int, j: int, a: int) -> int:
if n - i < m - j:
return inf
if j == m:
return 0 if i == n else inf
a &= nums[i]
if a < andValues[j]:
return inf
ans = dfs(i + 1, j, a)
if a == andValues[j]:
ans = min(ans, dfs(i + 1, j + 1, -1) + nums[i])
return ans
n, m = len(nums), len(andValues)
ans = dfs(0, 0, -1)
return ans if ans < inf else -1
// Accepted solution for LeetCode #3117: Minimum Sum of Values by Dividing Array
/**
* [3117] Minimum Sum of Values by Dividing Array
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashMap;
const INFINITE: i32 = (1 << 20) - 1;
impl Solution {
pub fn minimum_value_sum(nums: Vec<i32>, and_values: Vec<i32>) -> i32 {
let (n, m) = (nums.len(), and_values.len());
let mut memory = vec![HashMap::new(); m * n];
let result = Self::dfs(&mut memory, 0, 0, INFINITE, &nums, &and_values);
if result == INFINITE {
-1
} else {
result
}
}
fn dfs(
memory: &mut Vec<HashMap<i32, i32>>,
i: usize,
j: usize,
current: i32,
nums: &Vec<i32>,
and_values: &Vec<i32>,
) -> i32 {
let (n, m) = (nums.len(), and_values.len());
let key = m * i + j;
if i == n && j == m {
return 0;
}
if i == n || j == m {
return INFINITE;
}
if let Some(r) = memory[key].get(¤t) {
return *r;
}
let current = current & nums[i];
if current & and_values[j] < and_values[j] {
return INFINITE;
}
let mut result = Self::dfs(memory, i + 1, j, current, nums, and_values);
if current == and_values[j] {
result =
result.min(Self::dfs(memory, i + 1, j + 1, INFINITE, nums, and_values) + nums[i]);
}
memory[key].insert(current, result);
return result;
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3117() {
assert_eq!(
12,
Solution::minimum_value_sum(vec![1, 4, 3, 3, 2], vec![0, 3, 3, 2])
);
}
}
// Accepted solution for LeetCode #3117: Minimum Sum of Values by Dividing Array
function minimumValueSum(nums: number[], andValues: number[]): number {
const [n, m] = [nums.length, andValues.length];
const f: Map<bigint, number> = new Map();
const dfs = (i: number, j: number, a: number): number => {
if (n - i < m - j) {
return Infinity;
}
if (j === m) {
return i === n ? 0 : Infinity;
}
a &= nums[i];
if (a < andValues[j]) {
return Infinity;
}
const key = (BigInt(i) << 36n) | (BigInt(j) << 32n) | BigInt(a);
if (f.has(key)) {
return f.get(key)!;
}
let ans = dfs(i + 1, j, a);
if (a === andValues[j]) {
ans = Math.min(ans, dfs(i + 1, j + 1, -1) + nums[i]);
}
f.set(key, ans);
return ans;
};
const ans = dfs(0, 0, -1);
return ans >= Infinity ? -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: 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.