#3615

Longest Palindromic Path in Graph

Hard
StringDynamic ProgrammingBit ManipulationGraph TheoryBitmaskBitmaskingDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * 2^n)
Space
O(1)
O(2^n)
💡

Intuition

Time O(n * 2^n)Space O(2^n)

Use bitmask dynamic programming to track visited nodes and character counts. This allows efficient checking of potential palindrome formations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table with bitmasks representing visited nodes and their character counts.
  2. 2Step 2: Iterate through each node, updating the DP table for each valid path.
  3. 3Step 3: Calculate the maximum palindrome length based on character counts from the DP table.
solution.py23 lines
1def longestPalindromicPath(n, edges, label):
2    from collections import defaultdict
3    graph = defaultdict(list)
4    for u, v in edges:
5        graph[u].append(v)
6        graph[v].append(u)
7    dp = {}  # (mask, odd_count) -> max_length
8    def dfs(mask, odd_count):
9        if (mask, odd_count) in dp:
10            return dp[(mask, odd_count)]
11        max_len = 0
12        for i in range(n):
13            if mask & (1 << i) == 0:
14                new_mask = mask | (1 << i)
15                new_odd_count = odd_count
16                if label[i] in odd_count:
17                    new_odd_count.remove(label[i])
18                else:
19                    new_odd_count.add(label[i])
20                max_len = max(max_len, dfs(new_mask, new_odd_count) + 1)
21        dp[(mask, odd_count)] = max_len
22        return max_len
23    return dfs(0, set())

Complexity note: The complexity arises from the bitmasking approach, where each subset of nodes is processed.

  • 1Utilizing bitmasking allows efficient tracking of visited nodes.
  • 2Character counts are crucial for palindrome formation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.