MEDIUM NC#132 Blind #37 Intervals / Greedy

435. Non-overlapping Intervals

๐Ÿ“– Problem

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Greedy reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Sort intervals by end time
  • โ†’ Count non-overlapping intervals greedily
  • โ†’ If current start < last end, they overlap
  • โ†’ Time: O(n log n), Space: O(1)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขSort intervals by end time
  • โ€ขCount non-overlapping intervals greedily
  • โ€ขIf current start < last end, they overlap

Common Pitfalls

  • โ€ขTime: O(n log n), Space: O(1)

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
eraseOverlapIntervals([[1,2],[2,3],[3,4],[1,3]]);
Expected:
1
Test Case 2
Not run
Input:
eraseOverlapIntervals([[1,2],[1,2],[1,2]]);
Expected:
2
Test Case 3
Not run
Input:
eraseOverlapIntervals([[1,2],[2,3]]);
Expected:
0

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit