The Tape Equilibrium problem asks you to split an array of integers at some index P such that the absolute difference between the sum of the left part and the sum of the right part is as small as possible.
Imagine you have a row of items with different weights, and you want to pack them into **two bags (left bag and right bag)**.
You cannot change the order of the items. You must pick a splitting point: everything before that point goes to the left bag, and everything after goes to the right bag.
Your goal is to find the splitting point that makes the weights of both bags **as close as possible (minimum difference)** so you can carry them easily without falling over.
Step-by-Step Logic Trace
- Calculate the total sum of all elements in the array first.
- Set up a loop that simulates placing the split point
Pfrom index 1 to the end of the array. - For each index, add the current element to the
leftSum, and subtract it from therightSum(which is initialized tototalSum - leftSum). - Calculate the absolute difference
|leftSum - rightSum|. - Keep track of the minimum difference found during the loop iterations.
Java Implementation
package io.practise.myPractice;
public class TapeEquilibriumCodility {
public int solution(int[] A) {
long totalSum = 0;
for (int val : A) {
totalSum += val;
}
long leftSum = 0;
long minDiff = Long.MAX_VALUE;
// P splits the array into two non-empty parts: A[0..P-1] and A[P..N-1]
for (int p = 1; p < A.length; p++) {
leftSum += A[p - 1];
long rightSum = totalSum - leftSum;
long diff = Math.abs(leftSum - rightSum);
if (diff < minDiff) {
minDiff = diff;
}
}
return (int) minDiff;
}
}
Conclusion
By computing the total sum beforehand, we avoid nested loops. This optimizes the time complexity to O(N), ensuring high performance for extremely large arrays.