Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Check if DFS Strings Are Palindromes

XPChallenge Points: 30
levelLevel: Hard


You are given a rooted tree with n nodes labeled from 0 to n - 1.
The tree is represented by an array parent, where parent[i] is the parent of node i.
Since node 0 is the root, it holds that parent[0] == -1.

You are also given a string s of length n, where s[i] denotes the character assigned to node i.

We define a recursive function dfs(x) that performs a Depth-First Search traversal starting from node x:

  1. For each child y of x (in ascending order), call dfs(y).

  2. After visiting all children, append s[x] to a shared string dfsStr.

Now, for every node i in [0, n - 1],

  • Reset dfsStr to an empty string,

  • Perform dfs(i),

  • Check if the final string dfsStr forms a palindrome.

Return an array answer[] of size n, where answer[i] is true if the generated string is a palindrome, otherwise false.

Example 1:

Input: parent = [-1,0,0,1,1,2], s = "abcbca"

Output: [false, true, false, true, true, true]

Explanation:

dfs(0) → "acbbca" → palindrome ✅ dfs(1) → "bbc" → not palindrome ❌ dfs(2) → "bca" → not palindrome ❌ dfs(3) → "b" → palindrome ✅ dfs(4) → "c" → palindrome ✅ dfs(5) → "a" → palindrome ✅

Example 2:

Input: parent = [-1,0,0,0,0], s = "aaaaa"

Output: [true,true,true,true,true]

Explanation:

Each dfs traversal forms strings of repeating 'a's — all palindromes.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result