Find all good indices in the given Array in Python

Server Side ProgrammingProgrammingPython

Suppose we have an array A of numbers, we have to find all indices of this array so that after deleting the ith element from the array, the array will be a good array. We have to keep in mind that −

  • Good array is an array with an element that equals to the sum of all other elements.
  • 1-based indexing will be used here.

So, if the input is like [10, 4, 6, 2], then the output will be [1,4] as when we remove A[1], the array will look like [4, 6, 2] and it is good, as 6 = 4+2. If we delete A[4], the array will look like [10, 4, 6] and it is also good, as 10 = 4+6.

To solve this, we will follow these steps −

  • n := size of A
  • add := 0
  • my_map := a new map
  • for i in range 0 to n, do
    • my_map[A[i]] := my_map[A[i]] + 1
    • add := add + A[i]
  • for i in range 0 to n, do
    • k := add - A[i]
    • if k mod 2 is same as 0, then
      • k := k/2
      • if k in my_map, then
        • if (A[i] is same as k and my_map[k] > 1) or (A[i] is not same as k), then
          • display i + 1

Example

Let us see the following implementation to get better understanding −

 Live Demo

from collections import defaultdict
def find_indices(A):
   n = len(A)
   add = 0
   my_map = defaultdict(lambda:0)
   for i in range(n):
      my_map[A[i]] += 1
      add += A[i]
   for i in range(n):
      k = add - A[i]
      if k % 2 == 0:
         k = k >> 1
         if k in my_map:
            if ((A[i] == k and my_map[k] > 1) or (A[i] != k)):
               print((i + 1))
A = [10, 4, 6, 2]
find_indices(A)

Input

[10, 4, 6, 2]

Output

1
4
raja
Published on 23-Jul-2020 12:14:57
Advertisements