LeetCode 1013: Partition Array Into Three Parts With Equal Sum Solution
Master LeetCode problem 1013 (Partition Array Into Three Parts With Equal Sum), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we need to check if the array can be partitioned into three parts with equal sums. We can achieve this by first calculating the total sum of the array and then searching for two partitions that divide the array into three parts with equal sum.
- Calculate the total sum of the array.
- Iterate through the array to find the first partition point where the sum equals one-third of the total sum.
- Continue iterating to find the second partition point where the sum equals two-thirds of the total sum.
If we successfully find both partition points, we return true; otherwise, we return false.
Time complexity: O(n) where n is the number of elements in the array. Space complexity: O(1)
Solution Code
class Solution {
public boolean canThreePartsEqualSum(int[] arr) {
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
if (totalSum % 3 != 0) {
return false;
}
int partitionSum = totalSum / 3;
int currentSum = 0;
int partitionsFound = 0;
for (int num : arr) {
currentSum += num;
if (currentSum == partitionSum) {
partitionsFound++;
currentSum = 0;
}
}
return partitionsFound >= 3;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1013 (Partition Array Into Three Parts With Equal Sum)?
This page provides optimized solutions for LeetCode problem 1013 (Partition Array Into Three Parts With Equal Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1013 (Partition Array Into Three Parts With Equal Sum)?
The time complexity for LeetCode 1013 (Partition Array Into Three Parts With Equal Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1013 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1013 in Java, C++, or Python.