- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 56 lines of Java from the credited upstream file 1591.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 7 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1enum State { INIT, VISITING, VISITED }2 3class Solution {4 public boolean isPrintable(int[][] targetGrid) {5 final int MAX_COLOR = 60;6 final int m = targetGrid.length;7 final int n = targetGrid[0].length;8 9 Set<Integer>[] graph = new HashSet[MAX_COLOR + 1];10 11 for (int color = 1; color <= MAX_COLOR; ++color) {12 13 int minI = m;14 int minJ = n;15 int maxI = -1;16 int maxJ = -1;17 for (int i = 0; i < m; ++i)18 for (int j = 0; j < n; ++j)19 if (targetGrid[i][j] == color) {20 minI = Math.min(minI, i);21 minJ = Math.min(minJ, j);22 maxI = Math.max(maxI, i);23 maxJ = Math.max(maxJ, j);24 }25 26 graph[color] = new HashSet<>();27 for (int i = minI; i <= maxI; ++i)28 for (int j = minJ; j <= maxJ; ++j)29 if (targetGrid[i][j] != color) {30 graph[color].add(targetGrid[i][j]);31 }32 }33 34 State[] states = new State[MAX_COLOR + 1];35 36 for (int color = 1; color <= MAX_COLOR; ++color)37 if (hasCycle(graph, color, states))38 return false;39 40 return true;41 }42 43 private boolean hasCycle(Set<Integer>[] graph, int u, State[] states) {44 if (states[u] == State.VISITING)45 return true;46 if (states[u] == State.VISITED)47 return false;48 states[u] = State.VISITING;49 for (int v : graph[u])50 if (hasCycle(graph, v, states))51 return true;52 states[u] = State.VISITED;53 return false;54 }55}56