Merge Intervals

A coding challenge about Intervals Merging

I finished an interesting coding problem and I want to share it here.

Interval merging refers to combining several overlapping intervals into a single interval. This process is useful in various applications, such as consolidating time slots or ranges of numbers.

Python Function to Merge Intervals

Below is a Python function that merges overlapping intervals:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def merge_intervals(intervals):
# Sort the intervals by their starting point
intervals = sorted(intervals, key=lambda x: x[0])
merged = []
for interval in intervals:
# If the current interval overlaps with the last interval in merged, merge them
if merged and interval[0] <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], interval[1])
else:
# If they don't overlap, add the current interval to merged
merged.append(interval)
return merged

# Example usage
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
merged_intervals = merge_intervals(intervals)
print(merged_intervals)
# Output: [[1, 6], [8, 10], [15, 18]]

Theoretical Basics of Greedy Algorithms

By choosing the local optimum at every stage, we aim to achieve the global optimum. The key to selecting a greedy algorithm is: it’s possible to deduce the global optimum from the local optimum.

How to verify if you can use greedy:

  1. Provide a counterexample: If you can’t think of a counterexample, try harder.
  2. Mathematical induction.

Steps for a greedy algorithm:

  1. Decompose the problem into several sub-problems.
  2. Identify an appropriate greedy strategy.
  3. Find the optimal solution for each sub-problem.
  4. Stack the local optimums to form a global optimum.

Example: Leetcode 455: Distributing Cookies

  • Local Optimum: Give the largest cookie to the child with the biggest appetite.

  • Global Optimum: Feed as many children as possible.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
def sort(self, nums):
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[j] < nums[i]:
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp

def findContentChildren(self, g, s):
self.sort(g)
self.sort(s)
count = 0
i = 0 # pointer to g
j = 0 # pointer to s

while i < len(g) and j < len(s):
if s[j] - g[i] >= 0:
count += 1
i += 1
j += 1
else:
j += 1

return count

:D 一言句子获取中...