# Check if at least half array is reducible to zero by performing some operation in Python

Suppose, we are provided with a list of size n that contains positive integers and another positive integer m. Let's say, we are currently inside a loop and in each iteration, we decrease the value of some elements in the array by 1 and increase the value of the remaining elements by m. We have to find out if half or more of the elements of the list turn into zero after some iterations. We return True if possible, and False if not.

So, if the input is like input_list = [10, 18, 35, 5, 12], m = 4, then the output will be True.

To solve this, we will follow these steps −

• frequency_list := a new list of size m+1 initialized with 0
• i := 0
• while i < size of input_list, do
• frequency_list[input_list[i] mod(m + 1) ] :=

frequency_list[input_list[i] mod (m + 1) ] + 1

• i := i + 1
• i := 0
• while i <= m, do
• if frequency_list[i] >=(size of input_list / 2) , then
• come out from the loop
• i := i + 1
• if i <= m, then
• return True
• otherwise,
• return False

## Example

Let us see the following implementation to get better understanding −

Live Demo

def solve(input_list, m):
frequency_list = [0] * (m + 1)
i = 0
while(i < len(input_list)):
frequency_list[(input_list[i] % (m + 1))] += 1
i += 1
i = 0
while(i <= m):
if(frequency_list[i] >= (len(input_list)/ 2)):
break
i += 1
if (i <= m):
return True
else:
return False
input_list = [10, 18, 35, 5, 12]
print(solve(input_list, 4))

## Input

[10, 18, 35, 5, 12], 4

## Output

True

Advertisements