mediumArraysPattern: Two Pointers
Partition Array by Weight Solution
Problem Statement
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.
Examples
Example 1:
Input:{"weights":[1,2,3,4,5]}
Output:false
Explanation: The sum of weights is 15 which is odd, making it impossible to divide the weights into two equal parts.
Example 2:
Input:{"weights":[1,2,3,4,6]}
Output:false
Explanation: The sum of weights is 16 which can be divided into two equal parts (8), but the given sequence cannot be divided into two equal parts.
Example 3:
Input:{"weights":[1,1,1,1,1]}
Output:true
Explanation: The sum of weights is 5 which can be divided into two equal parts (2.5), but since the weights are integers, this can be achieved by dividing the weights into [1, 1, 1] and [1, 1].
Example 4:
Input:{"weights":[2,2,2]}
Output:true
Explanation: The sum of weights is 6 which can be divided into two equal parts (3), and this can be achieved by dividing the weights into [2, 2] and [2].
Constraints
- 1 <= number of crates <= 10^5
- 1 <= weight of each crate <= 10^5
Time: O(n) Space: O(1)
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).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
