def eraseOverlapIntervals(intervals):
intervals.sort(key=lambda x: x[1])
end = float('-inf')
count = 0
for s, e in intervals:
if s >= end:
end = e
else:
count += 1
return count
Gas Station
def canCompleteCircuit(gas, cost):
if sum(gas) < sum(cost): return -1
tank = start = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
tank = 0
return start
Trapping Rain Water
// C++ — Two pointers
int trap(vector<int>& height) {
int l = 0, r = height.size() - 1;
int leftMax = 0, rightMax = 0, water = 0;
while (l < r) {
if (height[l] < height[r]) {
if (height[l] >= leftMax) leftMax = height[l];
else water += leftMax - height[l];
l++;
} else {
if (height[r] >= rightMax) rightMax = height[r];
else water += rightMax - height[r];
r--;
}
}
return water;
}
More Problems
Problem
Pattern
Complexity
Partition Labels
Last occurrence, greedy partition
O(n), O(1)
Candy
Left-to-right, right-to-left passes
O(n), O(n)
Skyline Problem
Max-heap, sweep line
O(n log n)
✏️ Exercise: Implement Interval Scheduling (non-overlapping), Gas Station, and Trapping Rain Water. Aim to solve all three within 45 min.