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