
- 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 number of consecutive subsequences whose sum is divisible by k in Python
Suppose we have an array nums and a value k. We have to find number of consecutive subsequences whose sum is divisible by k.
So, if the input is like k = 3 nums = [1,2,3,4,1], then the output will be 4 because the subsequences are [3], [1,2], [1,2,3] and [2,3,4].
To solve this, we will follow these steps −
- x := An array of size k and fill with 0
- x[0] := 1
- r:= 0, s:= 0
- for each elem in nums, do
- s :=(s + elem) mod k
- r := r + x[s]
- x[s] := x[s] + 1
- return r
Example
Let us see the following implementation to get better understanding −
def solve(k, nums): x = [0]*k x[0] = 1 r=s=0 for elem in nums: s = (s+elem) % k r += x[s] x[s] += 1 return r k = 3 nums = [1,2,3,4,1] print(solve(k, nums))
Input
3, [1,2,3,4,1]
Output
4
- Related Articles
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Find number of substrings of length k whose sum of ASCII value of characters is divisible by k in C++
- Program to find number of increasing subsequences of size k in Python
- Program to count number of paths whose sum is k in python
- C++ program to find largest or equal number of A whose sum of digits is divisible by 4
- Count pairs in array whose sum is divisible by K in C++
- Program to find sum of rectangle whose sum at most k in Python
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- Program to count number of consecutive lists whose sum is n in C++
- Program to find number of distinct subsequences in Python
- Program to Find Out the Largest K-Divisible Subsequence Sum in Python
- Check if an array can be divided into pairs whose sum is divisible by k in Python
- Program to find number of sublists whose sum is given target in python
- Python Program for Smallest K digit number divisible by X
- Program to find number of subsequences that satisfy the given sum condition using Python

Advertisements