Split Array With Same Average — LeetCode 805 Python Solution

HardBit ManipulationArrayMathDynamic ProgrammingBitmask
Problem
#805
Reading time
4 min

The 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).

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(2^n), which will time out
SpaceO(2^{\frac{n}{2}}) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 805. Split Array With Same Average is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 805. Split Array With Same Average?
LeetCode 805. Split Array With Same Average is rated Hard on LeetCode.
What is the time complexity of LeetCode 805. Split Array With Same Average?
The Python solution on this page runs in O(2^n), which will time out.
What is the space complexity of LeetCode 805. Split Array With Same Average?
The Python solution on this page uses O(2^{\frac{n}{2}}) auxiliary space.
What topics does LeetCode 805. Split Array With Same Average cover?
LeetCode 805. Split Array With Same Average is tagged Bit Manipulation, Array, Math, Dynamic Programming and Bitmask on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview