- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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−

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))

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

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

- Related Questions & Answers
- Program to find total unique duration from a list of 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 length of longest interval from a list of intervals in Python
- Program to find sum of the sum of all contiguous sublists in Python
- Program to find sum of unique elements in Python
- Find Intersecting Intervals in Python
- Program to find intervals by merging target interval in Python
- Program to find length of concatenated string of unique characters in Python?
- Contiguous Array in C++
- C program to find the unique elements in an array.
- Program to find the number of unique integers in a sorted list in Python
- Program to find overlapping intervals and return them in ascending order in Python
- Program to find intervals that do not intersect the cut interval in Python

Advertisements