Given a list ‘L’, a sum ‘S’ and number of elements to take at a time ‘m’. The task is to find how many ways sum s can be found by adding any m contiguous elements.
Input : 1 2 1 3 2 3 2 Output : 2 Input : 1 1 1 1 1 1 3 2 Output : 0
For example 1, we have to find a sum 3 with the help of any 2 contiguous elements of the list. This can be done in two ways 1+2 and 2+1 so answer is 2
Method 1: (Simple)
Starting from beginning we select first m elements and find their sum if sum = s then increment the count by one, and increment index position by one select next m elements and repeat the same until the whole list is covered.
Time complexicity: O(n^2) in worst case.
Method 2: (Efficient)
Initialize a variable index as 0 and curr_sum as the first element. index indicates the count of contiguous elements and curr_sum indicates the sum of the current index elements. Start from the second element and add all elements one by one to the curr_sum. If curr_sum becomes equal to the sum and index becomes equal to m, then increment the value of count by 1. If index exceeds the m, then remove trailing elements and initialize index as m-1.
The time complexity of method 2 looks more than O(n), but if we take a closer look at the program, then we can figure out the time complexity is O(n). We can prove it by counting the number of operations performed on every element of arr in the worst case. There are at most 2 operations performed on every element: (a) the element is added to the curr_sum (b) the element is subtracted from curr_sum. So the upper bound on the number of operations is 2n which is O(n).
- Python program to find sum of elements in list
- Python program to find N largest elements from a list
- Python program to find smallest number in a list
- Python program to find second largest number in a list
- Python program to find largest number in a list
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python program to swap two elements in a list
- Python program to interchange first and last elements in a list
- Python | Find missing elements in List
- Python | Find elements of a list by indices
- Python | Find all elements count in list
- Python | Find sum of frequency of given elements in the list
- Python program to apply itertools.product to elements of a list of lists
- Python | Find common elements in list of lists
- Python | Find top K frequent elements from a list of tuples