Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1617: Count Subtrees With Max Distance Between Cities

In this guide, we solve Leetcode #1617 Count Subtrees With Max Distance Between Cities in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Bit Manipulation, Tree, Dynamic Programming, Bitmask, Enumeration

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: n = 4, edges = [[1,2],[2,3],[2,4]] Output: [3,4,0] Explanation: The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3.

Python Solution

class Solution: def countSubgraphsForEachDiameter( self, n: int, edges: List[List[int]] ) -> List[int]: def dfs(u: int, d: int = 0): nonlocal mx, nxt, msk if mx < d: mx, nxt = d, u msk ^= 1 << u for v in g[u]: if msk >> v & 1: dfs(v, d + 1) g = defaultdict(list) for u, v in edges: u, v = u - 1, v - 1 g[u].append(v) g[v].append(u) ans = [0] * (n - 1) nxt = mx = 0 for mask in range(1, 1 << n): if mask & (mask - 1) == 0: continue msk, mx = mask, 0 cur = msk.bit_length() - 1 dfs(cur) if msk == 0: msk, mx = mask, 0 dfs(nxt) ans[mx - 1] += 1 return ans

Complexity

The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy