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.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an integer n representing n teams. You are asked to generate a schedule such that:
schedule[i] is the match on day i.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 <= 50Problem 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Greedy
3
5
task-scheduler)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
// }
// }
// }
// 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
}
}
}
# Accepted solution for LeetCode #3680: Generate Schedule
# Time: O(n^2)
# Space: O(1)
# constructive algorithms
class Solution(object):
def generateSchedule(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
result = []
if n <= 4:
return result
l = 1
if n%2 == 0:
for i in xrange(0, n, 2):
result.append([i, i+l])
for i in xrange(0, n, 2):
result.append([i+l, i])
for i in xrange(1, n, 2):
result.append([i, (i+l)%n])
for i in xrange(1, n, 2):
result.append([(i+l)%n, i])
else:
for i in xrange(0, 2*n, 2):
result.append([i%n, (i+l)%n])
for i in xrange(0, 2*n, 2):
result.append([(i+l)%n, i%n])
for l in xrange(2, (n+1)//2):
j = result[-1][0]+1
for i in xrange(j, j+n):
result.append([i%n, (i+l)%n])
j = result[-1][1]-1
for i in xrange(j, j+n):
result.append([(i+l)%n, i%n])
if n%2 == 0:
l = n//2
j = result[-1][0]-1
for i in xrange(j, j+n):
result.append([i%n, (i+l)%n])
return result
// Accepted solution for LeetCode #3680: Generate Schedule
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// 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
// }
// }
// }
// Accepted solution for LeetCode #3680: Generate Schedule
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// 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
// }
// }
// }
Use this to step through a reusable interview workflow for this problem.
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 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.
Review these before coding to avoid predictable interview regressions.
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.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
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.