Skip to content
LEETFLIX

Cousins in Binary Tree II

Solve on LeetCode

Medium · hashing solution for Cousins in Binary Tree II. Python, Go, and a step-by-step animation.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 2641. Cousins in Binary Tree II. The copyrighted prompt is on LeetCode. This page is a working hashing solution for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

nums =
[1, 2, 3, 1]

Output

true

The hash set fires when a value is seen twice.

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Cousins in Binary Tree II — hashing

Remember every value you have already seen. A hit means the pattern fired. Built for LeetCode 2641. Cousins in Binary Tree II.

A hash set answers “have I seen this before?” in expected O(1). Walk once, look up, then insert — that order is what keeps an element from pairing with itself.

Algorithm

  1. Create an empty set seen.
  2. For each value x, if x is already in seen, return true.
  3. Otherwise insert x and continue.
  4. If the walk finishes, return false.
Time
O(n)
Space
O(n)
Solution.py
class Solution:    def cousinsInBinaryTreeIi(self, nums: list[int]) -> bool:        seen: set[int] = set()        for x in nums:            if x in seen:                return True            seen.add(x)        return False
Watch this run

03

Interactive walkthrough

Playing “Cousins in Binary Tree II — hashing”. Edit the input, hit Run, then scrub.

Approach: Cousins in Binary Tree II — hashing

Loading animation…