
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Partition Array into Three Parts with Equal Sum in Python
Suppose we have an array A of integers, our output will be true if and only if we can partition the array into three non-empty parts whose sum is equal.
Formally, we can partition the array if we can find the indexes i+1 < j with (A[0] + A[1] + ... + A[i] is same as A[i+1] + A[i+2] + ... + A[j-1] and A[j] + A[j-1] + ... + A[A.length - 1])
So if the input is [0,2,1,-6,6,-7,9,1,2,0,1], then the output will be true. Three arrays will be [0,2,1], [-6,6,-7,9,1] and [2,0,1]
To solve this, we will follow these steps −
- temp := sum of all elements, and required_sum := temp / 3
- set sum_left to store cumulative sum from left to right
- set sum_right to store cumulative sum from right to left
- index1 := 0 and index2 := length of the array – 1
- while index1 < index2:
- while index1 < index2 and sum_left[index1] != required_sum
- index1 := index1 + 1
- while index2 > index1 and sum_right[index2] != required_sum
- index2 := index2 – 1
- if index1 < index2 and index1 != index2, then return true, otherwise false
- while index1 < index2 and sum_left[index1] != required_sum
Example
Let us see the following implementation to get better understanding −
class Solution(object): def canThreePartsEqualSum(self, A): temp = sum(A) if (temp%3 != 0): return 0 sum_left=[0 for i in range(len(A))] sum_left[0] = A[0] sum_right=[0 for i in range(len(A))] sum_right[-1] = A[-1] for i in range(1,len(A)): sum_left[i] = A[i]+sum_left[i-1] for i in range(len(A)-2,-1,-1): sum_right[i] = A[i]+sum_right[i+1] #print(sum_left,sum_right) required_sum = temp/3 index1 = 0 index2 = len(A)-1 while index1 < index2: while index1 <index2 and sum_left[index1]!=required_sum: index1+=1 while index2>index1 and sum_right[index2]!=required_sum: index2-=1 return index1<index2 and index1 != index2 ob1 = Solution() print(ob1.canThreePartsEqualSum([0,2,2,-6,6,-7,9,2,2,0,2]))
Input
[0,2,1,-6,6,-7,9,1,2,0,1]
Output
true
Advertisements