Open In App

Find Number of M Contiguous Elements of a List with a Given Sum – Python

Last Updated : 18 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to find how many subsets of length m exist in a list such that their sum is equal to a given value.

For example, if the input list is [1, 2, 3, 4, 5], m = 2 and the target sum is 5, the subsets [2, 3] and [1, 4] satisfy the condition. Let’s go through multiple methods to solve this problem in Python.

Using Sliding Window

sliding window approach is an efficient method that avoids recalculating the sum of overlapping segments repeatedly.

Python
# Input list, segment length, and target sum
a = [1, 2, 3, 4, 5]
m = 2
tar_sum = 5

# Initialize variables
cur_sum = sum(a[:m])  # Sum of the first window
count = 0

# Check the first window
if cur_sum == tar_sum:
    cnt += 1

# Slide the window
for i in range(m, len(a)):
    cur_sum += a[i] - a[i - m]
    if cur_sum== tar_sum:
        cnt += 1
print(cnt) 

Output
1

Explanation:

  • We calculate the sum of the first m elements.
  • As the window slides, the new sum is updated by adding the next element and removing the first element of the previous window.
  • If the current sum matches the target, we increment the count.
  • This approach avoids recalculating sums from scratch and is efficient for large lists.

Let’s explore some more methods and see how we can find find number of m contiguous elements of a List with a given sum in Python.

Using List Comprehension

This method uses list slicing along with list comprehension and checks the sum of each segment of length m.

Python
# Input list, segment length, and target sum
a = [1, 2, 3, 4, 5]
m = 2
tar_sum = 5

# Calculate the count using list comprehension
cnt = sum(1 for i in range(len(a) - m + 1) if sum(a[i:i+m]) == tar_sum)
print(cnt) 

Output
1

Explanation:

  • For each valid starting index, we take a slice of length m and compute its sum.
  • If the sum equals the target, we increment the count.
  • This method recalculates the sum for each slice, making it less efficient than the sliding window approach.

Using itertools Combinations

This method considers all possible combinations of m elements in the list and checks their sums.

Python
from itertools import combinations

# Input list, segment length, and target sum
a = [1, 2, 3, 4, 5]
m = 2
tar_sum = 5

# Find the count of valid combinations
cnt = sum(1 for comb in combinations(a, m) if sum(comb) == tar_sum)
print(cnt) 

Output
2

Explanation:

  • The combinations function generates all subsets of length m.
  • Each subset is checked for its sum.
  • While simple, this approach does not restrict subsets to contiguous elements and for large lists it is computationally expensive.

Using Brute Force with Nested Loops

This is the least efficient method, as it computes the sum of each subarray independently.

Python
# Input list, segment length, and target sum
a = [1, 2, 3, 4, 5]
m = 2
tar_sum = 5

# Initialize count
count = 0

# Iterate through the list
for i in range(len(a) - m + 1):
    subarray = a[i:i + m]  # Extract the subarray
    if sum(subarray) == tar_sum:  # Check if its sum matches the target
        cnt += 1
print(cnt) 

Output
1

Explanation:

  • For each starting index, we extract a subarray of length m and calculate its sum.
  • If the sum equals the target, we increment the count.
  • This method is easy to understand but inefficient due to the redundant calculations of sums.


Next Article

Similar Reads