LeetCode #3615 — HARD

Longest Palindromic Path in Graph

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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.

Example 3:

Input: n = 4, edges = [[0,2],[0,3],[3,1]], label = "bbac"

Output: 3

Explanation:

  • The longest palindromic path is from node 0 to node 1, following the path 0 → 3 → 1, forming string "bcb".
  • This is a valid palindrome of length 3.

Constraints:

  • 1 <= n <= 14
  • n - 1 <= edges.length <= n * (n - 1) / 2
  • edges[i] == [ui, vi]
  • 0 <= ui, vi <= n - 1
  • ui != vi
  • label.length == n
  • label consists of lowercase English letters.
  • There are no duplicate edges.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

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

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. 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))
// }
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.