- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 55 lines of C++ from the credited upstream file generate-schedule.cpp.
- The implementation visibly relies on sequence storage.
- 10 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<vector<int>> generateSchedule(int n) {8 vector<vector<int>> result;9 if (n <= 4) {10 return result;11 }12 const auto& l = 1;13 if (n % 2 == 0) {14 for (int i = 0; i < n; i += 2) {15 result.push_back({i, i + l});16 }17 for (int i = 0; i < n; i += 2) {18 result.push_back({i + l, i});19 }20 for (int i = 1; i < n; i += 2) {21 result.push_back({i, (i + l) % n});22 }23 for (int i = 1; i < n; i += 2) {24 result.push_back({(i + l) % n, i});25 }26 } else {27 for (int i = 0; i < 2 * n; i += 2) {28 result.push_back({i % n, (i + l) % n});29 }30 for (int i = 0; i < 2 * n; i += 2) {31 result.push_back({(i + l) % n, i % n});32 }33 }34 for (int l = 2; l < (n + 1) / 2; ++l) {35 int j;36 j = result.back()[0] + 1;37 for (int i = j; i < j + n; ++i) {38 result.push_back({i % n, (i + l) % n});39 }40 j = ((result.back()[1] - 1) % n + n) % n;41 for (int i = j; i < j + n; ++i) {42 result.push_back({(i + l) % n, i % n});43 }44 }45 if (n % 2 == 0) {46 const auto& l = n / 2;47 const auto& j = ((result.back()[0] - 1) % n + n) % n;48 for (int i = j; i < j + n; ++i) {49 result.push_back({i % n, (i + l) % n});50 }51 }52 return result;53 }54};55