Count Univalue Subtrees
Real-world version: Pods Whose Cluster Reads the SameThe statement here is our own: the same inputs, outputs and technique.
A cluster hangs from a single top pod. Every pod holds at most two pods below it in a first and a second slot, and either slot may be empty. Each pod shows a reading.
A flat list is read level by level: its first entry is the top pod's reading, and reading left to right, every entry that is not null claims the next two unused positions as its first and second slot in that order, while null marks an empty slot and claims no positions of its own. An empty list means there is no cluster at all.
A pod is plain when every pod hanging at or below it shows the same reading as the pod itself. A pod with both slots empty is therefore always plain.
Return how many pods are plain.
Examples
Example 1
- Input
- cluster = [1, 1, 1, 2, 1, 1, 1]
- Output
- 5
The four pods at the bottom are plain on their own. The pod in the top pod's second slot has both its pods reading 1 like itself, so it is plain too. The pod in the first slot has a 2 hanging under it, which spoils that pod and the top pod with it.
Example 2
- Input
- cluster = [1, 2]
- Output
- 1
The pod hanging in the first slot is plain on its own. The top pod is not, because the reading below it differs.
Example 3
- Input
- cluster = [7, 7, 7, 7, 7, 7, 7]
- Output
- 7
Every pod shows the same reading, so every one of the seven is plain.
Constraints
- 0 <= cluster.length <= 2000
- The cluster holds between 0 and 1000 pods.
- -1000 <= cluster[i] <= 1000
- The first entry of the list is not null.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def count_unival_subtrees(cluster: list) -> int:public int countUnivalSubtrees(Integer[] cluster)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Diameter of Binary TreeReal-world version: Widest Gallery WalkEasy
- House Robber IIIReal-world version: Bonus Pool Without Direct ReportsMedium
- Find Leaves of Binary TreeReal-world version: Rounds of Unhooking a Light RigMedium
- Distribute Coins in Binary TreeReal-world version: Levelling Tokens Across The Depot TreeMedium