
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Program to find largest average of sublist whose size at least k in Python
- Program to find size of smallest sublist whose sum at least target in Python
- Program to find sum of rectangle whose sum at most k in Python
- Program to find three unique elements from list whose sum is closest to k Python
- Program to find elements from list which have occurred at least k times in Python
- Program to find k where k elements have value at least k in Python
- Program to count number of paths whose sum is k in python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to find length of longest substring with character count of at least k in Python
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Find the largest area rectangular sub-matrix whose sum is equal to k in C++
- Program to check whether list can be partitioned into pairs where sum is multiple of k in python
- Program to find number of sublists with sum k in a binary list in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to find length of longest increasing subsequence with at least k odd values in Python

Advertisements