← Questions

Split an array into two halves with equal sums

0
MetaCoding

A coding interview question asked at Meta. It tests arrays and prefix sums.

You are given an array nums of positive integers. Find an index i that splits it into two non-empty contiguous parts with the same sum:

  • the left part is nums[0..i] (it includes nums[i]),
  • the right part is nums[i+1..n-1].

Return i, or -1 if no such index exists.

def find_split_index(nums: list[int]) -> int: ...

Constraints

  • 0 <= len(nums) <= 10^5
  • 1 <= nums[k] <= 10^9
  • Both parts must contain at least one element.

Example 1

nums = [4, 2, 3, 3]
output: 1

Left [4, 2] sums to 6 and right [3, 3] sums to 6.

Example 2

nums = [1, 2, 5]
output: -1

The total is 8, but no prefix sums to 4 (the prefixes are 1, 3, 8).

Aim for O(n) time and O(1) extra space.

Clarifying questions

  • If several indices work, which one should be returned? (With positive values, at most one can.)
  • Is an array with fewer than two elements answered with -1?
  • Could values ever be zero or negative in a later version?
  • Do sums need 64-bit arithmetic (up to 10^5 * 10^9)?

What a strong answer covers

  • Computes the total once; returns -1 right away if it is odd or the array has fewer than two elements.
  • Walks the array with a running prefix sum and returns i when the prefix equals half the total, stopping at n - 2 so the right part is not empty.
  • Notes that with positive values the prefix sums strictly increase, so the split, if any, is unique and the scan can stop once the prefix passes half.
  • O(n) time and O(1) space, with 64-bit or arbitrary-size sums.
  • Tests both examples, [x, x], a single element, and an empty array.

Follow-ups

  • Allow zero and negative values: return every valid index.
  • Split into three parts with equal sums.
  • Split into two non-contiguous groups with equal sums.

Where it's asked

What it tests

arrays · prefix sums

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding