Solve Tree Diameter and Palindromic Counts
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This two-problem prompt evaluates proficiency in tree algorithms and recursion for computing longest paths in binary trees, along with string processing and palindromic substring enumeration that involve pattern recognition and algorithmic optimization.
Part 1: Tree Diameter in a Binary Tree
Constraints
- 0 <= number of nodes <= 10^4
- If the tree is non-empty, node 0 is the root
- Each child entry is either -1 or a valid node index
- The input describes a valid binary tree
Examples
Input: [[1, 2], [3, 4], [-1, -1], [-1, -1], [-1, -1]]
Expected Output: 3
Explanation: The longest path is from node 3 to node 2 through node 1 and node 0, or from node 4 to node 2. That path has 3 edges.
Input: []
Expected Output: 0
Explanation: An empty tree has no edges, so its diameter is 0.
Input: [[-1, -1]]
Expected Output: 0
Explanation: A single-node tree has no path between two different nodes, so the diameter is 0.
Input: [[1, -1], [2, -1], [3, -1], [-1, -1]]
Expected Output: 3
Explanation: This is a chain of 4 nodes, so the longest path uses all 3 edges.
Input: [[1, 2], [3, -1], [-1, 4], [-1, -1], [-1, -1]]
Expected Output: 4
Explanation: The longest path is node 3 -> node 1 -> node 0 -> node 2 -> node 4, which contains 4 edges.
Hints
- For each node, compute the height of its left and right subtrees.
- The longest path through a node is left_height + right_height.
Part 2: Count Palindromic Substrings
Constraints
- 1 <= len(s) <= 1000
- s consists only of lowercase English letters
Examples
Input: 'aaa'
Expected Output: 6
Explanation: The palindromic substrings are 'a', 'a', 'a', 'aa', 'aa', and 'aaa'.
Input: 'abc'
Expected Output: 3
Explanation: Only the three single-character substrings are palindromes.
Input: 'a'
Expected Output: 1
Explanation: A single character is always a palindrome.
Input: 'abba'
Expected Output: 6
Explanation: The palindromic substrings are 'a', 'b', 'b', 'a', 'bb', and 'abba'.
Input: 'racecar'
Expected Output: 10
Explanation: There are 7 single characters plus 'cec', 'aceca', and 'racecar'.
Hints
- Every palindrome can be expanded from its center.
- Remember that palindromes can have either odd length or even length.