feat(work): implement eraseOverlapIntervals solution for non-overlapping intervals problem

This commit is contained in:
Prad Nukala committed 2026-09-30 15:52:50 -04:00
1 parent 57a5917e09
commit e1c8f1a0f1
1 file changed
+18 -6
@@ -12,7 +12,7 @@ make the rest of the intervals non-overlapping.
Note that intervals which only touch at a point are non-overlapping. Note that intervals which only touch at a point are non-overlapping.
For example, [1, 2] and [2, 3] are non-overlapping. For example, [1, 2] and [2, 3] are non-overlapping.
Example 1: Example 1:
@@ -35,17 +35,29 @@ Output: 0
Explanation: You don't need to remove any of the intervals since Explanation: You don't need to remove any of the intervals since
they're already non-overlapping. they're already non-overlapping.
Constraints: Constraints:
• 1 <= intervals.length <= 10^5 • 1 <= intervals.length <= 10^5
• intervals[i].length == 2 • intervals[i].length == 2
• -5 * 10^4 <= starti < endi <= 5 * 10^4 • -5 * 10^4 <= starti < endi <= 5 * 10^4
""" """
class Solution: class Solution:
def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int: def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:
intervals.sort(key=lambda x: x[0])
result = []
for start, end in intervals:
# Use '<' to avoid intervals which touch
if result and start < result[-1][1]:
result[-1][1] = min(result[-1][1], end)
else:
result.append([start, end])
# Difference between original and result is to remove
return len(intervals) - len(result)