Skip to content

Instantly share code, notes, and snippets.

@fakemonk1
Last active October 13, 2022 03:06
Show Gist options
  • Save fakemonk1/cc412195b3a3f6f7e44f61709bd9586e to your computer and use it in GitHub Desktop.
Save fakemonk1/cc412195b3a3f6f7e44f61709bd9586e to your computer and use it in GitHub Desktop.
Codility Demo Test - Java Solution
// 100% marks solution for the github demo test
// Find an index in an array such that its prefix sum equals its suffix sum.
class Solution {
public int solution(int[] A) {
if(A.length == 0){
return -1;
}
long leftSum = 0;
long rightSum = getSum(A);
for (int i = 0; i < A.length ; i++) {
if(leftSum == rightSum - A[i]){
return i;
}
leftSum = leftSum + A[i];
rightSum = rightSum - A[i];
}
return -1;
}
public long getSum(int[] A){
long sum = 0;
for (int i :A){
sum = sum + i;
}
return sum;
}
public static void main(String[] args) {
System.out.println(new Solution().solution(new int[]{-1, 3, -4, 5, 1, -6, 2, 1}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment