Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/2d-submatrix-sum-queries/1
Count Indices to Balance Even and Odd Sums
Given an array arr[], count the number of indices such that deleting the element at that index and shifting all elements after it one position left results in an array where the sum of elements at even indices equals the sum at odd indices.
Examples:
Input: arr[] = [2, 1, 6, 4]
Output: 1
Explaination: After removing arr[1], the resulting array will be [2, 6, 4] the sums of elements at odd index is arr[1] = 6 and the sum of elements at even index is arr[0] + arr[2] = 6.
Input: arr[] = [1, 1, 1]
Output: 3
Explaination: Removing any element makes the sum of odd and even indexed elements equal.
Constraints:
1 β€ arr.size() β€ 105
0 β€ arr[i] β€ 104
Solution:
class Solution:
def cntWays(self, arr):
n = len(arr)
pe = [0](n+1)
po = [0](n+1)
for i in range(n):
pe[i+1] = pe[i]
po[i+1] = po[i]
if i % 2 == 0:
pe[i+1] += arr[i]
else:
po[i+1] += arr[i]
se = pe[n]
so = po[n]
ans = 0
for i in range(n):
even = pe[i] + (so - po[i] - (arr[i] if i % 2 == 1 else 0))
odd = po[i] + (se - pe[i] - (arr[i] if i % 2 == 0 else 0))
if even == odd:
ans += 1
return ans
Top comments (0)