Problem 1457

Abstract / Summary

Count paths from root to leaves where the sequence of node values reads the same forward and backward when digit pairs are treated as one value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1457.py

class Solution:
    def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
        def deeper(node, bitmask): # bitmask => set n-th bit if n occurs an odd time
            if not node:
                return 0

            # flip bit
            bitmask ^= 1 << node.val

            # leaf: at most one digit occurs an odd time => at most one bit is set
            if not node.left and not node.right:
                return 1 if bitmask.bit_count() <= 1 else 0

            return deeper(node.left, bitmask) + deeper(node.right, bitmask)

        return deeper(root, 0)
16 lines | 602 bytes | submitted December 15, 2023 | GitHub   30% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (300k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Bit Manipulation
  • Breadth First Search
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a method pseudoPalindromicPaths that counts root-to-leaf paths in a binary tree whose node values can be rearranged to form a palindrome. The algorithm traverses the tree depth-first while maintaining a bitmask that records the parity (odd or even occurrence) of each digit encountered along the current path. When a leaf node is reached, the bitmask is examined: a path is pseudo-palindromic if at most one bit is set, indicating that zero or one digit appears an odd number of times.

Core Logic

The heart of the solution is the nested helper function deeper. It receives a tree node and the current bitmask, updates the mask to reflect the node’s value, and recursively explores child subtrees.

def deeper(node, bitmask):
    if not node:
        return 0

    # flip bit
    bitmask ^= 1 << node.val

    # leaf: at most one digit occurs an odd time => at most one bit is set
    if not node.left and not node.right:
        return 1 if bitmask.bit_count() <= 1 else 0

    return deeper(node.left, bitmask) + deeper(node.right, bitmask)

The outer method simply initiates the recursion with an empty mask:

return deeper(root, 0)

Bitmask Construction

The expression bitmask ^= 1 << node.val toggles the bit corresponding to the node’s value. If the value has been seen an even number of times, the bit becomes 1 (odd count); a subsequent occurrence flips it back to 0 (even count). This compact representation eliminates the need for an explicit frequency table.

Leaf Evaluation

At a leaf, the condition bitmask.bit_count() <= 1 checks whether the number of set bits is zero or one. Zero set bits mean every digit appears an even number of times, which is already a palindrome. One set bit permits a single odd-count digit, which can occupy the middle position of an odd-length palindrome. The method returns 1 for a valid pseudo-palindromic path and 0 otherwise.

Recursive Aggregation

The return statement deeper(node.left, bitmask) + deeper(node.right, bitmask) aggregates the counts from both subtrees. Because the function returns an integer count, the sum yields the total number of qualifying paths beneath the current node.

Edge Cases Handled

When the input tree is empty (root is None), the initial call to deeper receives a None node, triggering the early return of 0. This correctly reports that there are no paths in an empty tree.

A leaf node with a single digit value is processed by flipping the corresponding bit and then evaluating the mask. Since the mask will contain exactly one set bit, the leaf satisfies the pseudo-palindromic condition, and the function returns 1. This demonstrates correct handling of the minimal non-empty tree.

If a node’s value exceeds the range of bits that can be represented in the integer mask, Python’s arbitrary-precision integers automatically expand, so the bitwise operations remain valid without overflow concerns. The algorithm therefore accommodates any non-negative integer value stored in the tree nodes.

Performance Optimizations

The solution leverages a bitmask to encode digit frequencies, which provides constant-time updates and checks regardless of the number of distinct values encountered along a path. By using the XOR operation to toggle bits, the algorithm avoids the overhead of incrementing and decrementing counters in a dictionary or list.

The use of bit_count() (available in modern Python versions) computes the number of set bits efficiently at the hardware level, enabling a rapid determination of the pseudo-palindromic condition at leaf nodes.

Because the recursion passes the updated mask by value (integers are immutable in Python), there is no need to backtrack or restore state after exploring a subtree. Each recursive call works with its own copy of the mask, eliminating additional bookkeeping and reducing the risk of side-effects.

The depth-first traversal visits each node exactly once, and the work performed per node is limited to a few bitwise operations and a conditional check. This tight inner loop contributes to a fast overall execution profile, especially for large trees where the number of nodes dominates runtime.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a tree made of branches that reach down from the top. Each branch has a little number sticker on it, and the goal is to travel from the very top all the way down to the bottom where the branches end. As you travel, you collect the numbers you see along the way. You want to know how many paths have a special property where the numbers can be rearranged to form a perfect mirror image, like a palindrome.

To figure this out, consider a helper who walks down every path. This helper keeps a tiny light for each number from one to nine. Every time a number appears, the helper flips the switch for that light, turning it on if it was off, or off if it was on. If a light is on at the end of the path, it means that specific number appeared an odd amount of times.

When the helper reaches the very end of a path, there is a quick check. If zero lights are on, or if exactly one light is on, that path is special and counts toward the total. If more than one light is glowing, the path is not special. The helper performs this walk over and over, exploring every single branch until every path from the top to the bottom has been checked.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 9 | μ = 8.69 | σ = 0.72

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
fartem Ruby
fpdjsns C++
fsq C++
JoshCrozier JS
lkwq007 Python
lzl124631x C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
fartem Ruby
fpdjsns C++
fsq C++
JoshCrozier JavaScript
lkwq007 Python
lzl124631x C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
31 links | 19 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

7 solutions   December 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality