Find the Value of the Partition - Problem

You are given a positive integer array nums and need to partition it into two non-empty arrays to minimize a specific value.

Goal: Split nums into two arrays nums1 and nums2 such that:

  • Each element belongs to exactly one array
  • Both arrays are non-empty
  • The partition value is minimized

The partition value is defined as: |max(nums1) - min(nums2)|

Example: For nums = [1, 3, 2, 4], if we partition into nums1 = [1, 2] and nums2 = [3, 4], then the partition value is |max([1,2]) - min([3,4])| = |2 - 3| = 1.

Return the minimum possible partition value.

Input & Output

example_1.py โ€” Basic case
$ Input: [1, 3, 2, 4]
โ€บ Output: 1
๐Ÿ’ก Note: After sorting: [1, 2, 3, 4]. The optimal partition is [1] and [2, 3, 4] where |max([1]) - min([2,3,4])| = |1 - 2| = 1. All consecutive pairs have difference 1, so minimum is 1.
example_2.py โ€” Larger gaps
$ Input: [1, 10, 2, 7]
โ€บ Output: 1
๐Ÿ’ก Note: After sorting: [1, 2, 7, 10]. Consecutive differences are: 2-1=1, 7-2=5, 10-7=3. The minimum difference is 1, achieved by partitioning into [1] and [2, 7, 10].
example_3.py โ€” Two elements
$ Input: [5, 8]
โ€บ Output: 3
๐Ÿ’ก Note: With only two elements, there's only one way to partition: [5] and [8]. The partition value is |5 - 8| = 3.

Constraints

  • 2 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109
  • All elements are positive integers
  • Array must be partitioned into exactly two non-empty parts

Visualization

Tap to expand
Optimal Team Division StrategyPlayers by skill: 1, 2, 3, 41234SPLITTeam ASkill: 1Max: 1Team BSkills: 2, 3, 4Min: 2Fairness CalculationGap = |Max(Team A) - Min(Team B)|Gap = |1 - 2| = 1๐Ÿ’กKey Insight: After sorting, optimal split always occurs between consecutive elements!Just find the smallest gap between adjacent players - that's your answer!
Understanding the Visualization
1
Line Up Players
Sort all players by their skill levels from weakest to strongest
2
Find Best Split Point
The fairest division occurs where consecutive skill levels are closest
3
Minimize Skill Gap
Choose the split that minimizes the gap between the strongest player on the weaker team and weakest player on the stronger team
Key Takeaway
๐ŸŽฏ Key Insight: Sort first, then the minimum partition value is simply the smallest difference between consecutive elements - no complex partition testing needed!
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
26.2K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen