1592. Balanced Cut Point
A necklace of weighted beads is stored as a singly linked list, and you want to split it into a front part and a back part so the two total weights are as close as possible. Write balancedCut(head), which returns the number p of beads in the front part, with 1 <= p < length so both parts are non-empty, that minimises the absolute difference between the front sum and the back sum. If several values of p give the same minimum difference, return the smallest p. If the list has fewer than 2 nodes, return -1. Node values are between -10^4 and 10^4 and the list has 0 to 10^5 nodes. Aim for O(n) time and O(1) extra space; sums need 64-bit arithmetic in some languages.
Example 1
- Input:
- head = [1,2,3,4]
- Output:
- 3
- Explanation:
Cutting after 3 nodes gives 6 versus 4, but cutting after 2 gives 3 versus 7; the best is p = 3 with difference 2.
Example 2
- Input:
- head = [5,-5]
- Output:
- 1
- Explanation:
Only p = 1 is possible.
Example 3
- Input:
- head = [1,0,0,1]
- Output:
- 1
- Explanation:
p = 1 already balances 1 against 1, and it is the smallest such p.
Constraints
0 ≤ length ≤ 105
-104 ≤ val ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)