Python coding

Ranges not inside another

Each range is a pair [start, end] of integers with start <= end. A range lies inside another one when the other starts no later and ends no earlier: [2, 5] lies inside [1, 5], [2, 8] and [1, 9], but not inside [3, 9]. Remove every range that lies inside a different range of the list, and return how many ranges are left. Copies of the same range count as one range.

The list is not sorted, may be empty and values can be negative. Comparing every pair is O(n²): aim for O(n log n).

Besides the tests, one large input (3,500 ranges) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • count_outer_ranges([[1,4],[3,6],[2,8]]) → 2
  • count_outer_ranges([[1,2],[1,4],[3,4]]) → 1
  • count_outer_ranges([[1,2],[3,4],[5,6]]) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Sort by start. Every range that could hold the current one now comes before it, and the best candidate is simply the one that reaches farthest.

Hint 2

Keep the farthest end seen so far. The current range lies inside an earlier one exactly when its end is not past that farthest end.

Hint 3

Ties decide it: with equal starts, put the longer range first (key (start, -end)), or [1, 2] is checked before [1, 4] and wrongly survives.

Solution and why it works
pythonO(n log n) · O(n) for the sorted copy
def count_outer_ranges(ranges: list[list[int]]) -> int:
    kept, reach = 0, None
    # Equal starts: longer range first, so the shorter one meets its holder before it.
    for start, end in sorted(ranges, key=lambda r: (r[0], -r[1])):
        if reach is None or end > reach:   # no earlier range ends this late: none holds it
            kept += 1
            reach = end
    return kept

After sorting by start, any range that could hold the current one comes earlier, and the one reaching farthest is the only candidate worth checking: the current range lies inside an earlier one exactly when its end is ≤ the farthest end so far. The trap is ties: with equal starts the longer range must come first (key (start, -end)), or [1, 2] is checked before [1, 4] and survives. A copy fails the same check, so copies count once.