- 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
- 46 lines of Python from the credited upstream file 3203.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 minimumDiameterAfterMerge(3 self,4 edges1: list[list[int]],5 edges2: list[list[int]],6 ) -> int:7 diameter1 = self._getDiameter(edges1)8 diameter2 = self._getDiameter(edges2)9 combinedDiameter = (diameter1 + 1) 2 + (diameter2 + 1) 2 + 110 return max(diameter1, diameter2, combinedDiameter)11 12 def _getDiameter(self, edges: list[list[int]]) -> int:13 n = len(edges) + 114 graph = [[] for _ in range(n)]15 16 for u, v in edges:17 graph[u].append(v)18 graph[v].append(u)19 20 maxDiameter = [0]21 self._maxDepth(graph, 0, -1, maxDiameter)22 return maxDiameter[0]23 24 25 def _maxDepth(26 self,27 graph: list[list[int]],28 u: int,29 prev: int,30 maxDiameter: list[int],31 ) -> int:32 """Returns the maximum depth of the subtree rooted at u."""33 maxSubDepth1 = 034 maxSubDepth2 = 035 for v in graph[u]:36 if v == prev:37 continue38 maxSubDepth = self._maxDepth(graph, v, u, maxDiameter)39 if maxSubDepth > maxSubDepth1:40 maxSubDepth2 = maxSubDepth141 maxSubDepth1 = maxSubDepth42 elif maxSubDepth > maxSubDepth2:43 maxSubDepth2 = maxSubDepth44 maxDiameter[0] = max(maxDiameter[0], maxSubDepth1 + maxSubDepth2)45 return 1 + maxSubDepth146