Pseudo-Palindromic Paths in a Binary Tree

MediumTreesbit manipulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Each node of the given non-empty binary tree holds a digit from 1 to 9. A root-to-leaf path is **pseudo-palindromic** if its digits can be reordered to form a palindrome, i.e. at most one digit occurs an odd number of times along the path. Return the number of root-to-leaf paths (ending at nodes with no children) that are pseudo-palindromic. Tracking digit parities in a 9-bit mask makes each check O(1), for O(n) overall.

Examples

Input: root = [2,3,1,3,1,null,1]
Output: 2
Paths are [2,3,3], [2,3,1], [2,1,1]. [2,3,3] and [2,1,1] can be rearranged into palindromes.
Input: root = [2,1,1,1,3,null,null,null,null,null,1]
Output: 1
Paths are [2,1,1], [2,1,3,1], [2,1]. Only [2,1,1] qualifies.
Input: root = [9]
Output: 1
A single digit is a palindrome.

Constraints

  • 1 <= number of nodes <= 10^5
  • 1 <= Node.val <= 9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bit manipulation problems