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.
You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B).
Return true if it is possible to achieve that and false otherwise.
Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.
Example 1:
Input: nums = [1,2,3,4,5,6,7,8] Output: true Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.
Example 2:
Input: nums = [3,1] Output: false
Constraints:
1 <= nums.length <= 300 <= nums[i] <= 104Problem summary: You are given an integer array nums. You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B). Return true if it is possible to achieve that and false otherwise. Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Math · Dynamic Programming · Bit Manipulation
[1,2,3,4,5,6,7,8]
[3,1]
partition-array-into-two-arrays-to-minimize-sum-difference)minimum-average-difference)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #805: Split Array With Same Average
class Solution {
public boolean splitArraySameAverage(int[] nums) {
int n = nums.length;
if (n == 1) {
return false;
}
int s = Arrays.stream(nums).sum();
for (int i = 0; i < n; ++i) {
nums[i] = nums[i] * n - s;
}
int m = n >> 1;
Set<Integer> vis = new HashSet<>();
for (int i = 1; i < 1 << m; ++i) {
int t = 0;
for (int j = 0; j < m; ++j) {
if (((i >> j) & 1) == 1) {
t += nums[j];
}
}
if (t == 0) {
return true;
}
vis.add(t);
}
for (int i = 1; i < 1 << (n - m); ++i) {
int t = 0;
for (int j = 0; j < (n - m); ++j) {
if (((i >> j) & 1) == 1) {
t += nums[m + j];
}
}
if (t == 0 || (i != (1 << (n - m)) - 1) && vis.contains(-t)) {
return true;
}
}
return false;
}
}
// Accepted solution for LeetCode #805: Split Array With Same Average
func splitArraySameAverage(nums []int) bool {
n := len(nums)
if n == 1 {
return false
}
s := 0
for _, v := range nums {
s += v
}
for i, v := range nums {
nums[i] = v*n - s
}
m := n >> 1
vis := map[int]bool{}
for i := 1; i < 1<<m; i++ {
t := 0
for j, v := range nums[:m] {
if (i >> j & 1) == 1 {
t += v
}
}
if t == 0 {
return true
}
vis[t] = true
}
for i := 1; i < 1<<(n-m); i++ {
t := 0
for j, v := range nums[m:] {
if (i >> j & 1) == 1 {
t += v
}
}
if t == 0 || (i != (1<<(n-m))-1 && vis[-t]) {
return true
}
}
return false
}
# Accepted solution for LeetCode #805: Split Array With Same Average
class Solution:
def splitArraySameAverage(self, nums: List[int]) -> bool:
n = len(nums)
if n == 1:
return False
s = sum(nums)
for i, v in enumerate(nums):
nums[i] = v * n - s
m = n >> 1
vis = set()
for i in range(1, 1 << m):
t = sum(v for j, v in enumerate(nums[:m]) if i >> j & 1)
if t == 0:
return True
vis.add(t)
for i in range(1, 1 << (n - m)):
t = sum(v for j, v in enumerate(nums[m:]) if i >> j & 1)
if t == 0 or (i != (1 << (n - m)) - 1 and -t in vis):
return True
return False
// Accepted solution for LeetCode #805: Split Array With Same Average
struct Solution;
use std::collections::HashMap;
impl Solution {
fn split_array_same_average(a: Vec<i32>) -> bool {
let n = a.len();
let sum: i32 = a.iter().sum();
for k in 1..=n / 2 {
if sum * k as i32 % n as i32 == 0 {
let target = sum * k as i32 / n as i32;
if Self::dp(target, k, n, &mut HashMap::new(), &a) {
return true;
}
}
}
false
}
fn dp(
target: i32,
k: usize,
n: usize,
memo: &mut HashMap<(i32, usize, usize), bool>,
a: &[i32],
) -> bool {
if let Some(&res) = memo.get(&(target, k, n)) {
res
} else {
let res = if k == 0 {
target == 0
} else {
if n < k {
false
} else {
let next = target - a[n - 1];
Self::dp(target, k, n - 1, memo, a)
|| next >= 0 && Self::dp(next, k - 1, n - 1, memo, a)
}
};
memo.insert((target, k, n), res);
res
}
}
}
#[test]
fn test() {
let a = vec![1, 2, 3, 4, 5, 6, 7, 8];
let res = true;
assert_eq!(Solution::split_array_same_average(a), res);
}
// Accepted solution for LeetCode #805: Split Array With Same Average
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #805: Split Array With Same Average
// class Solution {
// public boolean splitArraySameAverage(int[] nums) {
// int n = nums.length;
// if (n == 1) {
// return false;
// }
// int s = Arrays.stream(nums).sum();
// for (int i = 0; i < n; ++i) {
// nums[i] = nums[i] * n - s;
// }
// int m = n >> 1;
// Set<Integer> vis = new HashSet<>();
// for (int i = 1; i < 1 << m; ++i) {
// int t = 0;
// for (int j = 0; j < m; ++j) {
// if (((i >> j) & 1) == 1) {
// t += nums[j];
// }
// }
// if (t == 0) {
// return true;
// }
// vis.add(t);
// }
// for (int i = 1; i < 1 << (n - m); ++i) {
// int t = 0;
// for (int j = 0; j < (n - m); ++j) {
// if (((i >> j) & 1) == 1) {
// t += nums[m + j];
// }
// }
// if (t == 0 || (i != (1 << (n - m)) - 1) && vis.contains(-t)) {
// return true;
// }
// }
// return false;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
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: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
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.