Leetcode 1013. Partition Array Into Three Parts With Equal Sum
You are given an integer array arr
of length n
that contains only positive integers. The task is to check if the array can be partitioned into three non-empty contiguous subarrays such that the sum of the elements in all three subarrays is equal.
n
?
false
.total_sum / 3
) before the end of the array.public class Solution {
public boolean canThreePartsEqualSum(int[] arr) {
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
if (totalSum % 3 != 0) {
return false;
}
int targetSum = totalSum / 3;
int currentSum = 0;
int partitionCount = 0;
for (int i = 0; i < arr.length; i++) {
currentSum += arr[i];
if (currentSum == targetSum) {
partitionCount++;
currentSum = 0;
// If we found all 3 partitions
if (partitionCount == 2) {
return true;
}
}
}
return false;
}
}
This solution efficiently checks whether the array can be divided into three parts with equal sum using linear time and constant space, making it suitable for large input sizes as specified in typical constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?