Drill

ProblemsTypeScript › data

The imbalance across a split

mediumdataTypeScript

A load balancer divides a batch at one index and wants the difference between the two halves.

splitImbalance(values: list<int>, at: int) → int

Solve it in the editor →

Where you start

function splitImbalance(values: number[], at: number): number {
  
}

Worked examples

CallResult
splitImbalance([1,2,3,4], 2)-4
splitImbalance([5,3,8], 1)-6
splitImbalance([1,2,3], 0)-6
splitImbalance([1,2,3], 3)6

Hint

Handle the out-of-range slices first, then sum each side and subtract.

Reference solution in TypeScript
function splitImbalance(values: number[], at: number): number {
  const total = values.reduce((a: number, b: number) => a + b, 0);
  if (at <= 0) return -total;
  if (at >= values.length) return total;
  let left = 0;
  for (let i = 0; i < at; i++) left += values[i];
  let right = 0;
  for (let i = at; i < values.length; i++) right += values[i];
  return left - right;
}

The same problem in another language

More data problems in TypeScript