Use a prefix sum approach to find the partition points in one pass to split an array into three parts with equal sums.
💡 Model Answer
To split an array into three contiguous parts with equal sums, first compute the total sum. If it is not divisible by 3, return false. Let target = total / 3. Iterate through the array, maintaining a running sum. When the running sum equals target, record the index as the first cut. Continue; when the running sum equals 2 * target, record the second cut. If both cuts are found before the end of the array, the array can be partitioned. Complexity is O(n) time and O(1) extra space. Example in Python:
def can_split(nums):
total = sum(nums)
if total % 3 != 0:
return False
target = total // 3
cur = 0
first = second = -1
for i, v in enumerate(nums):
cur += v
if first == -1 and cur == target:
first = i
elif first != -1 and second == -1 and cur == 2 * target:
second = i
break
return first != -1 and second != -1 and second < len(nums) - 1This algorithm handles negative numbers and zeros correctly and runs in linear time.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500