# Program to make sum divisible by P in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have an array nums and another value p, we remove the smallest subarray (not the whole array) such that the sum of the remaining values is divisible by p. We have to find the length of the smallest subarray that we need to remove, if there is no such subarray then return -1.

So, if the input is like nums = [8,2,6,5,3] p = 7, then the output will be 1 because if we remove 3, then total sum will be 21 and that is divisible by 7.

To solve this, we will follow these steps −

• ans := infinity
• s := (sum of all elements in nums) mod p
• d := a map contains key-value pair {0: -1}
• cum := 0
• if s is same as 0, then
• return 0
• for i in range 0 to size of nums, do
• cum := cum + nums[i]
• r := cum mod p
• if (r-s)mod p is present in d, then
• ans := minimum of ans and i - d[(r-s) mod p]
• d[r] := i
• return ans if ans < size of nums otherwise -1

## Example

Let us see the following implementation to get better understanding −

def solve(nums, p):
ans = float("inf")
s = sum(nums) % p
d = {0:-1}
cum = 0
if s == 0:
return 0
for i in range(len(nums)):
cum+=nums[i]
r = cum%p
if (r-s)%p in d:
ans = min(ans, i-d[(r-s)%p])
d[r] = i
return ans if ans<len(nums) else -1

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

## Input

[8,2,6,5,3], 7

## Output

1
Updated on 04-Oct-2021 10:00:07