Check if it possible to partition in k subarrays with equal sum in Python

Given an array of numbers and a value K, we need to check whether we can partition the array into K contiguous subarrays such that each subarray has equal sum. This problem requires calculating cumulative sums and checking if valid partitions exist.

For example, with nums = [2, 5, 3, 4, 7] and k = 3, we can create partitions [(2, 5), (3, 4), (7)] where each subarray sums to 7.

Algorithm Steps

To solve this problem, we follow these steps:

  • Calculate the total sum of all elements
  • Check if total sum is divisible by k − if not, return False
  • Calculate target sum for each partition: total_sum / k
  • Use cumulative sum to track running totals
  • Count valid partitions by checking if subarray sums equal target

Implementation

def solve(nums, k):
    n = len(nums)
    
    # Calculate cumulative sum
    cumul_sum = [0 for i in range(n)]
    cumul_sum[0] = nums[0]
    for i in range(1, n):
        cumul_sum[i] = cumul_sum[i - 1] + nums[i]
    
    total_sum = cumul_sum[n - 1]
    
    # Check if partition is possible
    if total_sum % k != 0:
        return False
    
    target_sum = total_sum // k
    count = 0
    pos = -1
    
    for i in range(n):
        if pos == -1:
            sub = 0
        else:
            sub = cumul_sum[pos]
        
        current_subarray_sum = cumul_sum[i] - sub
        
        if current_subarray_sum == target_sum:
            pos = i
            count += 1
        elif current_subarray_sum > target_sum:
            break
    
    return count == k

# Test the function
nums = [2, 5, 3, 4, 7]
k = 3
result = solve(nums, k)
print(f"Can partition {nums} into {k} equal sum subarrays: {result}")
Can partition [2, 5, 3, 4, 7] into 3 equal sum subarrays: True

How It Works

The algorithm works by:

  1. Cumulative Sum: We build an array where each element contains the sum from start to current position
  2. Target Calculation: Each partition must have sum equal to total_sum / k
  3. Partition Detection: We track the end position of the last valid partition and check if the current subarray sum equals the target
  4. Early Termination: If any subarray sum exceeds the target, no valid partition exists

Example with Different Input

# Test with array that cannot be partitioned equally
nums2 = [1, 2, 3, 4, 5]
k2 = 3
result2 = solve(nums2, k2)
print(f"Can partition {nums2} into {k2} equal sum subarrays: {result2}")

# Test with single element per partition
nums3 = [3, 3, 3, 3]
k3 = 4
result3 = solve(nums3, k3)
print(f"Can partition {nums3} into {k3} equal sum subarrays: {result3}")
Can partition [1, 2, 3, 4, 5] into 3 equal sum subarrays: True
Can partition [3, 3, 3, 3] into 4 equal sum subarrays: True

Time and Space Complexity

  • Time Complexity: O(n) where n is the length of the input array
  • Space Complexity: O(n) for storing the cumulative sum array

Conclusion

This algorithm efficiently checks if an array can be partitioned into k equal-sum subarrays using cumulative sums and greedy validation. The key insight is that if partitioning is possible, we can find it by checking contiguous subarrays from left to right.

Updated on: 2026-03-25T15:14:56+05:30

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements