Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find a sub-list of size at least 2 whose sum is multiple of k in Python
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
- if i - m[sum] >= 2, then
- otherwise,
- m[sum] := i
- return False
Let us see the following implementation to get better understanding −
Example
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
Advertisements