Bird
Raised Fist0
DSA Rustprogramming

Activity Selection Problem in DSA Rust

Choose your learning style10 modes available
Mental Model
Choose the maximum number of activities that don't overlap by always picking the earliest finishing activity first.
Analogy: Imagine you have a single meeting room and many meetings to schedule. To fit the most meetings, always pick the meeting that ends soonest so the room becomes free earlier for the next meeting.
Activities (start-end):
[1-4]  [3-5]  [0-6]  [5-7]  [3-9]  [5-9]  [6-10]  [8-11]  [8-12]  [2-14]  [12-16]
Timeline:
|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|
 ↑    ↑    ↑    ↑    ↑    ↑    ↑    ↑    ↑    ↑    ↑    ↑    ↑    ↑    ↑    ↑
 1    2    3    4    5    6    7    8    9   10   11   12   13   14   15   16
Dry Run Walkthrough
Input: activities: [(1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16)]
Goal: Select the maximum number of non-overlapping activities from the list.
Step 1: Sort activities by their finish time
[(1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16)] -> sorted to -> [(1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16)] (already sorted by finish time)
Why: Sorting by finish time helps pick activities that free the room earliest.
Step 2: Select first activity (1,4)
Selected: [(1,4)]
Why: First activity always selected as it finishes earliest.
Step 3: Check next activity (3,5), overlaps with (1,4)? Yes, skip
Selected: [(1,4)]
Why: Activity (3,5) starts before (1,4) ends, so it overlaps.
Step 4: Check next activity (0,6), overlaps with (1,4)? Yes, skip
Selected: [(1,4)]
Why: Starts before previous selected activity ends.
Step 5: Check next activity (5,7), no overlap, select it
Selected: [(1,4), (5,7)]
Why: Starts after (1,4) ends, so can be selected.
Step 6: Check next activity (3,9), overlaps with (5,7)? Yes, skip
Selected: [(1,4), (5,7)]
Why: Starts before (5,7) ends.
Step 7: Check next activity (5,9), overlaps with (5,7)? Yes, skip
Selected: [(1,4), (5,7)]
Why: Starts at same time as (5,7), overlaps.
Step 8: Check next activity (6,10), overlaps with (5,7)? Yes, skip
Selected: [(1,4), (5,7)]
Why: Starts before (5,7) ends.
Step 9: Check next activity (8,11), no overlap, select it
Selected: [(1,4), (5,7), (8,11)]
Why: Starts after (5,7) ends.
Step 10: Check next activity (8,12), overlaps with (8,11)? Yes, skip
Selected: [(1,4), (5,7), (8,11)]
Why: Starts at same time as (8,11), overlaps.
Step 11: Check next activity (2,14), overlaps with (8,11)? Yes, skip
Selected: [(1,4), (5,7), (8,11)]
Why: Starts before (8,11) ends.
Step 12: Check next activity (12,16), no overlap, select it
Selected: [(1,4), (5,7), (8,11), (12,16)]
Why: Starts after (8,11) ends.
Result:
Selected activities: (1,4) -> (5,7) -> (8,11) -> (12,16)
Annotated Code
DSA Rust
#[derive(Clone)]
struct Activity {
    start: i32,
    finish: i32,
}

fn activity_selection(activities: &mut Vec<Activity>) -> Vec<Activity> {
    activities.sort_by_key(|a| a.finish); // sort by finish time
    let mut selected = Vec::new();
    if activities.is_empty() {
        return selected;
    }
    selected.push(activities[0].clone()); // select first activity
    let mut last_finish = activities[0].finish;
    for activity in activities.iter().skip(1) {
        if activity.start >= last_finish { // no overlap
            selected.push(activity.clone());
            last_finish = activity.finish; // update last finish
        }
    }
    selected
}

fn main() {
    let mut activities = vec![
        Activity { start: 1, finish: 4 },
        Activity { start: 3, finish: 5 },
        Activity { start: 0, finish: 6 },
        Activity { start: 5, finish: 7 },
        Activity { start: 3, finish: 9 },
        Activity { start: 5, finish: 9 },
        Activity { start: 6, finish: 10 },
        Activity { start: 8, finish: 11 },
        Activity { start: 8, finish: 12 },
        Activity { start: 2, finish: 14 },
        Activity { start: 12, finish: 16 },
    ];
    let selected = activity_selection(&mut activities);
    for act in selected {
        println!("({},{})", act.start, act.finish);
    }
}
activities.sort_by_key(|a| a.finish);
sort activities by their finish time to prioritize earliest finishing
selected.push(activities[0].clone());
select the first activity as it finishes earliest
if activity.start >= last_finish {
check if current activity starts after last selected activity finishes
selected.push(activity.clone());
select current activity as it does not overlap
last_finish = activity.finish;
update last finish time to current activity's finish
OutputSuccess
(1,4) (5,7) (8,11) (12,16)
Complexity Analysis
Time: O(n log n) because we sort the activities by finish time and then scan once
Space: O(n) because we store the selected activities in a separate list
vs Alternative: Naive approach tries all subsets with exponential time; greedy sorting reduces to O(n log n)
Edge Cases
empty activity list
returns empty selection without error
DSA Rust
if activities.is_empty() { return selected; }
all activities overlap
only the earliest finishing activity is selected
DSA Rust
if activity.start >= last_finish { ... }
activities with same finish time
selects the first one encountered, skips overlapping others
DSA Rust
activities.sort_by_key(|a| a.finish);
When to Use This Pattern
When you need to schedule the maximum number of non-overlapping intervals, use the greedy activity selection pattern by sorting on finish times.
Common Mistakes
Mistake: Sorting activities by start time instead of finish time
Fix: Sort activities by their finish time to ensure earliest finishing activities are chosen first
Mistake: Selecting overlapping activities without checking start time against last finish
Fix: Always check if current activity starts after or at the finish time of last selected activity
Summary
Selects the maximum number of activities that don't overlap by always choosing the earliest finishing activity next.
Use when you want to schedule as many non-overlapping intervals as possible.
The key insight is sorting by finish time lets you greedily pick activities that free up time earliest.

Practice

(1/5)
1. What is the main goal of the Activity Selection Problem?
easy
A. Calculate the total duration of all activities
B. Select the maximum number of activities that don't overlap in time
C. Sort activities by their start time
D. Find the activity with the longest duration

Solution

  1. Step 1: Understand the problem objective

    The Activity Selection Problem aims to choose the largest set of activities that do not overlap in their time intervals.
  2. Step 2: Identify the correct goal

    Among the options, only selecting the maximum number of non-overlapping activities matches the problem's goal.
  3. Final Answer:

    Select the maximum number of activities that don't overlap in time -> Option B
  4. Quick Check:

    Goal = Max non-overlapping activities [OK]
Hint: Focus on maximizing non-overlapping activities [OK]
Common Mistakes:
  • Confusing longest duration with maximum count
  • Sorting by start time only
  • Summing durations instead of counting activities
2. Which Rust code snippet correctly sorts a vector of activities by their finish time? Assume each activity is a tuple (start: i32, finish: i32).
easy
A. activities.sort_by_key(|a| a.1);
B. activities.sort_by_key(|a| a.0);
C. activities.sort_unstable_by(|a, b| b.1.cmp(&a.1));
D. activities.sort_by(|a, b| a.0.cmp(&b.0));

Solution

  1. Step 1: Identify sorting key for finish time

    Each activity is a tuple (start, finish). The finish time is at index 1.
  2. Step 2: Choose correct sorting method

    Sorting by finish time ascending uses sort_by_key(|a| a.1). activities.sort_by_key(|a| a.1); matches this.
  3. Final Answer:

    activities.sort_by_key(|a| a.1); -> Option A
  4. Quick Check:

    Sort by finish time = a.1 [OK]
Hint: Sort activities by finish time using .sort_by_key(|a| a.1) [OK]
Common Mistakes:
  • Sorting by start time instead of finish time
  • Sorting in descending order incorrectly
  • Using unstable sort unnecessarily
3. What is the output of the following Rust code that implements the activity selection logic?
let mut activities = vec![(1, 4), (3, 5), (0, 6), (5, 7), (8, 9), (5, 9)];
activities.sort_by_key(|a| a.1);
let mut selected = vec![activities[0]];
let mut last_finish = activities[0].1;
for &activity in &activities[1..] {
    if activity.0 >= last_finish {
        selected.push(activity);
        last_finish = activity.1;
    }
}
println!("{:?}", selected);
medium
A. [(1, 4), (3, 5), (5, 7), (8, 9)]
B. [(0, 6), (5, 7), (8, 9)]
C. [(1, 4), (5, 7), (8, 9)]
D. [(1, 4), (5, 9)]

Solution

  1. Step 1: Sort activities by finish time

    Sorted activities: [(1,4), (3,5), (0,6), (5,7), (8,9), (5,9)]
  2. Step 2: Select activities greedily

    Start with (1,4). Next, (3,5) starts before 4, skip. (0,6) starts before 4, skip. (5,7) starts at 5 ≥ 4, select. (8,9) starts at 8 ≥ 7, select. (5,9) starts at 5 < 7, skip.
  3. Final Answer:

    [(1, 4), (5, 7), (8, 9)] -> Option C
  4. Quick Check:

    Greedy selection = [(1,4),(5,7),(8,9)] [OK]
Hint: Pick earliest finishing activities that start after last finish [OK]
Common Mistakes:
  • Selecting overlapping activities
  • Not sorting by finish time first
  • Including activities starting before last finish
4. Identify the bug in this Rust code snippet for the Activity Selection Problem:
let mut activities = vec![(1, 3), (2, 5), (4, 7)];
activities.sort_by_key(|a| a.0);
let mut selected = vec![activities[0]];
let mut last_finish = activities[0].1;
for &activity in &activities[1..] {
    if activity.0 > last_finish {
        selected.push(activity);
        last_finish = activity.1;
    }
}
println!("{:?}", selected);
medium
A. Using > instead of >= in the if condition
B. Not pushing the first activity into selected
C. Not initializing last_finish correctly
D. Sorting by start time instead of finish time

Solution

  1. Step 1: Check sorting criteria

    The code sorts activities by start time (a.0), but the greedy approach requires sorting by finish time.
  2. Step 2: Understand impact of sorting

    Sorting by start time breaks the greedy logic, causing incorrect selection of activities.
  3. Final Answer:

    Sorting by start time instead of finish time -> Option D
  4. Quick Check:

    Sort by finish time needed, not start time [OK]
Hint: Always sort activities by finish time, not start time [OK]
Common Mistakes:
  • Sorting by start time
  • Using strict > instead of >= (less critical)
  • Incorrect initialization of last_finish
5. Given a list of activities with start and finish times, how would you modify the standard Activity Selection Problem to select activities that maximize total duration instead of count? Which approach is correct?
hard
A. Use dynamic programming to consider all subsets and maximize total duration
B. Sort activities by start time and greedily pick those with longest duration
C. Sort by finish time and pick activities with shortest duration first
D. Select activities randomly and check total duration

Solution

  1. Step 1: Understand difference in optimization goal

    Maximizing total duration is different from maximizing count; greedy approach fails here.
  2. Step 2: Choose correct algorithmic approach

    Dynamic programming can consider all subsets to find the maximum total duration without overlaps.
  3. Final Answer:

    Use dynamic programming to consider all subsets and maximize total duration -> Option A
  4. Quick Check:

    Max total duration needs DP, not greedy [OK]
Hint: Max duration needs DP, not greedy selection [OK]
Common Mistakes:
  • Trying greedy for max duration
  • Sorting by start time only
  • Random selection without logic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard