All problems
1071EasyBinary SearchTreeDepth-First SearchBinary Search TreeBinary Tree

The Reading Nearest a Target

Tracked in this browser only
Write code

Trains the technique from

LeetCode 270Closest Binary Search Tree Value

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A gauge tree is given as the flat list rig. It hangs from a single top joint, every joint carries at most two joints below it in a first and a second slot, and either slot may be empty. Every reading in the first slot and below is smaller than the joint's own, and every reading in the second slot and below is larger.

A flat list is read level by level: its first entry is the top joint'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.

Return the reading on the rig closest to target. Where two readings are equally close, return the smaller one.

Examples

Example 1

Input
rig = [8, 4, 12, 2, 6, 10, 14], target = 7.0
Output
6

The readings 6 and 8 both sit one away from the target, and the smaller of the two is the answer.

Example 2

Input
rig = [5], target = 100.0
Output
5

There is only one reading on the rig, so it is the closest by default.

Example 3

Input
rig = [2, 1, 3], target = 2.5
Output
2

Both 2 and 3 sit half a unit from the target, so the smaller wins.

Constraints

  • 1 <= rig.length <= 30000
  • The rig holds between 1 and 10^4 joints.
  • 0 <= rig[i] <= 10^9
  • -10^9 <= target <= 10^9
  • The first entry of the list is not null.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def closest_value(rig: list, target: float) -> int:
Java
public int closestValue(Integer[] rig, double target)
September 7
Apply