Skip to content
Problem 805 · LeetCode 805(opens in a new tab)

Split Array With Same Average

HardArrays

You are given an integer array nums. Put every element into one of two groups, A or B, so that neither group is empty.

Return true if you can do this so that A and B have exactly the same average (sum divided by count), and false if no such split exists.

Example 1

Input:  nums = [1, 5, 3, 7]
Output: true
Why:    [1, 7] and [5, 3] both average 4
2 more examples and the constraints

Example 2

Input:  nums = [4, 9]
Output: false
Why:    the only split is [4] and [9]

Example 3

Input:  nums = [5, 0, 10]
Output: true
Why:    [5] and [0, 10] both average 5

Constraints

  • 1 ≤ length of nums ≤ 30
  • 0 ≤ nums[i] ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sums by count (bitset DP)O(n² · S / 64)
  2. Meet in the middleO(n · 2^(n/2))

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 30 numbers up to 10,000Verdict
Sums by count (bitset DP)O(n² · S / 64)
Passes; needs big-integer bits
Meet in the middleO(n · 2^(n/2))
Best; plain sets and loops

n = length of nums, S = largest possible sum of half the numbers (150,000).

Edge cases to test

  • One number. There is no way to fill both groups: false.
  • All values equal. Any split works, e.g. [3, 3, 3] gives true.
  • Two numbers. True only when they are equal.
  • Zeros. [0, 0] is true; [0, 6] is false.
  • No k divides evenly. If total · k / n is never a whole number for k ≤ n / 2, the answer is false at once.

Common mistakes

  • Comparing averages with floating-point division instead of the whole-number test sum · n == total · k.
  • Allowing the whole array as one group, which makes the other group empty.
  • Updating reach[k] for k from low to high, which lets one number be used twice.

How to talk through it

  1. 1Clarify. Must both groups be non-empty? Can values be 0? How long can the array be?
  2. 2Simplify the condition. Both averages equal the overall average, so only one group matters.
  3. 3Name the brute force. 2³⁰ subsets is about a billion: too many, but 2¹⁵ per half is small.
  4. 4Code meet in the middle. Shift to x · n − total, store left sums, look up the opposite from the right.
  5. 5Test out loud. Run a single number, two unequal numbers, and an all-equal array.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?