- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to find contiguous intervals of a unique array in Python

Suppose we have a list of unique numbers called nums. We have to find a sorted 2D matrix of numbers where each list represents an inclusive interval summarizing number that are contiguous in nums.

So, if the input is like nums = [10, 11, 12, 15, 16, 17, 28, 30], then the output will be [[10, 12], [15, 17], [28, 28], [30, 30]], as in the list [10 to 12], [15 to 17] are contiguous, and 28 and 30 are there, they are represented as [28 to 28] and [30 to 30].

To solve this, we will follow these steps−

sort the list nums

insert infinity at the end of nums

ans:= a new list

l:= nums[0]

for i in range 1 to size of nums, do

if nums[i] is not same as nums[i-1] + 1, then

insert [l, nums[i-1]] at the end of ans

l:= nums[i]

return ans

Let us see the following implementation to get better understanding−

## Example

class Solution: def solve(self, nums): nums.sort() nums.append(1e9) ans=[] l=nums[0] for i in range(1,len(nums)): if nums[i] != nums[i-1] + 1: ans.append([l, nums[i-1]]) l=nums[i] return ans ob = Solution() nums = [10, 11, 12, 15, 16, 17, 28, 30] print(ob.solve(nums))

## Input

[10, 11, 12, 15, 16, 17, 28, 30]

## Output

[[10, 12], [15, 17], [28, 28], [30, 30]]

- Related Articles
- Program to find total unique duration from a list of intervals in Python
- Program to find partition array into disjoint intervals in Python
- Program to find maximum product of contiguous subarray in Python
- Program to find length of contiguous strictly increasing sublist in Python
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find sum of the sum of all contiguous sublists in Python
- Program to find sum of unique elements in Python
- Program to find length of longest interval from a list of intervals in Python
- Program to find intervals by merging target interval in Python
- C program to find the unique elements in an array.
- Program to find length of longest contiguous sublist with same first letter words in Python
- Find contiguous unmasked data in a masked array in Numpy
- Program to find largest product of three unique items in Python
- Program to find length of concatenated string of unique characters in Python?
- Program to find the number of unique integers in a sorted list in Python