869905. Split an array into two equal Sum subarrays

Easy

Split an array into two equal Sum subarrays

Slug: split-an-array-into-two-equal-sum-subarrays Difficulty: Easy Id: 869905 Topic Tags: prefix-sum, sliding-window, Arrays Company Tags: Facebook

Summary

Given a non-empty array of integers, we need to divide it into two parts such that the sum of elements in both parts is equal. This problem can be solved using the concept of prefix sum and sliding window.

Detailed Explanation

The approach to solve this problem involves calculating the total sum of the array and then finding the mid-point of the array. We can use a sliding window approach, starting from the beginning of the array and moving towards the end. At each step, we calculate the current sum of the elements in the window and check if it is equal to half of the total sum.

Here's a step-by-step breakdown of the solution:

  1. Calculate the total sum of the array.
  2. Find the mid-point of the array.
  3. Start a sliding window from the beginning of the array, moving towards the end.
  4. At each step, calculate the current sum of the elements in the window.
  5. Check if the current sum is equal to half of the total sum.
  6. If it is, return the current window as the first part and the remaining array as the second part.

Time complexity: O(n) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int[] splitArray(int[] arr) {
    int n = arr.length;
    int totalSum = 0;
    for (int num : arr) {
        totalSum += num;
    }
    int mid = totalSum / 2;
    int leftSum = 0;
    int start = 0, end = 0;
    for (int i = 0; i < n; i++) {
        leftSum += arr[i];
        if (leftSum == mid) {
            return new int[] { Arrays.copyOfRange(arr, start, i + 1), Arrays.copyOfRange(arr, i + 1, n) };
        }
    }
    return null;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.