Prepin
Log in

Divide an array into two sub-arrays that have equal sums.

Approach / Explanation

This question requires you to divide an array into two subarrays that have equal sums. To clarify this question, let’s outline the steps: Begin with an array as input. An array is a structure that can store a fixed number of items, all of the same type. You will need to separate this array into two distinct sub-arrays. Remember that a sub-array is a contiguous segment of the array. The sums of the elements in each of the sub-arrays must be equal. As you tackle this problem, keep in mind that it involves iterating through the array, calculating sums of various combinations of elements, and comparing these sums to identify two points where they are equal. Furthermore, be aware that it’s possible for no such division to exist. In those instances, your program should output an appropriate response (such as false, null, or an exception).

Suggested Answer

Given an array such as [1, 5, 11, 5], one possible approach is to divide the array in the middle. This creates two subarrays: [1, 5] and [11, 5], both of which sum to 6. Here’s a way to implement this in Python: def find_partition ( arr ) : total = sum ( arr ) # if the total sum isn't even, two subsets with equal sum aren't possible if total % 2 != 0 : return False sub_sum = total // 2 dp = [ False ] * ( sub_sum + 1 ) # dynamic programming array dp [ 0 ] = True # 0 sum is always achievable for num in arr : for j in range ( sub_sum , num - 1 , - 1 ) : dp [ j ] = dp [ j ] or dp [ j - num ] return dp [ sub_sum ]

Alternative Answer

For a more varied array, such as [1, 2, 3, 4, 5, 6, 7, 8], simply dividing it in the middle will not suffice. A proper partition would be [1, 2, 3, 7] and [4, 5, 6, 8], both of which total 13. You can utilize the same Python function defined in the earlier example as follows: arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] if ( find_partition ( arr ) ) : print ( "Can be divided." ) else : print ( "Can't be divided." ) This will produce the output "Can be divided.", signifying that there exists a partition that divides the array into two subarrays with equal sums.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.