Skip to content
LEETFLIX

Partition Array Into Two Arrays to Minimize Sum Difference

Solve on LeetCode

Hard · two pointers solution for Partition Array Into Two Arrays to Minimize Sum Difference. Python, Go, and a step-by-step animation.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 2035. Partition Array Into Two Arrays to Minimize Sum Difference. The copyrighted prompt is on LeetCode. This page is a working two pointers solution for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

nums =
[2, 7, 11, 15]
target =
9

Output

[0, 1]

2 + 7 = 9. The inward walk finds the pair in one comparison.

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Partition Array Into Two Arrays to Minimize Sum Difference — two pointers

On a sorted array the pair that sums to target is found by walking inward. Built for LeetCode 2035. Partition Array Into Two Arrays to Minimize Sum Difference.

If the current sum is too small, the only way to grow it is to advance lo. If it is too big, retreat hi. Each step discards an index forever, so the walk is linear.

Algorithm

  1. Set lo = 0, hi = n−1.
  2. While lo < hi, compare nums[lo] + nums[hi] to target.
  3. Equal → return the indices. Too small → lo++. Too big → hi--.
Time
O(n)
Space
O(1)

Assumes the array is sorted.

Solution.py
class Solution:    def partitionArrayIntoTwoArraysToMinimizeSumDifference(self, nums: list[int], target: int) -> list[int]:        lo, hi = 0, len(nums) - 1        while lo < hi:            s = nums[lo] + nums[hi]            if s == target:                return [lo, hi]            if s < target:                lo += 1            else:                hi -= 1        return []
Watch this run

03

Interactive walkthrough

Playing “Partition Array Into Two Arrays to Minimize Sum Difference — two pointers”. Edit the input, hit Run, then scrub.

Approach: Partition Array Into Two Arrays to Minimize Sum Difference — two pointers

Loading animation…