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:
Check if List is Strictly Increasing - Python
Next article icon

Python | Find groups of strictly increasing numbers in a list

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list of integers, write a Python program to find groups of strictly increasing numbers. 

Examples:

Input : [1, 2, 3, 5, 6] Output : [[1, 2, 3], [5, 6]]  Input : [8, 9, 10, 7, 8, 1, 2, 3] Output : [[8, 9, 10], [7, 8], [1, 2, 3]]

Approach #1 : Pythonic naive This is a naive approach which uses an extra input list space. It makes use of a for loop and in every iteration, it checks if the next element increments from previous by 1. If yes, append it to the current sublist, otherwise, create another sublist. 

Python3




# Python3 program to Find groups
# of strictly increasing numbers within
 
def groupSequence(lst):
    res = [[lst[0]]]
 
    for i in range(1, len(lst)):
        if lst[i-1]+1 == lst[i]:
            res[-1].append(lst[i])
 
        else:
            res.append([lst[i]])
    return res
     
# Driver program
l = [8, 9, 10, 7, 8, 1, 2, 3]
print(groupSequence(l))
 
 
Output:
[[8, 9, 10], [7, 8], [1, 2, 3]]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n).

Approach #2 : Alternate naive This is an alternative to the above mentioned naive approach. This method is quite simple and straight. It constructs a start_bound list and an end_bound list, which contains the position of starting and ending sequence of increasing integers. Thus simply return the bounds using for loops. 

Python3




# Python3 program to Find groups
# of strictly increasing numbers within
 
def groupSequence(l):
    start_bound = [i for i in range(len(l)-1)
        if (l == 0 or l[i] != l[i-1]+1)
        and l[i + 1] == l[i]+1]
 
    end_bound = [i for i in range(1, len(l))
        if l[i] == l[i-1]+1 and
        (i == len(l)-1 or l[i + 1] != l[i]+1)]
 
    return [l[start_bound[i]:end_bound[i]+1]
    for i in range(len(start_bound))]
     
# Driver program
l = [8, 9, 10, 7, 8, 1, 2, 3]
print(list(groupSequence(l)))
 
 
Output:
[[8, 9, 10], [7, 8], [1, 2, 3]]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as two additional lists are created with a maximum size of n.

Approach #3 : Using iterable and yield This approach uses another list ‘res’ and an iterable ‘it’. A variable ‘prev’ is used for keeping the record of previous integer and start is used for getting the starting position of the increasing sequence. Using a loop, in every iteration, we check if start element is a successor of prev or not. If yes, we append it to res, otherwise, we simply yield the res + [prev] as list element. 

Python3




# Python3 program to Find groups
# of strictly increasing numbers within
 
def groupSequence(x):
    it = iter(x)
    prev, res = next(it), []
 
    while prev is not None:
        start = next(it, None)
 
        if prev + 1 == start:
            res.append(prev)
        elif res:
            yield list(res + [prev])
            res = []
        prev = start
     
# Driver program
l = [8, 9, 10, 7, 8, 1, 2, 3]
print(list(groupSequence(l)))
 
 
Output:
[[8, 9, 10], [7, 8], [1, 2, 3]]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as two additional lists are created with a maximum size of n.

Approach #4 : Using itertools Python itertools provides operations like cycle and groupby which are used in this method. First we form another list ‘temp_list‘ using cycle. Cycle generates an infinitely repeating series of values. Then we group the temp_list accordingly using groupby operation and finally yield the desired output. 

Python3




# Python3 program to Find groups
# of strictly increasing numbers within
from itertools import groupby, cycle
 
def groupSequence(l):
    temp_list = cycle(l)
 
    next(temp_list)
    groups = groupby(l, key = lambda j: j + 1 == next(temp_list))
    for k, v in groups:
        if k:
            yield tuple(v) + (next((next(groups)[1])), )
 
     
# Driver program
l = [8, 9, 10, 7, 8, 1, 2, 3]
print(list(groupSequence(l)))
 
 
Output:
[(8, 9, 10), (7, 8), (1, 2, 3)]

Approach #5: Using recursion

This approach uses recursion to find groups of strictly increasing numbers. The function find_groups takes two arguments – the input list and the index of the current element being processed. Initially, the index is set to 0. The function returns a list of lists, where each inner list represents a group of strictly increasing numbers.

Algorithm:

  1. If the index is equal to the length of the input list, return an empty list.
  2. Initialize the current element to the value at the current index.
  3. Find the groups of strictly increasing numbers starting from the next index recursively.
  4. If the next group starts with the current element + 1, add the current element to the start of the next group.
  5. If the next group is empty or does not start with the current element + 1, create a new group starting with the current element.
  6. Return the list of groups.

Python3




def find_groups(l, index=0):
    if index == len(l):
        return []
 
    current_element = l[index]
    groups = find_groups(l, index + 1)
 
    if len(groups) > 0 and groups[0][0] == current_element + 1:
        groups[0].insert(0, current_element)
    else:
        groups.insert(0, [current_element])
 
    return groups
 
 
# Driver program
l = [8, 9, 10, 7, 8, 1, 2, 3]
print(find_groups(l))
 
 
Output
[[8, 9, 10], [7, 8], [1, 2, 3]]

Time complexity: O(n^2), where n is the length of the input list. This is because in the worst case, we may have to check each element against every other element.
Auxiliary space: O(n), where n is the length of the input list. This is because we are creating a list of lists to store the groups.



Next Article
Check if List is Strictly Increasing - Python

S

Smitha Dinesh Semwal
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Group each increasing and decreasing run in list
    Given a list, the task is to write a Python program to group each increasing and decreasing run. This is known as a monotonous grouping. A list is monotonic if it is either monotone increasing or monotone decreasing. A list A is monotone decreasing if for all i <= j, A[i] >= A[j]. Example: Inp
    9 min read
  • Check if List is Strictly Increasing - Python
    We are given a list of numbers and our task is to check whether the list is strictly increasing meaning each element must be greater than the previous one. For example: a = [1, 3, 5, 7] this is strictly increasing and b = [1, 3, 3, 7], this is not strictly increasing as 3 appears twice. Using all()
    2 min read
  • Reverse sequence of strictly increasing integers in a list-Python
    The task of reversing the sequence of strictly increasing integers in a list in Python involves identifying consecutive increasing subsequences and reversing each subsequence individually. For example, given a list a = [0, 1, 9, 8, 7, 5, 3, 14], the goal is to reverse the strictly increasing subsequ
    3 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
  • Counting number of unique values in a Python list
    Counting the number of unique values in a Python list involves determining how many distinct elements are present disregarding duplicates. Using a SetUsing a set to count the number of unique values in a Python list leverages the property of sets where each element is stored only once. [GFGTABS] Pyt
    2 min read
  • Print all Strong Numbers in Given List - Python
    The task of printing all Strong numbers from a given list in Python involves iterating through the list and checking each number based on its digit factorial sum. A Strong number is a number whose sum of the factorials of its digits equals the number itself. For example, given a list a = [145, 375,
    4 min read
  • Python - List of N size increasing lists
    Given integer N and M, construct increasing list till M, each list being N size i.e all combinations lists. Input : N = 2, M = 3 Output : [(1, 2), (1, 3), (2, 3)] Explanation : Increasing paired elements. Input : N = 1, M = 4 Output : [(1, ), (2, ), (3, ), (4, )] Explanation : Increasing paired elem
    4 min read
  • Python program to find the group sum till each K in a list
    Given a List, the task is to write a Python program to perform grouping of sum till K occurs. Examples: Input : test_list = [2, 3, 5, 6, 2, 6, 8, 9, 4, 6, 1], K = 6 Output : [10, 6, 2, 6, 21, 6, 1] Explanation : 2 + 3 + 5 = 10, grouped and cumulated before 6. Input : test_list = [2, 3, 5, 6, 2, 6, 8
    3 min read
  • Python | Find missing numbers in a sorted list range
    Given a range of sorted list of integers with some integers missing in between, write a Python program to find all the missing integers. Examples: Input : [1, 2, 4, 6, 7, 9, 10] Output : [3, 5, 8] Input : [5, 6, 10, 11, 13] Output : [7, 8, 9, 12] Method #1: List comprehension [GFGTABS] Python # Pyth
    5 min read
  • Find Number of M Contiguous Elements of a List with a Given Sum - Python
    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 probl
    3 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