• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LilyLiya
博客园    首页    新随笔    联系   管理    订阅  订阅
Merge Overlapping Intervals
Array, sorting with respect to the starting value; intervals

refer to: https://www.algoexpert.io/questions/Merge%20Overlapping%20Intervals


Problem Statement

Sample example

Analysis

step 1: sort the intervals by their start value

step 2: check if the end value of the previous interval is larger than the start value of the latter interval

Code

def mergeOverlappingIntervals(intervals):
    # sort the intervals by startinf value.  O(nlogn)
    sortedIntervals = sorted(intervals, key = lambda x: x[0])
    
    mergedIntervals = []# space: O(n)
    currentInterval = sortedIntervals[0]#initialize the currentInterval as the first interval of the intervals
    mergedIntervals.append(currentInterval)#initialize the mergedIntervals as the first interval of the intervals
    
    for nextInterval in sortedIntervals:# for the first iteration, no update
        _, currentIntervalEnd = currentInterval
        nextIntervalStart, nextIntervalEnd = nextInterval
        
        if currentIntervalEnd >= nextIntervalStart: # overlap found, update the end value of interval
            currentInterval[1] = max(currentIntervalEnd, nextIntervalEnd)
        else: # no overlap, add the current(nextInterval) into the mergedIntervals array
            currentInterval = nextInterval
            mergedIntervals.append(currentInterval)
    return mergedIntervals

Time and Space complexity

O(nlogn) time complexity for sorting

O(n) space complexity for store the mergedIntervals(upper bound, all intervals kept)

 

 

 

posted on 2021-07-19 08:53  LilyLiya  阅读(168)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3