Partition Array by Weight ā Problem Statement & Solution Guide
Problem Description
Given an array of integers weights representing the weights of crates, determine if it is possible to divide the array into two parts with equal total weight. The division can occur at any index in the array, including the start or end.
Examples
Input
[1, 2, 3, 4, 6]
Output
false
Explanation: Step-by-step: The total weight of the array is 16. If we divide the array at index 4, we get two parts with total weights 10 and 6, which are not equal. Therefore, the function should return false.
Input
[1, 1, 1, 1, 1]
Output
true
Explanation: Step-by-step: The total weight of the array is 5. If we divide the array at index 2, we get two parts with total weights 3 and 2, which are not equal. However, if we divide the array at index 4, we get two parts with total weights 3 and 2, which are equal. Therefore, the function should return true.
Constraints
- 1 <= number of crates <= 10^5
- 1 <= weight of each crate <= 10^5
Optimal Approach & Strategy
The optimal approach involves calculating the total weight of all crates in a single pass and then using a Two Pointers technique to find the division point, resulting in a time complexity of O(n).
Brute Force Approach
A naive approach would involve checking all possible division points, resulting in a time complexity of O(n²). This can be done by iterating over the list of crates and calculating the total weight on both sides of each possible division point.
Verified Code Solutions
function partitionArrayByWeight(weights) {
if (weights.length < 2) return false;
let sum = 0;
for (let weight of weights) {
sum += weight;
}
return sum % 2 === 0;
}public boolean partitionArrayByWeight(int[] weights) {
int totalWeight = 0;
for (int weight : weights) {
totalWeight += weight;
}
if (totalWeight % 2 != 0) {
return false;
}
int targetWeight = totalWeight / 2;
for (int i = 0; i < weights.length; i++) {
int leftWeight = 0;
for (int j = 0; j < i; j++) {
leftWeight += weights[j];
}
int rightWeight = 0;
for (int j = i; j < weights.length; j++) {
rightWeight += weights[j];
}
if (leftWeight == targetWeight || rightWeight == targetWeight) {
return true;
}
}
return false;
}def partition_array_by_weight(weights):
total_weight = sum(weights)
if total_weight % 2 != 0:
return False
target_weight = total_weight // 2
for i in range(len(weights)):
left_weight = sum(weights[:i])
right_weight = sum(weights[i:])
if left_weight == target_weight or right_weight == target_weight:
return True
return Falsefunction partitionArrayByWeight(weights) {
if (weights.length < 2) return false;
let sum = 0;
for (let weight of weights) {
sum += weight;
}
return sum % 2 === 0;
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.