I have a list of elements, where each element is a non-negative integer range. I want to filter the list in such a way that only largest unenclosed ranges are separated out. And I want to do this in O(n)
manner with single loop. This list will always be sorted according to starting integer of each ranges.An enclosed range element may occur before or after the enclosing range element in the list.
Example:
Suppose the list that I have is {[0-12],[5-15],[5-20],[10-20],[11-30],[25-42],[28-40]}
. In this list, ranges [5-15]
and [10-20]
fall within [5-20]
range so I need to discard them. Similarly range element [28-40]
is discarded as it falls within range [25-42]
.
I want to do this filtering using a single loop to achieve O(n)
time complexity.
Would it be possible to achieve this ? If not, what is the best way to do filtering with complexity more than O(n)
. A solution in Java would be great.
The time complexity of the filter function is O(n) as well. At this moment, the total time complexity is O(2n). The last step is reduce function. We apply the result of the filter function to reduce function.
complexity for list is O(n) and for set it is O(1) which is constant.
Time complexity is defined as the amount of time taken by an algorithm to run, as a function of the length of the input. It measures the time taken to execute each statement of code in an algorithm. It is not going to examine the total execution time of an algorithm.
An element could swallow previous one if they have the same range start but bigger or equal end. Also the element could swallow next if the next one's range end less than current eleemnt's end.
So you go through the list and compare current and next elements.
If they have the currentStart=nextStart and nextEnd>=currentEnd -> remove current.
else If nextEnd<=currentEnd -> remove next.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With