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

Interval Scheduling Implementation in Go

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

  • ✓Interval Scheduling runs in O(n log n) time and O(1) space, in Go as in every other language.
  • ✓slices.SortFunc, from the generics-based slices package (Go 1.21+), sorts any []E using a three-way comparator; cmp.Compare, from the cmp package, supplies that comparator for any ordered type.
  • ✓Reach for slices.SortFunc over sort.Slice on any codebase targeting Go 1.21+: it is monomorphized per element type by the generics compiler instead of going through reflection, and the comparator returning an int via cmp.Compare(a.End, b.End) matches the same three-way-comparison convention used across sort, slices, and cmp.
  • ✓The Go trap: Neither sort.Slice nor slices.SortFunc validates that your comparator defines a strict weak ordering, and neither panics if it does not, an inconsistent less/compare function (for example one that accidentally compares Start on one branch and End on another) just produces a slice that is not correctly sorted, with no error, no warning, and no stack trace to point at the bug.
  • ✓sort.Slice's reflection path swaps elements through reflect.Swapper, which is measurably slower than a type-specific swap because every element access goes through an interface and a runtime type check.

What Interval Scheduling actually is

Interval scheduling picks the largest possible set of non-overlapping intervals out of a list, and the algorithm itself never varies: sort the intervals by END time, then make one pass keeping track of the end time of the last interval you accepted, taking the next interval only when its start is at or after that end. The exchange-argument proof that sorting by end (not by start, not by length) is optimal is the same in every language, and so is the O(n log n) bound, because the scan after the sort is a single O(n) pass carrying one integer of state. What is genuinely different across these eight languages is what the sort itself does under the hood, and that is where the O(1) space bound quoted for this topic actually gets tested. Some standard libraries hand you a sort that is guaranteed stable and will throw at runtime if your comparator is not a valid ordering; others make no stability promise and will silently tie-break differently between runs; one gives you an explicit choice between a sort that allocates a temporary merge buffer and one that provably does not, and only the second one actually hits the O(1) auxiliary-space bound rather than merely being close to it. None of that changes the answer for an input with no tied end times, which is exactly why it is the kind of detail you only discover by reading the sort function's documented contract, not by reading the greedy algorithm.

Interval Scheduling in Go: what you actually reach for

slices.SortFunc, from the generics-based slices package (Go 1.21+), sorts any []E using a three-way comparator; cmp.Compare, from the cmp package, supplies that comparator for any ordered type. The older sort.Slice (sort package) takes an any and a less func(i, j int) bool, and reaches that generality through reflection under the hood.

Go implementation

Reach for slices.SortFunc over sort.Slice on any codebase targeting Go 1.21+: it is monomorphized per element type by the generics compiler instead of going through reflection, and the comparator returning an int via cmp.Compare(a.End, b.End) matches the same three-way-comparison convention used across sort, slices, and cmp.
go
package main

import (
	"cmp"
	"slices"
)

type Interval struct {
	Start, End int
}

func MaxNonOverlapping(intervals []Interval) []Interval {
	// slices.SortFunc: generic, no reflection (unlike sort.Slice); in place, no allocation
	slices.SortFunc(intervals, func(a, b Interval) int {
		return cmp.Compare(a.End, b.End)
	})

	selected := make([]Interval, 0, len(intervals))
	lastEnd := -1 << 31
	for _, iv := range intervals {
		if iv.Start >= lastEnd {
			selected = append(selected, iv)
			lastEnd = iv.End
		}
	}
	return selected
}

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 Go-specific trap

Neither sort.Slice nor slices.SortFunc validates that your comparator defines a strict weak ordering, and neither panics if it does not, an inconsistent less/compare function (for example one that accidentally compares Start on one branch and End on another) just produces a slice that is not correctly sorted, with no error, no warning, and no stack trace to point at the bug. That is a real, load-bearing difference from Java's TimSort on this same page, which actively detects an inconsistent comparator at runtime and throws.

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

sort.Slice's reflection path swaps elements through reflect.Swapper, which is measurably slower than a type-specific swap because every element access goes through an interface and a runtime type check. slices.SortFunc avoids that entirely: Go's generics compile via GC-shape stenciling with a runtime dictionary (one compiled body shared by every type with the same underlying memory layout, not a fresh copy per concrete type the way Rust or C++ templates work), but even that dictionary-passing path uses directly-compiled element access and swaps instead of reflect.Swapper, so it stays categorically faster than sort.Slice's reflection. Since Go 1.19 the underlying sort algorithm for both is a pattern-defeating quicksort variant, in place, with no extra allocation beyond the small recursion stack. 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 Interval Scheduling between languages.

Real-World Applications

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

Interview Tips & Practice

Interval Scheduling 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 Interval Scheduling 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 Interval Scheduling to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

Which Go type or library should I use for Interval Scheduling?

slices.SortFunc, from the generics-based slices package (Go 1.21+), sorts any []E using a three-way comparator; cmp.Compare, from the cmp package, supplies that comparator for any ordered type. The older sort.Slice (sort package) takes an any and a less func(i, j int) bool, and reaches that generality through reflection under the hood.

What is the most common Go mistake when implementing Interval Scheduling?

Neither sort.Slice nor slices.SortFunc validates that your comparator defines a strict weak ordering, and neither panics if it does not, an inconsistent less/compare function (for example one that accidentally compares Start on one branch and End on another) just produces a slice that is not correctly sorted, with no error, no warning, and no stack trace to point at the bug. That is a real, load-bearing difference from Java's TimSort on this same page, which actively detects an inconsistent comparator at runtime and throws.

How does Interval Scheduling actually perform in Go?

sort.Slice's reflection path swaps elements through reflect.Swapper, which is measurably slower than a type-specific swap because every element access goes through an interface and a runtime type check. slices.SortFunc avoids that entirely: Go's generics compile via GC-shape stenciling with a runtime dictionary (one compiled body shared by every type with the same underlying memory layout, not a fresh copy per concrete type the way Rust or C++ templates work), but even that dictionary-passing path uses directly-compiled element access and swaps instead of reflect.Swapper, so it stays categorically faster than sort.Slice's reflection. Since Go 1.19 the underlying sort algorithm for both is a pattern-defeating quicksort variant, in place, with no extra allocation beyond the small recursion stack. 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

Before paying full price for a tool, check the student deals on AI and developer tools listed 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.