LeetCode #3680 — MEDIUM

Generate Schedule

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer n representing n teams. You are asked to generate a schedule such that:

  • Each team plays every other team exactly twice: once at home and once away.
  • There is exactly one match per day; the schedule is a list of consecutive days and schedule[i] is the match on day i.
  • No team plays on consecutive days.

Return a 2D integer array schedule, where schedule[i][0] represents the home team and schedule[i][1] represents the away team. If multiple schedules meet the conditions, return any one of them.

If no schedule exists that meets the conditions, return an empty array.

Example 1:

Input: n = 3

Output: []

Explanation:

​​​​​​​Since each team plays every other team exactly twice, a total of 6 matches need to be played: [0,1],[0,2],[1,2],[1,0],[2,0],[2,1].

It's not possible to create a schedule without at least one team playing consecutive days.

Example 2:

Input: n = 5

Output: [[0,1],[2,3],[0,4],[1,2],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[2,0],[3,1],[4,0],[2,1],[4,3],[1,0],[3,2],[4,1],[3,0],[4,2]]

Explanation:

Since each team plays every other team exactly twice, a total of 20 matches need to be played.

The output shows one of the schedules that meet the conditions. No team plays on consecutive days.

Constraints:

  • 2 <= n <= 50​​​​​​​
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer n representing n teams. You are asked to generate a schedule such that: Each team plays every other team exactly twice: once at home and once away. There is exactly one match per day; the schedule is a list of consecutive days and schedule[i] is the match on day i. No team plays on consecutive days. Return a 2D integer array schedule, where schedule[i][0] represents the home team and schedule[i][1] represents the away team. If multiple schedules meet the conditions, return any one of them. If no schedule exists that meets the conditions, return an empty array.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Math · Greedy

Example 1

3

Example 2

5

Related Problems

  • Task Scheduler (task-scheduler)
Step 02

Core Insight

What unlocks the optimal approach

  • The problem can be solved greedily or using randomization.
  • Try pairing teams greedily while ensuring neither team played on the previous day.
  • Keep track of how many games each team still has to play.
  • Among teams that didn't play the previous day, match a pair whose combined remaining games is highest.
  • If a greedy choice leads to a dead end, try a different match order.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3680: Generate Schedule
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3680: Generate Schedule
// package main
// 
// import (
// 	"math/rand"
// 	"slices"
// )
// 
// // https://space.bilibili.com/206214
// func generateSchedule1(n int) [][]int {
// 	if n < 5 {
// 		return nil
// 	}
// 
// 	ans := make([][]int, 0, n*(n-1)) // 预分配空间
// 
// 	// 处理 d=2,3,...,n-2
// 	for d := 2; d < n-1; d++ {
// 		for i := range n {
// 			ans = append(ans, []int{i, (i + d) % n})
// 		}
// 	}
// 
// 	// 交错排列 d=1 与 d=n-1(或者说 d=-1)
// 	for i := range n {
// 		ans = append(ans, []int{i, (i + 1) % n}, []int{(i + n - 1) % n, (i + n - 2) % n})
// 	}
// 
// 	return ans
// }
// 
// func gen(perm [][]int) (ans [][]int) {
// 	ans = append(ans, perm[0])
// 	perm = perm[1:]
// next:
// 	for len(perm) > 0 {
// 		// 倒着遍历,这样删除的时候 i 更大,移动的数据少
// 		for i, p := range slices.Backward(perm) {
// 			last := ans[len(ans)-1]
// 			if p[0] != last[0] && p[0] != last[1] && p[1] != last[0] && p[1] != last[1] {
// 				// p 和上一场比赛无冲突
// 				ans = append(ans, p)
// 				perm = append(perm[:i], perm[i+1:]...) // 删除 perm[i]
// 				continue next // 找下一场比赛
// 			}
// 		}
// 		return nil
// 	}
// 	return
// }
// 
// func generateSchedule(n int) [][]int {
// 	if n < 5 {
// 		return nil
// 	}
// 
// 	// 赛程排列
// 	perm := make([][]int, 0, n*(n-1))
// 	for i := range n {
// 		for j := range n {
// 			if j != i {
// 				perm = append(perm, []int{i, j})
// 			}
// 		}
// 	}
// 
// 	for {
// 		rand.Shuffle(len(perm), func(i, j int) { perm[i], perm[j] = perm[j], perm[i] })
// 		if ans := gen(slices.Clone(perm)); ans != nil {
// 			return ans
// 		}
// 	}
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n log n)
Space
O(1)

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.

GREEDY
O(n log n) time
O(1) space

Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.