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

Activity Selection Implementation in JavaScript

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 JavaScript as in every other language.
  • ✓Array.prototype.sort((a, b) => a[1] - b[1]) is the entire dependency here, no separate priority-queue or heap type is needed, because activity selection only ever compares against the single most-recently-kept activity, not a frontier of candidates.
  • ✓Always pass a comparator. Spread into a copy before sorting, [...activities].sort(...), rather than sorting the caller's array in place: sort() mutates and returns the same reference, so an un-copied sort is a hidden side effect on whatever array the caller handed you.
  • ✓The JavaScript trap: A bare .sort() with no comparator converts every element to a string first, fine for words, wrong for anything numeric.
  • ✓V8 has sorted with TimSort, guaranteeing stability, since V8 7.0 / Chrome 70 (2018); before that it used an unstable QuickSort for arrays with more than 10 elements (and insertion sort below that).

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 JavaScript: what you actually reach for

Array.prototype.sort((a, b) => a[1] - b[1]) is the entire dependency here, no separate priority-queue or heap type is needed, because activity selection only ever compares against the single most-recently-kept activity, not a frontier of candidates.

JavaScript implementation

Always pass a comparator. Spread into a copy before sorting, [...activities].sort(...), rather than sorting the caller's array in place: sort() mutates and returns the same reference, so an un-copied sort is a hidden side effect on whatever array the caller handed you.
javascript
function selectActivities(activities) {
  const ordered = [...activities].sort((a, b) => a[1] - b[1]); // by finish, not start

  const selected = [ordered[0]];
  let lastFinish = ordered[0][1];
  for (let i = 1; i < ordered.length; i += 1) {
    const [start, finish] = ordered[i];
    if (start >= lastFinish) {
      selected.push(ordered[i]);
      lastFinish = finish;
    }
  }
  return selected;
}

const activities = [[1, 4], [3, 5], [0, 6], [5, 7], [8, 9], [5, 9]];
console.log(selectActivities(activities)); // [[1,4],[5,7],[8,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 JavaScript-specific trap

A bare .sort() with no comparator converts every element to a string first, fine for words, wrong for anything numeric. [9, 80, 700].sort() returns [700, 80, 9], because the string '700' sorts before the string '80'. Forgetting the comparator on the finish-time sort here reproduces that exact bug: no error is thrown, the greedy pass just silently runs on the wrong order and returns a wrong-looking-right answer.

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

V8 has sorted with TimSort, guaranteeing stability, since V8 7.0 / Chrome 70 (2018); before that it used an unstable QuickSort for arrays with more than 10 elements (and insertion sort below that). TimSort's merge phase allocates a temporary array, so the sort step is O(n) space even though the greedy scan that follows it needs none. 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 JavaScript, 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 JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

Frequently Asked Questions

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

Array.prototype.sort((a, b) => a[1] - b[1]) is the entire dependency here, no separate priority-queue or heap type is needed, because activity selection only ever compares against the single most-recently-kept activity, not a frontier of candidates.

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

A bare .sort() with no comparator converts every element to a string first, fine for words, wrong for anything numeric. [9, 80, 700].sort() returns [700, 80, 9], because the string '700' sorts before the string '80'. Forgetting the comparator on the finish-time sort here reproduces that exact bug: no error is thrown, the greedy pass just silently runs on the wrong order and returns a wrong-looking-right answer.

How does Activity Selection actually perform in JavaScript?

V8 has sorted with TimSort, guaranteeing stability, since V8 7.0 / Chrome 70 (2018); before that it used an unstable QuickSort for arrays with more than 10 elements (and insertion sort below that). TimSort's merge phase allocates a temporary array, so the sort step is O(n) space even though the greedy scan that follows it needs none. 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? GitHub Copilot 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.