Python | Consecutive remaining elements in list
Sometimes, while working with Python list, we can have a problem in which we need to get the consecutive elements count remaining( including current ), to make certain decisions beforehand. This can be a potential subproblem of many competitive programming competitions. Let’s discuss a shorthand which can be applied to solve this problem. Method : Using range() + from_iterable() + groupby() + list comprehension This task can be performed and solved using combination of above functions. In this, we first use groupby function to form groups and convert them into reverse ranges using range(). This all is converted to generator to avoid creation of nested list and then final list is obtained using from_iterable().
The original list is : [4, 4, 5, 5, 5, 1, 1, 2, 4] Consecutive remaining elements list : [2, 1, 3, 2, 1, 2, 1, 1, 1]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the new res list
Please Login to comment...