Split Array With Same Average - Problem

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: For an array arr, average(arr) is the sum of all the elements of arr over the length of arr.

Input & Output

Example 1 — Possible Split
$ Input: nums = [1,2,3,4,5,6,7,8]
Output: true
💡 Note: We can split into {1,4,5,8} with average 4.5 and {2,3,6,7} with average 4.5
Example 2 — Impossible Split
$ Input: nums = [3,1]
Output: false
💡 Note: Cannot split 2 elements into two non-empty groups with same average
Example 3 — Equal Elements
$ Input: nums = [1,1,1,1]
Output: true
💡 Note: Any split like {1,1} and {1,1} will have the same average of 1.0

Constraints

  • 1 ≤ nums.length ≤ 30
  • 0 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Split Array With Same Average INPUT nums = [1,2,3,4,5,6,7,8] 1 2 3 4 5 6 7 8 Total Sum = 36 n = 8, avg = 4.5 Goal: Split into A and B where avg(A) == avg(B) Both non-empty ALGORITHM STEPS 1 Math Property If avg(A)=avg(B)=avg(nums) sum(A)/|A| = totalSum/n 2 Transform Problem sum(A)*n = totalSum*|A| Find subset with valid sum 3 DP with Bitmask Track possible sums for each subset size k 4 Check Valid Splits For k=1 to n/2, check if sum = k*totalSum/n exists DP State Check k=1: sum=4.5 (not int) k=2: sum=9 (check DP) k=4: sum=18 (found!) {1,2,7,8} sums to 18 FINAL RESULT Valid Split Found! Array A 1 2 7 8 Sum=18, Len=4, Avg=4.5 Array B 3 4 5 6 Sum=18, Len=4, Avg=4.5 Output: true avg(A) == avg(B) == 4.5 Verification: OK Both arrays non-empty Key Insight: The mathematical insight is that if avg(A) = avg(B), then both must equal avg(nums). This transforms the problem to: find a subset of size k with sum = k * totalSum / n. We use DP with meet-in-middle optimization to track achievable sums for each subset size, checking only sizes up to n/2. TutorialsPoint - Split Array With Same Average | Mathematical Optimization with DP
Asked in
Google 8 Facebook 5 Microsoft 3
22.3K Views
Medium Frequency
~45 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen