Cousins in Binary Tree
Real-world version: Do Two Lamps Hang as CousinsThe statement here is our own: the same inputs, outputs and technique.
A frame hangs from a single top lamp. Every lamp holds at most two lamps below it in a first and a second slot, and either slot may be empty. Every lamp carries a different label.
A flat list is read level by level: its first entry is the top lamp's label, 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.
Two lamps are cousins when they hang the same number of slots below the top lamp and they do not hang from the same lamp.
The labels x and y are different and both appear in the frame. Return true when the lamps carrying them are cousins.
Examples
Example 1
- Input
- frame = [1, 2, 3, 4, null, null, 5], x = 4, y = 5
- Output
- true
Both lamps hang two slots below the top. Lamp 4 hangs from lamp 2 and lamp 5 hangs from lamp 3, so they are cousins.
Example 2
- Input
- frame = [1, 2, 3], x = 2, y = 3
- Output
- false
The two lamps hang the same distance down, but both of them hang from the top lamp.
Example 3
- Input
- frame = [1, 2, 3, 4, 5, 6, 7], x = 4, y = 3
- Output
- false
Lamp 4 hangs two slots down while lamp 3 hangs only one, so the distances differ.
Constraints
- 2 <= frame.length <= 200
- The frame holds between 2 and 100 lamps.
- 1 <= frame[i] <= 100
- no two lamps carry the same label
- x != y
- both x and y appear in the frame
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 is_cousins(frame: list, x: int, y: int) -> bool:public boolean isCousins(Integer[] frame, int x, int y)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