- 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
- 52 lines of Python from the credited upstream file 1617.py.
- The implementation visibly relies on sequence storage.
- No explicit 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.
1class Solution:2 def countSubgraphsForEachDiameter(3 self,4 n: int,5 edges: list[list[int]],6 ) -> list[int]:7 maxMask = 1 << n8 dist = self._floydWarshall(n, edges)9 ans = [0] * (n - 1)10 11 12 for mask in range(maxMask):13 maxDist = self._getMaxDist(mask, dist, n)14 if maxDist > 0:15 ans[maxDist - 1] += 116 17 return ans18 19 def _floydWarshall(self, n: int, edges: list[list[int]]) -> list[list[int]]:20 dist = [[n] * n for _ in range(n)]21 22 for i in range(n):23 dist[i][i] = 024 25 for u, v in edges:26 dist[u - 1][v - 1] = 127 dist[v - 1][u - 1] = 128 29 for k in range(n):30 for i in range(n):31 for j in range(n):32 dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])33 34 return dist35 36 def _getMaxDist(self, mask: int, dist: list[list[int]], n: int) -> int:37 maxDist = 038 edgeCount = 039 cityCount = 040 for u in range(n):41 if (mask >> u) & 1 == 0: 42 continue43 cityCount += 144 for v in range(u + 1, n):45 if (mask >> v) & 1 == 0: 46 continue47 if dist[u][v] == 1: 48 edgeCount += 149 maxDist = max(maxDist, dist[u][v])50 51 return maxDist if edgeCount == cityCount - 1 else 052