Search code examples
javaalgorithmtime-complexityspace-complexity

Cover a given range of an array


I'm trying to figure out the algorithm to implement a method and I would need some advice in the regard. I have given an array and range,

A = [1, 15, 30, 40, 50]
range =  10

I need to figure out the minimum number of points that would cover all the numbers of the given array.

Cover means that distance you can reach both left and right with the provided range. For example, if I have a point at 23 and range of 5, then I can reach 18-23 left side and 23-28 right side. The points can cover both the left and the right sides of the given range.

In the provided array the result is 3. We would need one point at 1, another at 15, and 3rd one at 40. I explain it below,

i. The point at 1 will cover till 10 (1-10)
ii. The point at 15 will cover itself (15)
iii.  The point at 40 will cover left till the 30 and at the right till the 50 (30-40-50)

Please, provide a good reason before you attempt to downvote. Thank you.


Solution

  • If the array is sorted one can use greedy algorithm. I also assume that all number in the input are positive.

    Consider the following steps:

    1. Int cover = -1, points= new array
    2. For each element in the array:
       2.1 . If element > cover then:
           2.1.1 cover = element + range - 1 // biggest value that still cover the element
           2.1.2 push to point cover value
    

    The points array will contain the mimium points needed to cover the array for given range

    Complexity: assuming n is the size of the input array:

    Time complexity is O(n) if the array is sorted and O(nlogn) if not. Space complexity is O(k) when k is the number of cover points which bounded by n. If all you want is the number of the points then space complexity is O(1)

    If the points can only be chosen from the array you can modify the algorithm as follow:

    1. Int cover = -1, points= new array
    2. For each i in the array.length:
        2.1 If array[i] > cover then:
            2.1.1 cover = array[i] //element can cover itself 
            2.1.2 for (j=i+1; array[j] < array[i] + range; j++) // find the largest element who still cover array[i]
                2.1.2.1 cover = array[j] // element in index j cover also index i
            2.1.3 push to point cover value
            2.1.4 add range to cover // to mark for cover after a[j]
    

    The space complexity is the same. Time complexity is also O(n) - because every step the inner loop (j) is doing the i-loop we fail the condition of the if statement - so we stay with O(n).