LeetCode 548: Split Array with Equal Sum Solution
Master LeetCode problem 548 (Split Array with Equal Sum), a hard 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.
548. Split Array with Equal Sum
Problem Explanation
Explanation:
This problem asks us to split an array into three non-empty subarrays with equal sums. We need to return true if it is possible, otherwise false.
To solve this problem, we can iterate over all possible positions to split the array into three parts. For each position, we calculate the sum of each part and check if they are equal. If they are equal, we return true.
We can optimize the solution by pre-calculating the prefix sums of the array, which allows us to calculate the sum of any subarray in constant time. :
Solution Code
class Solution {
public boolean splitArray(int[] nums) {
int n = nums.length;
int[] prefixSum = new int[n];
prefixSum[0] = nums[0];
for (int i = 1; i < n; i++) {
prefixSum[i] = prefixSum[i - 1] + nums[i];
}
for (int j = 3; j < n - 3; j++) {
HashSet<Integer> set = new HashSet<>();
for (int i = 1; i < j - 1; i++) {
if (prefixSum[i - 1] == prefixSum[j - 1] - prefixSum[i]) {
set.add(prefixSum[i - 1]);
}
}
for (int k = j + 2; k < n - 1; k++) {
int sum3 = prefixSum[n - 1] - prefixSum[k];
int sum4 = prefixSum[k] - prefixSum[j];
if (set.contains(sum3) && sum3 == sum4) {
return true;
}
}
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 548 (Split Array with Equal Sum)?
This page provides optimized solutions for LeetCode problem 548 (Split Array 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 548 (Split Array with Equal Sum)?
The time complexity for LeetCode 548 (Split Array 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 548 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 548 in Java, C++, or Python.