Approach
Depth-first search
For Check if DFS Strings Are Palindromes, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 71 lines of Python from the credited upstream file 3327.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def findAnswer(self, parent: list[int], s: str) -> list[bool]:3 n = len(parent)4 tree = [[] for _ in parent]5 start = [0] * n 6 end = [0] * n 7 dfsStr = []8 9 for i in range(1, n):10 tree[parent[i]].append(i)11 12 self._dfs(tree, 0, 0, s, start, end, dfsStr)13 t = '#'.join('@' + ''.join(dfsStr) + '$')14 p = self._manacher(t)15 return [self._isPalindrome(s, e, p)16 for s, e in zip(start, end)]17 18 def _dfs(19 self,20 tree: list[list[int]],21 u: int,22 index: int,23 s: str,24 start: list[int],25 end: list[int],26 dfsStr: list[str]27 ) -> int:28 """Returns the start index of the "DFS string" of u's next node."""29 start[u] = index30 for v in tree[u]:31 index = self._dfs(tree, v, index, s, start, end, dfsStr)32 end[u] = index33 dfsStr.append(s[u])34 return index + 135 36 def _manacher(self, t: str) -> list[int]:37 """38 Returns an array `p` s.t. `p[i]` is the length of the longest palindrome39 centered at `t[i]`, where `t` is a string with delimiters and sentinels.40 """41 p = [0] * len(t)42 center = 043 for i in range(1, len(t) - 1):44 rightBoundary = center + p[center]45 mirrorIndex = center - (i - center)46 if rightBoundary > i:47 p[i] = min(rightBoundary - i, p[mirrorIndex])48 49 while t[i + 1 + p[i]] == t[i - 1 - p[i]]:50 p[i] += 151 52 53 if i + p[i] > rightBoundary:54 center = i55 return p56 57 def _isPalindrome(self, s: int, e: int, p: list[int]) -> bool:58 """59 Returns true if `dfsStr[s..e]` is a palindrome by using the precomputed60 array `p` from the Manacher's algorithm.61 62 The precomputed array `p` is based on the string `t` with delimiters and63 sentinels. Let `t = '#'.join('@' + dfsStr + '$')`. Then, the center of64 `dfsStr` maps to `t[s + e + 2]` since `dfsStr[s]` maps to `t[2 * s + 2]`65 and `dfsStr[e]` maps to `t[2 * e + 2]`. So, the center of `dfsStr` is66 `t[(2 * s + 2 + 2 * e + 2) / 2] = t[s + e + 2]`.67 """68 length = e - s + 169 center = s + e + 270 return p[center] >= length71