Split an array into two halves with equal sums
I was asked this
No reports yet. Sign in to say where you were asked it.
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 includesnums[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^51 <= 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
-1right away if it is odd or the array has fewer than two elements. - Walks the array with a running prefix sum and returns
iwhen the prefix equals half the total, stopping atn - 2so 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 andO(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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
