Check if DFS Strings Are Palindromes - Problem
You are given a tree rooted at node 0, consisting of n nodes numbered from 0 to n - 1. The tree is represented by an array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.
You are also given a string s of length n, where s[i] is the character assigned to node i.
Consider an empty string dfsStr, and define a recursive function dfs(int x) that takes a node x as a parameter and performs the following steps in order:
- Iterate over each child
yofxin increasing order of their numbers, and calldfs(y). - Add the character
s[x]to the end of the stringdfsStr.
Note that dfsStr is shared across all recursive calls of dfs.
You need to find a boolean array answer of size n, where for each index i from 0 to n - 1, you do the following:
- Empty the string
dfsStrand calldfs(i). - If the resulting string
dfsStris a palindrome, then setanswer[i]totrue. Otherwise, setanswer[i]tofalse.
Return the array answer.
Input & Output
Example 1 — Basic Tree
$
Input:
parent = [-1,0,0,1,1], s = "aaaab"
›
Output:
[true,true,true,true,true]
💡 Note:
Node 0 DFS: visit 3,4,1,2,0 → "aabaa" (palindrome). Node 1 DFS: visit 3,4,1 → "aba" (palindrome). All other nodes produce single characters or palindromes.
Example 2 — Mixed Characters
$
Input:
parent = [-1,0,0,1], s = "abcd"
›
Output:
[false,false,true,true]
💡 Note:
Node 0 DFS: visit 3,1,2,0 → "dcba" (not palindrome). Node 1 DFS: visit 3,1 → "db" (not palindrome). Nodes 2,3 are single characters (palindromes).
Example 3 — Single Node
$
Input:
parent = [-1], s = "a"
›
Output:
[true]
💡 Note:
Only root node, DFS produces "a" which is a palindrome.
Constraints
- n == parent.length == s.length
- 1 ≤ n ≤ 105
- parent[0] == -1
- 0 ≤ parent[i] ≤ n - 1 for i ≠ 0
- parent represents a valid tree
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Tree Structure
Build tree from parent array with node characters
2
DFS Traversal
Post-order DFS: children first, then current node
3
Palindrome Check
Verify if DFS string reads same forwards and backwards
Key Takeaway
🎯 Key Insight: DFS creates post-order strings by visiting children first, then adding current node character
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code