- 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
- 43 lines of C++ from the credited upstream file 886.cpp.
- The implementation visibly relies on sequence storage.
- 3 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.
1enum Color { kWhite, kRed, kGreen };2 3class Solution {4 public:5 bool possibleBipartition(int n, vector<vector<int>>& dislikes) {6 vector<vector<int>> graph(n + 1);7 vector<Color> colors(n + 1, Color::kWhite);8 9 for (const vector<int>& d : dislikes) {10 const int u = d[0];11 const int v = d[1];12 graph[u].push_back(v);13 graph[v].push_back(u);14 }15 16 17 for (int i = 1; i <= n; ++i)18 if (colors[i] == Color::kWhite &&19 !isValidColor(graph, i, colors, Color::kRed))20 return false;21 22 return true;23 }24 25 private:26 bool isValidColor(const vector<vector<int>>& graph, int u,27 vector<Color>& colors, Color color) {28 29 if (colors[u] != Color::kWhite)30 return colors[u] == color;31 32 colors[u] = color; 33 34 35 for (const int v : graph[u])36 if (!isValidColor(graph, v, colors,37 color == Color::kRed ? Color::kGreen : Color::kRed))38 return false;39 40 return true;41 }42};43