Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 numbers 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].
Algorithm
To solve this, we will follow these steps ?
Sort the list nums
Insert infinity at the end of nums to handle the last interval
Initialize an empty result list and start pointer
Iterate through the list and check for breaks in continuity
When a break is found, add the current interval to results
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, nums):
nums.sort()
nums.append(float('inf')) # Add infinity to handle last interval
ans = []
start = nums[0]
for i in range(1, len(nums)):
if nums[i] != nums[i-1] + 1:
ans.append([start, nums[i-1]])
start = nums[i]
return ans
# Test the solution
ob = Solution()
nums = [10, 11, 12, 15, 16, 17, 28, 30]
print(ob.solve(nums))
The output of the above code is ?
[[10, 12], [15, 17], [28, 28], [30, 30]]
How It Works
The algorithm works by identifying breaks in the sequence of consecutive numbers. When nums[i] is not equal to nums[i-1] + 1, it means the current contiguous interval has ended. We then store the interval [start, nums[i-1]] and update the start pointer to begin a new interval.
Alternative Approach Using Groupby
Here's another approach using Python's itertools.groupby ?
from itertools import groupby
def find_intervals(nums):
nums.sort()
intervals = []
for k, g in groupby(enumerate(nums), lambda x: x[1] - x[0]):
group = list(g)
intervals.append([group[0][1], group[-1][1]])
return intervals
# Test the alternative approach
nums = [10, 11, 12, 15, 16, 17, 28, 30]
print(find_intervals(nums))
The output is ?
[[10, 12], [15, 17], [28, 28], [30, 30]]
Conclusion
Both approaches effectively find contiguous intervals in a unique array. The first method uses a simple iteration with break detection, while the second leverages groupby for a more functional programming style. Choose based on readability preferences and performance requirements.
