Snippets

Camilo Rocha Minimal Interval Covering algorithm

Created by Camilo Rocha last modified Camilo Rocha
# input:  L and H integers with L<=H, and a[0..N) array of pairs of
#         integers, with a[i][0]<a[i][1] for 0 <= i < N and N>=0,
#         representing closed intervals [a[i][0],a[i][1]] covering the
#         closed interval [L,H]
#
# output: an array b[0..M) with indexes of a[0..N) representing a
#         minimal interval covering of [L,H] with intervals in a
#
# time complexity O(N) without sorting; O(N log N) with sorting

def mic(L,H,a):
  a.sort()
  ans,low,n,N = list(),L,0,len(a)
  while low<H and n!=N:
    best,n = n,n+1
    while n!=N and a[n][0]<=low:
      if a[n][1]>a[best][1]:
        best = n
      n += 1
    ans.append(best)
    low = a[best][1]
  return ans

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.