Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Activity Selection Implementation in Swift

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Activity Selection runs in O(n log n) time and O(1) space, in Swift as in every other language.
  • ✓Array.sorted(by:) (non-mutating, returns a new array) or Array.sort(by:) (mutating), with a trailing closure comparing on finish: activities.sorted { $0.finish < $1.finish }.
  • ✓Use sorted(by:), not sort(by:), unless you specifically own and intend to mutate the array you were given.
  • ✓The Swift trap: A plain (Int, Int) tuple type does not conform to Comparable, Swift does not allow tuple types to conform to protocols at all, so activities.sorted() with no closure on an array of (Int, Int) fails at COMPILE time with a protocol-conformance error, never as a runtime surprise.
  • ✓sort(by:)/sorted(by:) is a stable, adaptive merge sort with a guaranteed O(n log n) worst case, true of both the implementation and the documented guarantee since Swift 5.

What Activity Selection actually is

Activity selection asks for the largest set of non-overlapping intervals a single resource can serve: one meeting room, one machine, one slot per day. The textbook proof that a single greedy pass is optimal is short, sort the activities by FINISH time, then walk the sorted list once, keeping any activity whose start is not earlier than the finish time of the activity most recently kept. The O(n log n) time and O(1) auxiliary space usually quoted for this problem describe only that second pass: the scan itself needs nothing but a running finish time and a running count. The sort that has to happen first is not free, and it is exactly where the eight languages below stop agreeing with each other. Some default to a sort that is guaranteed stable and pays for that guarantee with a heap-allocated buffer; others default to an unstable, in-place sort that never allocates but makes no promise about which of two equally-finishing activities comes first; a few ship both under different names and expect the caller to choose. None of that changes how many activities can end up selected, a tie in finish time can only ever contribute one activity to an optimal answer, so tie-breaking order never changes the optimal COUNT, but it does change what the 'O(1) space' badge is actually describing. And the one bug that is genuinely universal here is not in the scan at all: sorting by START time instead of FINISH time compiles, or runs, without complaint in every language below, and just silently returns fewer activities than the true maximum.

Activity Selection in Swift: what you actually reach for

Array.sorted(by:) (non-mutating, returns a new array) or Array.sort(by:) (mutating), with a trailing closure comparing on finish: activities.sorted { $0.finish < $1.finish }. No import beyond the standard library is needed.

Swift implementation

Use sorted(by:), not sort(by:), unless you specifically own and intend to mutate the array you were given. Swift function parameters are let by default, so the natural shape of this function takes activities: [Activity] and returns a new sorted-and-filtered array rather than requiring the caller to pass a var.
swift
struct Activity {
    let start: Int
    let finish: Int
}

func selectActivities(_ activities: [Activity]) -> [Activity] {
    let ordered = activities.sorted { $0.finish < $1.finish }  // non-mutating

    var selected: [Activity] = [ordered[0]]
    var lastFinish = ordered[0].finish
    for activity in ordered.dropFirst() {
        if activity.start >= lastFinish {
            selected.append(activity)
            lastFinish = activity.finish
        }
    }
    return selected
}

let activities = [Activity(start: 1, finish: 4), Activity(start: 3, finish: 5),
                   Activity(start: 0, finish: 6), Activity(start: 5, finish: 7),
                   Activity(start: 8, finish: 9), Activity(start: 5, finish: 9)]
print(selectActivities(activities))
// [Activity(start: 1, finish: 4), Activity(start: 5, finish: 7), Activity(start: 8, finish: 9)]

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Swift-specific trap

A plain (Int, Int) tuple type does not conform to Comparable, Swift does not allow tuple types to conform to protocols at all, so activities.sorted() with no closure on an array of (Int, Int) fails at COMPILE time with a protocol-conformance error, never as a runtime surprise. You must supply by: on every sort call over a tuple element, which is also why defining a real Activity struct (as below) instead of an unlabeled tuple is the idiomatic choice: it reads better at every call site for the identical underlying reason.

Performance in Swift, beyond the O(n log n)

sort(by:)/sorted(by:) is a stable, adaptive merge sort with a guaranteed O(n log n) worst case, true of both the implementation and the documented guarantee since Swift 5. Because Array has copy-on-write value semantics, calling the MUTATING sort(by:) on an array that has any other live reference triggers a full buffer copy before the sort even starts, so 'mutate in place' is only actually cheaper than sorted(by:) when the array happens to be uniquely referenced, something a caller can't see from the call site alone. The asymptotic cost is the same in every language, O(n log n) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Activity Selection between languages.

Real-World Applications

Activity Selection applies wherever its problem shape appears in your own code. In Swift, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Activity Selection helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Activity Selection appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Activity Selection over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Activity Selection to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

Frequently Asked Questions

Which Swift type or library should I use for Activity Selection?

Array.sorted(by:) (non-mutating, returns a new array) or Array.sort(by:) (mutating), with a trailing closure comparing on finish: activities.sorted { $0.finish < $1.finish }. No import beyond the standard library is needed.

What is the most common Swift mistake when implementing Activity Selection?

A plain (Int, Int) tuple type does not conform to Comparable, Swift does not allow tuple types to conform to protocols at all, so activities.sorted() with no closure on an array of (Int, Int) fails at COMPILE time with a protocol-conformance error, never as a runtime surprise. You must supply by: on every sort call over a tuple element, which is also why defining a real Activity struct (as below) instead of an unlabeled tuple is the idiomatic choice: it reads better at every call site for the identical underlying reason.

How does Activity Selection actually perform in Swift?

sort(by:)/sorted(by:) is a stable, adaptive merge sort with a guaranteed O(n log n) worst case, true of both the implementation and the documented guarantee since Swift 5. Because Array has copy-on-write value semantics, calling the MUTATING sort(by:) on an array that has any other live reference triggers a full buffer copy before the sort even starts, so 'mutate in place' is only actually cheaper than sorted(by:) when the array happens to be uniquely referenced, something a caller can't see from the call site alone. Time complexity is O(n log n) and space is O(1).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.