# Program to find a sub-list of size at least 2 whose sum is multiple of k in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of non-negative numbers called nums and another positive value k. We have to find check whether there is any sublist of length at least 2 whose sum is multiple of k or not.

So, if the input is like nums = [12, 6, 3, 4] k = 5, then the output will be True, as the sublist is [12, 3] sums to 15 which is divisible by 5.

To solve this, we will follow these steps −

• sum := 0
• m := a new map
• m[0] := -1
• for i in range 0 to size of nums, do
• sum := sum + nums[i]
• sum := sum mod k
• if sum is present in m, then
• if i - m[sum] >= 2, then
• return True
• otherwise,
• m[sum] := i
• return False

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, nums, k):
sum = 0
m = {}
m[0] = -1
for i in range(0, len(nums)):
sum += nums[i]
sum %= k
if sum in m:
if i - m[sum] >= 2:
return True
else:
m[sum] = i
return False
ob = Solution()
nums = [12, 6, 3, 4]
k = 5
print(ob.solve(nums, k))

## Input

[12, 6, 3, 4], 5

## Output

True
Updated on 19-Nov-2020 06:34:05

Advertisements