Longest Palindromic Path in Graph Problem
Description
LeetCode Problem 3615.
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] = [u_i, v_i] indicates an edge between nodes u_i and v_i.
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 <= 14n - 1 <= edges.length <= n * (n - 1) / 2edges[i] == [u_i, v_i]0 <= u_i, v_i <= n - 1u_i != v_ilabel.length == nlabelconsists of lowercase English letters.- There are no duplicate edges.
Solution
Approach: Bitmask Memoization from the Middle Outwards
A palindromic path grows from its middle: it starts at one node (odd length) or at an edge whose two ends share a label (even length), then repeatedly adds one node on each side, and the two new nodes must have the same label. So the state is (i, j, mask): the current two ends and the set of used nodes. Let dfs(i, j, mask) be the maximum number of extra nodes we can still add. For every unused neighbor a of i and unused neighbor b of j with a != b and the same label, try 2 + dfs(a, b, mask | a | b).
The answer is the best over all single starting nodes (1 + dfs(i, i, {i})) and all edges with equal labels (2 + dfs(u, v, {u, v})), and at least 1. With n <= 14 there are at most n^2 · 2^n states.
Complexity: O(n^4 · 2^n) time and O(n^2 · 2^n) space.
from functools import lru_cache
class Solution:
def maxLen(self, n: int, edges: List[List[int]], label: str) -> int:
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
@lru_cache(None)
def dfs(i, j, mask):
res = 0
for a in g[i]:
if mask >> a & 1:
continue
for b in g[j]:
if mask >> b & 1 or a == b or label[a] != label[b]:
continue
res = max(res, 2 + dfs(a, b, mask | 1 << a | 1 << b))
return res
ans = 1
for i in range(n):
ans = max(ans, 1 + dfs(i, i, 1 << i))
for u, v in edges:
if label[u] == label[v]:
ans = max(ans, 2 + dfs(u, v, 1 << u | 1 << v))
return ans