Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Count occurrence of all elements of list in a tuple
Next article icon

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.

Table of Content

  • Using List Comprehension
  • Using itertools Combinations
  • Using Brute Force with Nested Loops

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
Python | Count occurrence of all elements of list in a tuple
author
madarsh986
Improve
Article Tags :
  • Python
  • Python Programs
  • python-list
  • Python list-programs
Practice Tags :
  • python
  • python-list

Similar Reads

  • Python program to find sum of elements in list
    Finding the sum of elements in a list means adding all the values together to get a single total. For example, given a list like [10, 20, 30, 40, 50], you might want to calculate the total sum, which is 150. Let's explore these different methods to do this efficiently. Using sum()sum() function is t
    3 min read
  • Sum of number digits in List in Python
    Our goal is to calculate the sum of digits for each number in a list in Python. This can be done by iterating through each number, converting it to a string, and summing its digits individually. We can achieve this using Python’s built-in functions like sum(), map(), and list comprehensions. For exa
    2 min read
  • Python | Count occurrence of all elements of list in a tuple
    Given a tuple and a list as input, write a Python program to count the occurrences of all items of the list in the tuple. Examples: Input : tuple = ('a', 'a', 'c', 'b', 'd') list = ['a', 'b'] Output : 3 Input : tuple = (1, 2, 3, 1, 4, 6, 7, 1, 4) list = [1, 4, 7] Output : 6 Approach #1 : Naive Appro
    5 min read
  • Python - Find the frequency of numbers greater than each element in a list
    Given a list, a new list is constructed that has frequency of elements greater than or equal to it, corresponding to each element of the list. Input : test_list = [6, 3, 7, 1, 2, 4] Output : [2, 4, 1, 6, 5, 3] Explanation : 6, 7 are greater or equal to 6 in list, hence 2. Input : test_list = [6, 3,
    8 min read
  • Python - Check whether the given List forms Contiguous Distinct Sub-Array or Not
    You are given an array consisting of elements in the form A1, A2, A3.......An. The task is to find whether the array can be formed as a Contiguous Distinct Sub Array or Not. You need to find whether the array can be converted to contiguous sub-arrays that consist of similar elements and there are a
    6 min read
  • Count the Sublists Containing given Element in a List - Python
    Given a list of lists our task is to count the number of sublists containing the given element x. For example: li = [[1, 3, 5], [1, 3, 5, 7], [1, 3, 5, 7, 9]] and x = 1 then output will be 3. Using List ComprehensionThis method uses list comprehension to check for the presence of the given element i
    3 min read
  • How to Get the Number of Elements in a Python List
    In Python, lists are one of the most commonly used data structures to store an ordered collection of items. In this article, we'll learn how to find the number of elements in a given list with different methods. Example Input: [1, 2, 3.5, geeks, for, geeks, -11]Output: 7 Let's explore various ways t
    3 min read
  • Get the indices of all occurrences of an element in a list - Python
    We are given a list and our task is to find all the indices where a particular element occurs. For example, if we have a list like [1, 2, 3, 2, 4, 2] and the element is 2, then the output will be [1, 3, 5] because 2 appears at these positions. Using List ComprehensionList comprehension allows for a
    2 min read
  • Python Program to convert a list into matrix with size of each row increasing by a number
    Given a list and a number N, the task here is to write a python program to convert it to matrix where each row has N elements more than previous row elements from list. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 3 Output : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10
    6 min read
  • Sum of Consecutive Numbers with Overlapping in Lists
    The task of summing consecutive numbers with overlapping in a list involves iterating over the elements and adding each element to the next one, with the last element being paired with the first to form a circular sum. The goal is to efficiently compute the sum of consecutive elements while ensuring
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences