Problem Description
Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums. Formally, we need to check if there exist indices i and j such that: (arr[0] + arr[1] + ... + arr[i]) == (arr[i+1] + ... + arr[j-1]) == (arr[j] + ... + arr[arr.length-1]) with the condition that i+1 < j.
Key Insights
- The total sum of the array must be divisible by 3.
- If the total sum is divisible by 3, the target sum for each partition is total_sum / 3.
- Traverse the array once, accumulating the sum. When the cumulative sum equals target, reset it and count a partition.
- Ensure that two partitions are found before the end of the array so that the third partition is non-empty.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
First, compute the total sum of the array. If the total sum is not divisible by 3, return false immediately since it's impossible to partition appropriately. Otherwise, the target sum for each partition is total_sum / 3.
Iterate through the array accumulating a running sum. When the running sum equals the target, increment a partition counter and reset the running sum to zero.
If two such partitions are identified before reaching the end of the array, the remainder of the array will form a valid third partition. This approach uses a single pass and minimal extra space, making it efficient for large arrays.