
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
Split Array with Equal Sum in C++
Suppose we have an array with n integers, we have to find if there are triplets (i, j, k) which follows these conditions −
0 < i, i + 1 < j, j + 1 < k < n - 1
Sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) will be same.
The subarray (L, R) is a slice of the original array starting from the element indexed L to the element indexed R.
So, if the input is like [1,2,1,2,1,2,1], then the output will be True, as i = 1, j = 3, k = 5.
sum(0, i - 1) = 1 sum(0, 0) = 1 sum(i + 1, j - 1) = 1 sum(2, 2) = 1 sum(j + 1, k - 1) = 1 sum(4, 4) = 1 sum(k + 1, n - 1) = 1 sum(6, 6) = 1
To solve this, we will follow these steps −
n := size of nums
Define an array sums of size n
sums[0] := nums[0]
-
for initialize i := 1, when i < n, update (increase i by 1), do −
sums[i] := sums[i] + (nums[i] + sums[i - 1])
-
for initialize j := 3, when j − n, update (increase j by 1), do −
Define one set s
-
for initialize i := 1, when i < j - 1, update (increase i by 1), do: −
sum1 := sums[i - 1]
sum2 := sums[j - 1] - sums[i]
-
if sum1 is same as sum2, then −
insert sum1 into s
-
for initialize k := j + 2, when k < n - 1, update (increase k by 1), do −
sum1 := sums[k - 1] - sums[j]
sum2 := sums[n - 1] - sums[k]
-
if sum1 is same as sum2 and sum1 is in s, then −
return true
return false
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool splitArray(vector<int>& nums) { int n = nums.size(); vector<int> sums(n); sums[0] = nums[0]; for (int i = 1; i < n; i++) { sums[i] += (nums[i] + sums[i - 1]); } for (int j = 3; j < n; j++) { set<int> s; for (int i = 1; i < j - 1; i++) { int sum1 = sums[i - 1]; int sum2 = sums[j - 1] - sums[i]; if (sum1 == sum2) s.insert(sum1); } for (int k = j + 2; k < n - 1; k++) { int sum1 = sums[k - 1] - sums[j]; int sum2 = sums[n - 1] - sums[k]; if (sum1 == sum2 && s.count(sum1)) return true; } } return false; } }; main(){ Solution ob; vector<int> v = {1,2,1,2,1,2,1}; cout << (ob.splitArray(v)); }
Input
{1,2,1,2,1,2,1}
Output
1