#1013

Partition Array Into Three Parts With Equal Sum

Easy
ArrayGreedyHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach leverages the fact that if we can find two partitions that equal one-third of the total sum, the remaining elements will automatically sum to the same value. This reduces the problem to a linear scan of the array.

⚙️

Algorithm

5 steps
  1. 1Step 1: Calculate the total sum of the array.
  2. 2Step 2: If the total sum is not divisible by 3, return false.
  3. 3Step 3: Set a target sum as total sum divided by 3.
  4. 4Step 4: Traverse the array while maintaining a running sum and a count of how many times we reach the target sum.
  5. 5Step 5: If we reach the target sum twice before the last element, return true.
solution.py20 lines
1# Full working Python code
2
3def can_partition(arr):
4    total_sum = sum(arr)
5    if total_sum % 3 != 0:
6        return False
7    target = total_sum // 3
8    current_sum = 0
9    count = 0
10    for i in range(len(arr)):
11        current_sum += arr[i]
12        if current_sum == target:
13            count += 1
14            current_sum = 0
15        if count == 2 and i < len(arr) - 1:
16            return True
17    return False
18
19# Example usage
20print(can_partition([0,2,1,-6,6,-7,9,1,2,0,1]))  # Output: True

Complexity note: This complexity is linear because we only traverse the array once, maintaining a running sum and a count.

  • 1The total sum must be divisible by 3 for a valid partition to exist.
  • 2Finding the first two partitions that equal one-third of the total sum is sufficient to confirm the third.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.