#3327
Check if DFS Strings Are Palindromes
HardArrayHash TableStringTreeDepth-First SearchHash FunctionDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the properties of the DFS traversal. By storing the order of nodes visited in a single DFS traversal, we can efficiently check if the substrings corresponding to each node are palindromes without redundant DFS calls.
⚙️
Algorithm
3 steps- 1Step 1: Build the tree structure from the parent array.
- 2Step 2: Perform a single DFS traversal from the root, recording the order of nodes visited in a list.
- 3Step 3: For each node, extract its corresponding substring from the DFS list and check if it's a palindrome.
solution.py29 lines
1# Full working Python code
2from collections import defaultdict
3
4def checkPalindromeStrings(parent, s):
5 n = len(s)
6 tree = defaultdict(list)
7 for i in range(n):
8 if parent[i] != -1:
9 tree[parent[i]].append(i)
10
11 dfsOrder = []
12
13 def dfs(node):
14 dfsOrder.append(s[node])
15 for child in sorted(tree[node]):
16 dfs(child)
17
18 dfs(0)
19
20 answer = [False] * n
21
22 for i in range(n):
23 start = dfsOrder.index(s[i])
24 end = start + dfsOrder.count(s[i]) - 1
25 substring = dfsOrder[start:end + 1]
26 answer[i] = substring == substring[::-1]
27
28 return answer
29ℹ
Complexity note: The time complexity is O(n) because we perform a single DFS traversal of the tree, visiting each node once. The space complexity is O(n) due to the storage of the DFS order.
- 1The DFS traversal order captures the structure of the tree effectively.
- 2Palindromes can be checked efficiently by leveraging string properties.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.