Drill

ProblemsPython › data

The imbalance across a split

mediumdataPython

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

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

Solve it in the editor →

Where you start

def split_imbalance(values: list[int], at: int) -> int:
    

Worked examples

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

Hint

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

Reference solution in Python
def split_imbalance(values: list[int], at: int) -> int:
    total = sum(values)
    if at <= 0:
        return -total
    if at >= len(values):
        return total
    left = sum(values[:at])
    right = sum(values[at:])
    return left - right

The same problem in another language

More data problems in Python