Back to course home
0% completed
Vote For New Content
Why not to use prefix sum approch to solve this problem
Ravat Tailor
Apr 21, 2025
Explanation:
- Calculate prefix sum and suffix sum
- check where both the prefix sum and suffix sum are equals that would be our resulting index and break the loop
- if not matches then resulting index is -1
- time complexity and space complexity both are O(n)
// Method to find the index where the sum of elements to the left equals the sum of elements to the right public int findMiddleIndex(int[] nums) { int[] prefixSum = new int[nums.length]; int[] suffixSum = new int[nums.length]; prefixSum[0] = 0; suffixSum[nums.length-1] = 0; for(int i =1; i< nums.length; i++) { prefixSum[i] = prefixSum[i-1] + nums[i-1]; } for(int i= nums.length-2;i>=0;i--) { suffixSum[i] = suffixSum[i+1] + nums[i+1]; } int outputIndex = -1; for(int i =0; i< nums.length; i++) { if(prefixSum[i] == suffixSum[i]) { outputIndex = i; break; } } return outputIndex; }
0
0
Comments
Comments