Program to find length of smallest sublist that can be deleted to make sum divisible by k in Python


Suppose we have a list with positive values, called nums and also have a positive number k. We have to find the length of the shortest sublist (may be empty) that we can delete from nums, such that sum of the remaining elements is divisible by k. But we cannot remove the entire list. If there is no such sublist to delete, return -1.

So, if the input is like nums = [5,8,6,3] k = 8, then the output will be 1, because current sum of the elements of [5,8,6,3] is 22. If we remove sublist [6] of length 1, then sum is 16, which is divisible by 8.

To solve this, we will follow these steps −

  • rem := (sum of all elements present in nums + k) mod k
  • if rem is same as 0, then
    • return 0
  • n := size of nums
  • presum := 0
  • mp := a dictionary, initially store -1 for key 0
  • res := n
  • for i in range 0 to n - 1, do
    • presum := presum + nums[i]
    • m :=(presum + k) mod k
    • mp[m] := i
    • if (m - rem + k) mod k is present in mp, then
      • res := minimum of res and (i - mp[(m - rem + k) mod k])
  • return res if res is not same as n otherwise -1

Example

Let us see the following implementation to get better understanding −

def solve(nums, k):
   rem = (sum(nums) + k) % k
   if rem == 0:
      return 0
   n, presum = len(nums), 0
   mp = {0: -1}
   res = n
   for i in range(n):
      presum += nums[i]
      m = (presum + k) % k
      mp[m] = i
      if (m - rem + k) % k in mp:
         res = min(res, i - mp[(m - rem + k) % k])
   return res if res != n else -1

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

Input

[5,8,6,3], 8

Output

1

Updated on: 18-Oct-2021

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements