Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to split a set into equal sum sets where elements in first set are smaller than second in Python
We need to split a list of numbers into two groups A and B such that they have equal sums, and every number in A is strictly smaller than every number in B.
For example, with nums = [3, 4, 5, 12], we can split into A = [3, 4, 5] and B = [12], both having sum 12.
Algorithm
The key insight is that after sorting, we need to find a split point where:
All elements before the split form group A
All elements from the split onwards form group B
Both groups have equal sums
The maximum element in A is less than the minimum element in B
Implementation
class Solution:
def solve(self, nums):
nums.sort()
total = sum(nums)
# If total sum is odd, equal split is impossible
if total % 2 != 0:
return False
target = total // 2
current_sum = 0
i = 0
while i < len(nums):
n = nums[i]
# Add all occurrences of the same number
while i < len(nums) and nums[i] == n:
current_sum += nums[i]
i += 1
# Check if we found the equal sum split point
if current_sum == target:
return True
# If we exceeded target, no valid split exists
if current_sum > target:
return False
return False
# Test the solution
ob = Solution()
nums = [3, 4, 5, 12]
print(ob.solve(nums))
True
How It Works
The algorithm works by:
Sorting the array to ensure natural ordering
Calculating target sum as half of total sum
Grouping identical elements together to maintain the constraint
Checking split points only after processing all occurrences of each unique value
Additional Examples
ob = Solution()
# Example 1: Valid split
nums1 = [1, 1, 2, 4]
print(f"nums1 = {nums1}: {ob.solve(nums1)}")
# Example 2: No valid split (odd sum)
nums2 = [1, 2, 3]
print(f"nums2 = {nums2}: {ob.solve(nums2)}")
# Example 3: No valid split (can't satisfy constraint)
nums3 = [1, 3, 3, 5]
print(f"nums3 = {nums3}: {ob.solve(nums3)}")
nums1 = [1, 1, 2, 4]: True nums2 = [1, 2, 3]: False nums3 = [1, 3, 3, 5]: False
Conclusion
This solution efficiently finds valid splits by sorting first and checking split points only after processing complete groups of identical numbers. The time complexity is O(n log n) due to sorting.
