Find the sums for which an array can be divided into subarrays of equal sum in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of integers A; we have to find all the values for sum so that for a value sum[i] the array can be divided into sub-arrays of sum sum[i]. If we cannot divide the array into sub-arrays of equal sum then return -1.

So, if the input is like A = [2, 4, 2, 2, 2, 4, 2, 6], then the output will be [6,8,12] as the array can be divided into sub-arrays of sum 6, 8 and 12. These are as follows: [{2, 4}, {2, 2, 2}, {4, 2}, {6}] [{2, 4, 2}, {2, 2, 4},{2, 6}] [{2, 4, 2, 2, 2},{4, 2, 6

To solve this, we will follow these steps −

  • n := size of a

  • table := an array of size n and filled with 0

  • table[0] := a[0]

  • for i in range 1 to n, do

    • table[i] := a[i] + table[i - 1]

  • S := table[n - 1]

  • my_map := a new map

  • for i in range 0 to n, do

    • my_map[table[i]] := 1

  • answer := a new set

  • for i in range 1 to integer part of (square root of (S)) + 1, do

    • if S mod i is same as 0, then

      • is_present := True

      • part_1 := i

      • part_2 := quotient of S / i

      • for j in range part_1 to S + 1, update in each step by part_1, do

        • if j not in my_map, then

          • is_present := False

          • come out from the loop

      • if is_present is true and part_1 is not same as S, then

        • add(part_1) of answer

      • is_present := True

      • for j in range quotient of (S / i) to S + 1, update in each step by S // i, do

        • if j not in my_map, then

          • is_present := False;

          • come out from the loop

      • if is_present and part_2 is not same as S, then

        • add(part_2) of answer

  • if size of answer is same as 0, then

    • return -1

  • return answer

Example

Let us see the following implementation to get better understanding −

 Live Demo

from math import sqrt
def find_sum(a) :
   n = len(a)
   table = [0] * n
   table[0] = a[0]
   for i in range(1, n) :
      table[i] = a[i] + table[i - 1]
   S = table[n - 1]
   my_map = {}
   for i in range(n) :
      my_map[table[i]] = 1
   answer = set()
   for i in range(1, int(sqrt(S)) + 1) :
      if (S % i == 0) :
         is_present = True;
         part_1 = i
         part_2 = S // i
         for j in range(part_1 , S + 1, part_1) :
            if j not in my_map :
               is_present = False
               break
         if (is_present and part_1 != S) :
            answer.add(part_1)
         is_present = True
         for j in range(S // i , S + 1 , S // i) :
            if j not in my_map:
               is_present = False;
               break
         if (is_present and part_2 != S) :
            answer.add(part_2)
   if(len(answer) == 0) :
      return -1
   return answer
a = [2, 4, 2, 2, 2, 4, 2, 6]
print(find_sum(a))

Input

[2, 4, 2, 2, 2, 4, 2, 6]

Output

{8, 12, 6}
raja
Published on 27-Aug-2020 12:23:37
Advertisements