Skip to content

How to Fix Activity Selection Errors

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about How to Fix Activity Selection Errors. We cover key concepts, practical examples, and best practices.

Fix activity selection errors when sort by end time vs start time confusion or no sorting before greedy.

Quick Fix

Wrong

def act(activities):
    activities.sort()  # sorts by start time, not end time!
    count=1; end=activities[0][1]
    for s,e in activities[1:]:
        if s>=end: count+=1; end=e
    return count

Sorting by start time fails. Example: [[1,10],[2,3],[4,5]] sorted by start gives 1 activity, optimal is 2.

def act(activities):
    activities.sort(key=lambda x:x[1])  # sort by end time
    count=1; end=activities[0][1]
    for s,e in activities[1:]:
        if s>=end: count+=1; end=e
    return count
[[1,2],[3,4],[0,6],[5,7],[8,9],[5,9]] -> 4 activities. O(n log n).

Prevention

Sort by end time. Pick first activity. For each subsequent, if start >= last end, pick it.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is activity selection?

Maximum non-overlapping activities. Sort by end time, greedy pick.

Why sort by end?

Ending earlier leaves more room for subsequent activities. Optimal greedy choice.

Proof?

Exchange argument: optimal solution can be transformed to include activity with earliest end.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro