Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering out list elements with O(n) time complexity

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.

like image 317
swap310 Avatar asked May 30 '14 09:05

swap310


People also ask

What is the time complexity of filter?

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.

What is the time complexity of searching for an element in a list?

complexity for list is O(n) and for set it is O(1) which is constant.

What is the time complexity in java?

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.


1 Answers

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.

like image 148
StanislavL Avatar answered Oct 04 '22 21:10

StanislavL