This is the problem from online hackerrank online platform. Nikita and the Game
I coded this and my solution passes only the given testcases, it is giving segmentation fault for other testcases on submit.
I compared my approach with editorial solutions, and one of the solution uses same approach as mine(the binary search approach to find the index at which we'll be able to split the array).
But i can't figure out why is it giving the segmentation fault.
#include <bits/stdc++.h>
#define lld long long
using namespace std;
lld isPossible(vector<lld>&pre_sum, lld start, lld end){
lld low = start-1;
lld high = end;
while(start<=end){
lld mid = (start+end)/2;
lld left_sum = pre_sum[mid] - pre_sum[low];
lld right_sum = pre_sum[high]- pre_sum[mid];
if(left_sum == right_sum) return mid;
if(left_sum < right_sum) start = mid+1;
if(left_sum > right_sum) end = mid-1;
}
return -1;
}
lld calcAns(vector<lld>&pre_sum, lld start, lld end){
//cout<<start<<" "<<end<<"\n";
lld idx = isPossible(pre_sum, start, end);
//cout<<idx<<"\n";
if(idx == -1) return 0;
return 1 + max(calcAns(pre_sum, start, idx), calcAns(pre_sum, idx+1, end));
}
/*
* Complete the arraySplitting function below.
*/
lld arraySplitting(vector<lld> arr) {
vector<lld> pre_sum(arr.size() + 1);
pre_sum[0] = 0;
for(lld i=0; i<arr.size(); i++){
pre_sum[i+1] = pre_sum[i] + arr[i];
}
lld ans = calcAns(pre_sum, 1, pre_sum.size()-1);
//cout<<ans<<"\n";
return ans;
}
int main()
{
lld t;
cin >> t;
for (lld t_itr = 0; t_itr < t; t_itr++) {
lld arr_count;
cin >> arr_count;
vector<lld> arr(arr_count);
for (lld arr_itr = 0; arr_itr < arr_count; arr_itr++) {
lld arr_item;
cin>>arr_item;
arr[arr_itr] = arr_item;
}
lld result = arraySplitting(arr);
cout << result << "\n";
}
return 0;
}
Explanation of code:
isPossible function finds the index at which the sum of the left part [start....mid]
of the array is equal to the right part [mid+1.....end]
.
calcAns calculates the no of possible such indexes in a way that once it will finds such index, it will ignore one part and finds in other part if any such possible. It will calculate maximum no. of such possible splittings.
arraySplitting just calculates the prefix sum array pre_sum
and is one size more than the actual array, i.e first index have sum zero, so that it will ease calculations later while calculating sums between a range. It calls calcAns function for further processing.
EDIT: i want to learn debugging cases without actually having to use debugger as testcases are not downloadable during a contest submission. so i want to learn what thing's am i missing which causes segmentation faults as i started training myself for programming contests. If someone can predict on seeing the code that these type of tescases is possible where my code probably can give segmentation fault, will be helpful. This is what i'm actually looking for, otherwise it is not any benefit that i debug large testcases by using gdb on setting breakpoints after the contest.