Program to find number of elements can be removed to make odd and even indexed elements sum equal in Python


Suppose we have a list of numbers called nums. Now consider a function say f(i) which deletes the element at index i and then returns true or false, depending the resulting list's sum of even index values is same as the sum of odd index values or not. So we need the number of indexes for which f would return true.

So, if the input is like nums = [6, 8, 5, 2, 3], then the output will be 2 becuase, if we remove 8, the array will be [6, 5, 2, 3], the odd and even index elements sum is 8, so they are same. Another possible solution is, if we remove 2, the array will be [6, 8, 5, 3], here odd and even indexed elements sum is 11, so they are same.

To solve this, we will follow these steps −

  • n := size of nums
  • a := a 2d list of order 2 x (n+1) and fill each with 0s
  • for each index i and value x nums, do
    • a[0, i + 1] := a[0, i]
    • a[1, i + 1] := a[1, i]
    • a[i mod 2, i + 1] := a[i mod 2, i + 1] + x
  • c := 0
  • s := sum of all elements present in nums
  • for i in range 0 to n - 1, do
    • e := a[0, i] - a[0, 0] + a[1, n] - a[1, i + 1]
    • if e * 2 is same as s - nums[i], then
      • c := c + 1
  • return c

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   n = len(nums)
   a = [[0] * (n + 1), [0] * (n + 1)]
   for i, x in enumerate(nums):
      a[0][i + 1] = a[0][i]
      a[1][i + 1] = a[1][i]
      a[i % 2][i + 1] += x

   c = 0
   s = sum(nums)
   for i in range(n):
      e = a[0][i] - a[0][0] + a[1][n] - a[1][i + 1]
      if e * 2 == s - nums[i]:
         c += 1
   return c

nums = [6, 8, 5, 2, 3]
print(solve(nums))

Input

[6, 8, 5, 2, 3]

Output

2

Updated on: 18-Oct-2021

462 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements