You are given an integer n and an undirected graph with n nodes labeled from 0 to n - 1 and a 2D array edges, where edges[i] = [ui, vi] indicates an edge between nodes ui and vi.
You are also given a string label of length n, where label[i] is the character associated with node i.
You may start at any node and move to any adjacent node, visiting each node at most once.
Return the maximum possible length of a palindrome that can be formed by visiting a set of unique nodes along a valid path.
Example 1:
Input:n = 3, edges = [[0,1],[1,2]], label = "aba"
Output:3
Explanation:
The longest palindromic path is from node 0 to node 2 via node 1, following the path 0 → 1 → 2 forming string "aba".
This is a valid palindrome of length 3.
Example 2:
Input:n = 3, edges = [[0,1],[0,2]], label = "abc"
Output:1
Explanation:
No path with more than one node forms a palindrome.
The best option is any single node, giving a palindrome of length 1.
Problem summary: You are given an integer n and an undirected graph with n nodes labeled from 0 to n - 1 and a 2D array edges, where edges[i] = [ui, vi] indicates an edge between nodes ui and vi. You are also given a string label of length n, where label[i] is the character associated with node i. You may start at any node and move to any adjacent node, visiting each node at most once. Return the maximum possible length of a palindrome that can be formed by visiting a set of unique nodes along a valid path.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming · Bit Manipulation
Example 1
3
[[0,1],[1,2]]
"aba"
Example 2
3
[[0,1],[0,2]]
"abc"
Example 3
4
[[0,2],[0,3],[3,1]]
"bbac"
Step 02
Core Insight
What unlocks the optimal approach
Use bitmask dynamic programming.
Build the palindrome by expanding from both endpoints: you can include a new pair of nodes as endpoints if neither is already in the current bitmask <code>mask</code>.
Before adding new endpoints to the current palindrome, ensure their labels match the labels at the previous endpoints <code>prev_l</code> and <code>prev_r</code>.
Memoize each state as <code>dp[mask][prev_l][prev_r]</code>, representing the maximum palindrome length achievable using the set of visited nodes in <code>mask</code> with current endpoints at <code>prev_l</code> and <code>prev_r</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3615: Longest Palindromic Path in Graph
// Auto-generated Java example from go.
class Solution {
public void exampleSolution() {
}
}
// Reference (go):
// // Accepted solution for LeetCode #3615: Longest Palindromic Path in Graph
// package main
//
// import (
// "math/bits"
// )
//
// // https://space.bilibili.com/206214
// func maxLen(n int, edges [][]int, label string) (ans int) {
// // 计算理论最大值
// cnt := [26]int{}
// for _, ch := range label {
// cnt[ch-'a']++
// }
// odd := 0
// for _, c := range cnt {
// odd += c % 2
// }
// theoreticalMax := n - max(odd-1, 0) // 奇数选一个放正中心,其余全弃
//
// if len(edges) == n*(n-1)/2 { // 完全图,可以达到理论最大值
// return theoreticalMax
// }
//
// g := make([][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// }
//
// memo := make([][][]int, n)
// for i := range memo {
// memo[i] = make([][]int, n)
// for j := range memo[i] {
// memo[i][j] = make([]int, 1<<n)
// for p := range memo[i][j] {
// memo[i][j][p] = -1
// }
// }
// }
//
// // 计算从 x 和 y 向两侧扩展,最多还能访问多少个节点(不算 x 和 y)
// var dfs func(int, int, int) int
// dfs = func(x, y, vis int) (res int) {
// p := &memo[x][y][vis]
// if *p >= 0 { // 之前计算过
// return *p
// }
// for _, v := range g[x] {
// if vis>>v&1 > 0 { // v 在路径中
// continue
// }
// for _, w := range g[y] {
// if vis>>w&1 == 0 && w != v && label[w] == label[v] {
// // 保证 v < w,减少状态个数和计算量
// r := dfs(min(v, w), max(v, w), vis|1<<v|1<<w)
// res = max(res, r+2)
// }
// }
// }
// *p = res // 记忆化
// return
// }
//
// for x, to := range g {
// // 奇回文串,x 作为回文中心
// ans = max(ans, dfs(x, x, 1<<x)+1)
// if ans == theoreticalMax {
// return
// }
// // 偶回文串,x 和 x 的邻居 y 作为回文中心
// for _, y := range to {
// // 保证 x < y,减少状态个数和计算量
// if x < y && label[x] == label[y] {
// ans = max(ans, dfs(x, y, 1<<x|1<<y)+2)
// if ans == theoreticalMax {
// return
// }
// }
// }
// }
// return
// }
//
// func maxLenGroupByLabel(n int, edges [][]int, label string) (ans int) {
// g := make([][]int, n)
// labelG := make([][26][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// labelG[x][label[y]-'a'] = append(labelG[x][label[y]-'a'], y)
// labelG[y][label[x]-'a'] = append(labelG[y][label[x]-'a'], x)
// }
//
// memo := make([][][]int, n)
// for i := range memo {
// memo[i] = make([][]int, n)
// for j := range memo[i] {
// memo[i][j] = make([]int, 1<<n)
// for p := range memo[i][j] {
// memo[i][j][p] = -1
// }
// }
// }
//
// // 计算从 x 和 y 向两侧扩展,最多还能访问多少个节点(不算 x 和 y)
// var dfs func(int, int, int) int
// dfs = func(x, y, vis int) (res int) {
// p := &memo[x][y][vis]
// if *p >= 0 { // 之前计算过
// return *p
// }
// for _, v := range g[x] {
// if vis>>v&1 > 0 { // v 在路径中
// continue
// }
// for _, w := range labelG[y][label[v]-'a'] {
// if vis>>w&1 == 0 && w != v {
// // 保证 v < w,减少状态个数和计算量
// r := dfs(min(v, w), max(v, w), vis|1<<v|1<<w)
// res = max(res, r+2)
// }
// }
// }
// *p = res // 记忆化
// return
// }
//
// for x, to := range labelG {
// // 奇回文串,x 作为回文中心
// ans = max(ans, dfs(x, x, 1<<x)+1)
// if ans == n {
// return
// }
// // 偶回文串,x 和 x 的邻居 y 作为回文中心
// for _, y := range to[label[x]-'a'] {
// // 保证 x < y,减少状态个数和计算量
// if x < y {
// ans = max(ans, dfs(x, y, 1<<x|1<<y)+2)
// if ans == n {
// return
// }
// }
// }
// }
// return
// }
//
// func maxLenBFS(n int, edges [][]int, label string) int {
// g := make([][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// }
//
// vis := make([][][]bool, n)
// for i := range vis {
// vis[i] = make([][]bool, n)
// for j := range vis[i] {
// vis[i][j] = make([]bool, 1<<n)
// }
// }
// type tuple struct{ x, y, vis int }
// q := []tuple{}
// // 奇回文串,x 作为回文中心
// for x := range n {
// vis[x][x][1<<x] = true
// q = append(q, tuple{x, x, 1 << x})
// }
// // 偶回文串,x 和 x 的邻居 y 作为回文中心
// for x, to := range g {
// for _, y := range to {
// // 保证 x < y,减少状态个数
// if x < y && label[x] == label[y] {
// vis[x][y][1<<x|1<<y] = true
// q = append(q, tuple{x, y, 1<<x | 1<<y})
// }
// }
// }
// var t tuple
// for len(q) > 0 {
// t = q[0]
// q = q[1:]
// for _, v := range g[t.x] {
// if t.vis>>v&1 > 0 { // v 在路径中
// continue
// }
// for _, w := range g[t.y] {
// if t.vis>>w&1 == 0 && w != v && label[w] == label[v] {
// // 保证 v < w,减少状态个数
// p := &vis[min(v, w)][max(v, w)][t.vis|1<<v|1<<w]
// if !*p {
// *p = true
// q = append(q, tuple{min(v, w), max(v, w), t.vis | 1<<v | 1<<w})
// }
// }
// }
// }
// }
// return bits.OnesCount(uint(t.vis))
// }
// Accepted solution for LeetCode #3615: Longest Palindromic Path in Graph
package main
import (
"math/bits"
)
// https://space.bilibili.com/206214
func maxLen(n int, edges [][]int, label string) (ans int) {
// 计算理论最大值
cnt := [26]int{}
for _, ch := range label {
cnt[ch-'a']++
}
odd := 0
for _, c := range cnt {
odd += c % 2
}
theoreticalMax := n - max(odd-1, 0) // 奇数选一个放正中心,其余全弃
if len(edges) == n*(n-1)/2 { // 完全图,可以达到理论最大值
return theoreticalMax
}
g := make([][]int, n)
for _, e := range edges {
x, y := e[0], e[1]
g[x] = append(g[x], y)
g[y] = append(g[y], x)
}
memo := make([][][]int, n)
for i := range memo {
memo[i] = make([][]int, n)
for j := range memo[i] {
memo[i][j] = make([]int, 1<<n)
for p := range memo[i][j] {
memo[i][j][p] = -1
}
}
}
// 计算从 x 和 y 向两侧扩展,最多还能访问多少个节点(不算 x 和 y)
var dfs func(int, int, int) int
dfs = func(x, y, vis int) (res int) {
p := &memo[x][y][vis]
if *p >= 0 { // 之前计算过
return *p
}
for _, v := range g[x] {
if vis>>v&1 > 0 { // v 在路径中
continue
}
for _, w := range g[y] {
if vis>>w&1 == 0 && w != v && label[w] == label[v] {
// 保证 v < w,减少状态个数和计算量
r := dfs(min(v, w), max(v, w), vis|1<<v|1<<w)
res = max(res, r+2)
}
}
}
*p = res // 记忆化
return
}
for x, to := range g {
// 奇回文串,x 作为回文中心
ans = max(ans, dfs(x, x, 1<<x)+1)
if ans == theoreticalMax {
return
}
// 偶回文串,x 和 x 的邻居 y 作为回文中心
for _, y := range to {
// 保证 x < y,减少状态个数和计算量
if x < y && label[x] == label[y] {
ans = max(ans, dfs(x, y, 1<<x|1<<y)+2)
if ans == theoreticalMax {
return
}
}
}
}
return
}
func maxLenGroupByLabel(n int, edges [][]int, label string) (ans int) {
g := make([][]int, n)
labelG := make([][26][]int, n)
for _, e := range edges {
x, y := e[0], e[1]
g[x] = append(g[x], y)
g[y] = append(g[y], x)
labelG[x][label[y]-'a'] = append(labelG[x][label[y]-'a'], y)
labelG[y][label[x]-'a'] = append(labelG[y][label[x]-'a'], x)
}
memo := make([][][]int, n)
for i := range memo {
memo[i] = make([][]int, n)
for j := range memo[i] {
memo[i][j] = make([]int, 1<<n)
for p := range memo[i][j] {
memo[i][j][p] = -1
}
}
}
// 计算从 x 和 y 向两侧扩展,最多还能访问多少个节点(不算 x 和 y)
var dfs func(int, int, int) int
dfs = func(x, y, vis int) (res int) {
p := &memo[x][y][vis]
if *p >= 0 { // 之前计算过
return *p
}
for _, v := range g[x] {
if vis>>v&1 > 0 { // v 在路径中
continue
}
for _, w := range labelG[y][label[v]-'a'] {
if vis>>w&1 == 0 && w != v {
// 保证 v < w,减少状态个数和计算量
r := dfs(min(v, w), max(v, w), vis|1<<v|1<<w)
res = max(res, r+2)
}
}
}
*p = res // 记忆化
return
}
for x, to := range labelG {
// 奇回文串,x 作为回文中心
ans = max(ans, dfs(x, x, 1<<x)+1)
if ans == n {
return
}
// 偶回文串,x 和 x 的邻居 y 作为回文中心
for _, y := range to[label[x]-'a'] {
// 保证 x < y,减少状态个数和计算量
if x < y {
ans = max(ans, dfs(x, y, 1<<x|1<<y)+2)
if ans == n {
return
}
}
}
}
return
}
func maxLenBFS(n int, edges [][]int, label string) int {
g := make([][]int, n)
for _, e := range edges {
x, y := e[0], e[1]
g[x] = append(g[x], y)
g[y] = append(g[y], x)
}
vis := make([][][]bool, n)
for i := range vis {
vis[i] = make([][]bool, n)
for j := range vis[i] {
vis[i][j] = make([]bool, 1<<n)
}
}
type tuple struct{ x, y, vis int }
q := []tuple{}
// 奇回文串,x 作为回文中心
for x := range n {
vis[x][x][1<<x] = true
q = append(q, tuple{x, x, 1 << x})
}
// 偶回文串,x 和 x 的邻居 y 作为回文中心
for x, to := range g {
for _, y := range to {
// 保证 x < y,减少状态个数
if x < y && label[x] == label[y] {
vis[x][y][1<<x|1<<y] = true
q = append(q, tuple{x, y, 1<<x | 1<<y})
}
}
}
var t tuple
for len(q) > 0 {
t = q[0]
q = q[1:]
for _, v := range g[t.x] {
if t.vis>>v&1 > 0 { // v 在路径中
continue
}
for _, w := range g[t.y] {
if t.vis>>w&1 == 0 && w != v && label[w] == label[v] {
// 保证 v < w,减少状态个数
p := &vis[min(v, w)][max(v, w)][t.vis|1<<v|1<<w]
if !*p {
*p = true
q = append(q, tuple{min(v, w), max(v, w), t.vis | 1<<v | 1<<w})
}
}
}
}
}
return bits.OnesCount(uint(t.vis))
}
# Accepted solution for LeetCode #3615: Longest Palindromic Path in Graph
#
# @lc app=leetcode id=3615 lang=python3
#
# [3615] Longest Palindromic Path in Graph
#
# @lc code=start
from functools import lru_cache
from typing import List
class Solution:
def maxLen(self, n: int, edges: List[List[int]], label: str) -> int:
# Build adjacency list
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
# Precompute neighbors grouped by their character label for faster lookup
# neighbors[u][char_code] will store a list of neighbors of u that have that label
neighbors = [[[] for _ in range(26)] for _ in range(n)]
for u in range(n):
for v in adj[u]:
char_idx = ord(label[v]) - ord('a')
neighbors[u][char_idx].append(v)
# DFS with memoization to find the longest extension
# State: (u, v, mask)
# u, v: current endpoints of the path (u <= v enforced for uniqueness)
# mask: bitmask of visited nodes
@lru_cache(None)
def dfs(u, v, mask):
max_extension = 0
# Try to extend from u to nu and v to nv such that label[nu] == label[nv]
# Iterate through all possible characters 'a'...'z'
for char_idx in range(26):
u_candidates = neighbors[u][char_idx]
if not u_candidates: continue
v_candidates = neighbors[v][char_idx]
if not v_candidates: continue
for nu in u_candidates:
# If nu is already visited, skip
if (mask >> nu) & 1:
continue
for nv in v_candidates:
# If nv is already visited, skip
if (mask >> nv) & 1:
continue
# Cannot extend to the same node from both ends (unless it's the center, handled separately)
if nu == nv:
continue
# Determine next state, ensuring first endpoint index < second endpoint index
next_u, next_v = (nu, nv) if nu < nv else (nv, nu)
new_mask = mask | (1 << nu) | (1 << nv)
max_extension = max(max_extension, 2 + dfs(next_u, next_v, new_mask))
return max_extension
ans = 1
# 1. Try odd-length palindromes centered at each node
for i in range(n):
# Path starts at i, length 1. Try to extend.
ans = max(ans, 1 + dfs(i, i, 1 << i))
# 2. Try even-length palindromes centered at each edge with matching labels
for u, v in edges:
if label[u] == label[v]:
# Path starts at u-v, length 2. Try to extend.
u_sorted, v_sorted = (u, v) if u < v else (v, u)
ans = max(ans, 2 + dfs(u_sorted, v_sorted, (1 << u) | (1 << v)))
return ans
# @lc code=end
// Accepted solution for LeetCode #3615: Longest Palindromic Path in Graph
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (go):
// // Accepted solution for LeetCode #3615: Longest Palindromic Path in Graph
// package main
//
// import (
// "math/bits"
// )
//
// // https://space.bilibili.com/206214
// func maxLen(n int, edges [][]int, label string) (ans int) {
// // 计算理论最大值
// cnt := [26]int{}
// for _, ch := range label {
// cnt[ch-'a']++
// }
// odd := 0
// for _, c := range cnt {
// odd += c % 2
// }
// theoreticalMax := n - max(odd-1, 0) // 奇数选一个放正中心,其余全弃
//
// if len(edges) == n*(n-1)/2 { // 完全图,可以达到理论最大值
// return theoreticalMax
// }
//
// g := make([][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// }
//
// memo := make([][][]int, n)
// for i := range memo {
// memo[i] = make([][]int, n)
// for j := range memo[i] {
// memo[i][j] = make([]int, 1<<n)
// for p := range memo[i][j] {
// memo[i][j][p] = -1
// }
// }
// }
//
// // 计算从 x 和 y 向两侧扩展,最多还能访问多少个节点(不算 x 和 y)
// var dfs func(int, int, int) int
// dfs = func(x, y, vis int) (res int) {
// p := &memo[x][y][vis]
// if *p >= 0 { // 之前计算过
// return *p
// }
// for _, v := range g[x] {
// if vis>>v&1 > 0 { // v 在路径中
// continue
// }
// for _, w := range g[y] {
// if vis>>w&1 == 0 && w != v && label[w] == label[v] {
// // 保证 v < w,减少状态个数和计算量
// r := dfs(min(v, w), max(v, w), vis|1<<v|1<<w)
// res = max(res, r+2)
// }
// }
// }
// *p = res // 记忆化
// return
// }
//
// for x, to := range g {
// // 奇回文串,x 作为回文中心
// ans = max(ans, dfs(x, x, 1<<x)+1)
// if ans == theoreticalMax {
// return
// }
// // 偶回文串,x 和 x 的邻居 y 作为回文中心
// for _, y := range to {
// // 保证 x < y,减少状态个数和计算量
// if x < y && label[x] == label[y] {
// ans = max(ans, dfs(x, y, 1<<x|1<<y)+2)
// if ans == theoreticalMax {
// return
// }
// }
// }
// }
// return
// }
//
// func maxLenGroupByLabel(n int, edges [][]int, label string) (ans int) {
// g := make([][]int, n)
// labelG := make([][26][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// labelG[x][label[y]-'a'] = append(labelG[x][label[y]-'a'], y)
// labelG[y][label[x]-'a'] = append(labelG[y][label[x]-'a'], x)
// }
//
// memo := make([][][]int, n)
// for i := range memo {
// memo[i] = make([][]int, n)
// for j := range memo[i] {
// memo[i][j] = make([]int, 1<<n)
// for p := range memo[i][j] {
// memo[i][j][p] = -1
// }
// }
// }
//
// // 计算从 x 和 y 向两侧扩展,最多还能访问多少个节点(不算 x 和 y)
// var dfs func(int, int, int) int
// dfs = func(x, y, vis int) (res int) {
// p := &memo[x][y][vis]
// if *p >= 0 { // 之前计算过
// return *p
// }
// for _, v := range g[x] {
// if vis>>v&1 > 0 { // v 在路径中
// continue
// }
// for _, w := range labelG[y][label[v]-'a'] {
// if vis>>w&1 == 0 && w != v {
// // 保证 v < w,减少状态个数和计算量
// r := dfs(min(v, w), max(v, w), vis|1<<v|1<<w)
// res = max(res, r+2)
// }
// }
// }
// *p = res // 记忆化
// return
// }
//
// for x, to := range labelG {
// // 奇回文串,x 作为回文中心
// ans = max(ans, dfs(x, x, 1<<x)+1)
// if ans == n {
// return
// }
// // 偶回文串,x 和 x 的邻居 y 作为回文中心
// for _, y := range to[label[x]-'a'] {
// // 保证 x < y,减少状态个数和计算量
// if x < y {
// ans = max(ans, dfs(x, y, 1<<x|1<<y)+2)
// if ans == n {
// return
// }
// }
// }
// }
// return
// }
//
// func maxLenBFS(n int, edges [][]int, label string) int {
// g := make([][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// }
//
// vis := make([][][]bool, n)
// for i := range vis {
// vis[i] = make([][]bool, n)
// for j := range vis[i] {
// vis[i][j] = make([]bool, 1<<n)
// }
// }
// type tuple struct{ x, y, vis int }
// q := []tuple{}
// // 奇回文串,x 作为回文中心
// for x := range n {
// vis[x][x][1<<x] = true
// q = append(q, tuple{x, x, 1 << x})
// }
// // 偶回文串,x 和 x 的邻居 y 作为回文中心
// for x, to := range g {
// for _, y := range to {
// // 保证 x < y,减少状态个数
// if x < y && label[x] == label[y] {
// vis[x][y][1<<x|1<<y] = true
// q = append(q, tuple{x, y, 1<<x | 1<<y})
// }
// }
// }
// var t tuple
// for len(q) > 0 {
// t = q[0]
// q = q[1:]
// for _, v := range g[t.x] {
// if t.vis>>v&1 > 0 { // v 在路径中
// continue
// }
// for _, w := range g[t.y] {
// if t.vis>>w&1 == 0 && w != v && label[w] == label[v] {
// // 保证 v < w,减少状态个数
// p := &vis[min(v, w)][max(v, w)][t.vis|1<<v|1<<w]
// if !*p {
// *p = true
// q = append(q, tuple{min(v, w), max(v, w), t.vis | 1<<v | 1<<w})
// }
// }
// }
// }
// }
// return bits.OnesCount(uint(t.vis))
// }
// Accepted solution for LeetCode #3615: Longest Palindromic Path in Graph
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// Reference (go):
// // Accepted solution for LeetCode #3615: Longest Palindromic Path in Graph
// package main
//
// import (
// "math/bits"
// )
//
// // https://space.bilibili.com/206214
// func maxLen(n int, edges [][]int, label string) (ans int) {
// // 计算理论最大值
// cnt := [26]int{}
// for _, ch := range label {
// cnt[ch-'a']++
// }
// odd := 0
// for _, c := range cnt {
// odd += c % 2
// }
// theoreticalMax := n - max(odd-1, 0) // 奇数选一个放正中心,其余全弃
//
// if len(edges) == n*(n-1)/2 { // 完全图,可以达到理论最大值
// return theoreticalMax
// }
//
// g := make([][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// }
//
// memo := make([][][]int, n)
// for i := range memo {
// memo[i] = make([][]int, n)
// for j := range memo[i] {
// memo[i][j] = make([]int, 1<<n)
// for p := range memo[i][j] {
// memo[i][j][p] = -1
// }
// }
// }
//
// // 计算从 x 和 y 向两侧扩展,最多还能访问多少个节点(不算 x 和 y)
// var dfs func(int, int, int) int
// dfs = func(x, y, vis int) (res int) {
// p := &memo[x][y][vis]
// if *p >= 0 { // 之前计算过
// return *p
// }
// for _, v := range g[x] {
// if vis>>v&1 > 0 { // v 在路径中
// continue
// }
// for _, w := range g[y] {
// if vis>>w&1 == 0 && w != v && label[w] == label[v] {
// // 保证 v < w,减少状态个数和计算量
// r := dfs(min(v, w), max(v, w), vis|1<<v|1<<w)
// res = max(res, r+2)
// }
// }
// }
// *p = res // 记忆化
// return
// }
//
// for x, to := range g {
// // 奇回文串,x 作为回文中心
// ans = max(ans, dfs(x, x, 1<<x)+1)
// if ans == theoreticalMax {
// return
// }
// // 偶回文串,x 和 x 的邻居 y 作为回文中心
// for _, y := range to {
// // 保证 x < y,减少状态个数和计算量
// if x < y && label[x] == label[y] {
// ans = max(ans, dfs(x, y, 1<<x|1<<y)+2)
// if ans == theoreticalMax {
// return
// }
// }
// }
// }
// return
// }
//
// func maxLenGroupByLabel(n int, edges [][]int, label string) (ans int) {
// g := make([][]int, n)
// labelG := make([][26][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// labelG[x][label[y]-'a'] = append(labelG[x][label[y]-'a'], y)
// labelG[y][label[x]-'a'] = append(labelG[y][label[x]-'a'], x)
// }
//
// memo := make([][][]int, n)
// for i := range memo {
// memo[i] = make([][]int, n)
// for j := range memo[i] {
// memo[i][j] = make([]int, 1<<n)
// for p := range memo[i][j] {
// memo[i][j][p] = -1
// }
// }
// }
//
// // 计算从 x 和 y 向两侧扩展,最多还能访问多少个节点(不算 x 和 y)
// var dfs func(int, int, int) int
// dfs = func(x, y, vis int) (res int) {
// p := &memo[x][y][vis]
// if *p >= 0 { // 之前计算过
// return *p
// }
// for _, v := range g[x] {
// if vis>>v&1 > 0 { // v 在路径中
// continue
// }
// for _, w := range labelG[y][label[v]-'a'] {
// if vis>>w&1 == 0 && w != v {
// // 保证 v < w,减少状态个数和计算量
// r := dfs(min(v, w), max(v, w), vis|1<<v|1<<w)
// res = max(res, r+2)
// }
// }
// }
// *p = res // 记忆化
// return
// }
//
// for x, to := range labelG {
// // 奇回文串,x 作为回文中心
// ans = max(ans, dfs(x, x, 1<<x)+1)
// if ans == n {
// return
// }
// // 偶回文串,x 和 x 的邻居 y 作为回文中心
// for _, y := range to[label[x]-'a'] {
// // 保证 x < y,减少状态个数和计算量
// if x < y {
// ans = max(ans, dfs(x, y, 1<<x|1<<y)+2)
// if ans == n {
// return
// }
// }
// }
// }
// return
// }
//
// func maxLenBFS(n int, edges [][]int, label string) int {
// g := make([][]int, n)
// for _, e := range edges {
// x, y := e[0], e[1]
// g[x] = append(g[x], y)
// g[y] = append(g[y], x)
// }
//
// vis := make([][][]bool, n)
// for i := range vis {
// vis[i] = make([][]bool, n)
// for j := range vis[i] {
// vis[i][j] = make([]bool, 1<<n)
// }
// }
// type tuple struct{ x, y, vis int }
// q := []tuple{}
// // 奇回文串,x 作为回文中心
// for x := range n {
// vis[x][x][1<<x] = true
// q = append(q, tuple{x, x, 1 << x})
// }
// // 偶回文串,x 和 x 的邻居 y 作为回文中心
// for x, to := range g {
// for _, y := range to {
// // 保证 x < y,减少状态个数
// if x < y && label[x] == label[y] {
// vis[x][y][1<<x|1<<y] = true
// q = append(q, tuple{x, y, 1<<x | 1<<y})
// }
// }
// }
// var t tuple
// for len(q) > 0 {
// t = q[0]
// q = q[1:]
// for _, v := range g[t.x] {
// if t.vis>>v&1 > 0 { // v 在路径中
// continue
// }
// for _, w := range g[t.y] {
// if t.vis>>w&1 == 0 && w != v && label[w] == label[v] {
// // 保证 v < w,减少状态个数
// p := &vis[min(v, w)][max(v, w)][t.vis|1<<v|1<<w]
// if !*p {
// *p = true
// q = append(q, tuple{min(v, w), max(v, w), t.vis | 1<<v | 1<<w})
// }
// }
// }
// }
// }
// return bits.OnesCount(uint(t.vis))
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.