Katkat

Solve Four Online Assessment Coding Tasks

Virtu FinancialSoftware Engineer · Online Assessment

Last updated

Determine the maximum number of contiguous, non-empty subarrays an array can be partitioned into such that each subarray has the same sum.

Problem Statement

Given an array of positive integers nums, you want to partition the entire array into the maximum possible number of contiguous, non-empty subarrays such that every subarray has the exact same element sum.

Return the maximum number of subarrays, k, that nums can be divided into.

Every element of nums must belong to exactly one subarray, and the relative order of elements must be preserved.

Function Signature

def max_equal_sum_partitions(nums: list[int]) -> int:
    pass

Input and Output Format

  • Input: A list of positive integers nums of length n.
  • Output: An integer representing the maximum number of contiguous segments k where all segments have identical sums.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^4
  • The sum of elements in nums will not exceed 10^9.

Examples

Example 1

Input: nums = [1, 2, 3, 1, 1, 1, 3]
Output: 4
Explanation: 
The total sum is 12. We can partition the array into 4 subarrays of sum 3:
[1, 2], [3], [1, 1, 1], and [3].
No partition into more than 4 subarrays with equal sum is possible.

Example 2

Input: nums = [3, 2, 4, 1]
Output: 2
Explanation:
The total sum is 10. We can partition the array into 2 subarrays of sum 5:
[3, 2] and [4, 1].
It is impossible to partition into more than 2 subarrays of equal sum.

Edge Cases

  • nums.length == 1: The only partition is the array itself, so return 1.
  • All elements equal: An array like [2, 2, 2, 2] should return 4 (each subarray has size 1).
  • Prime total sum: If the total sum is prime, the only possible partitions have sum equal to the total sum (k = 1) or each element equal to 1 (if total sum equals nums.length).

Hints

Hint 1

Because all elements are positive, the sum of any valid subarray must be a factor of the total array sum.

Hint 2

The sum of the first subarray in any valid partition corresponds to a prefix sum nums[0] + ... + nums[i].

Hint 3

Store all prefix sums in a hash set or use binary search; for each candidate segment sum that divides the total sum, verify whether multiples of that sum exist until reaching the total sum.

Follow-up questions

  • How would your approach change if nums could contain negative integers or zeroes?
  • If the array is too large to fit in memory and is streamed chunk-by-chunk with known total sum, how can you determine if a given partition count k is valid?
  • What is the theoretical worst-case time complexity of testing all valid divisors of the total sum, and what value of total sum maximizes the number of operations?