All problems
0166MediumTreeDepth-First SearchBinary Search TreeBinary Tree

Kth Lowest Call Number

Tracked in this browser only
Write code

Trains the technique from

LeetCode 230Kth Smallest Element in a BST

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 lending library files its catalogue as a lookup tree. Each filed entry carries one call number, and an entry may hang up to two entries beneath it: one on its lower peg and one on its upper peg.

The filing rule holds everywhere in the tree. For any entry, every call number sitting anywhere in the branch below its lower peg is smaller than that entry's own number, and every call number anywhere in the branch below its upper peg is larger. Because the comparisons are strict, a call number never repeats.

The harness hands you plain JSON, so the tree arrives as the array shelf, read peg row by peg row starting from the topmost entry. Position 0 holds the topmost entry's call number. The remaining positions arrive in pairs, and each pair gives the lower-peg entry and then the upper-peg entry of one already-listed entry, taken in that same row order. An empty peg is written null and contributes no pair of its own, and the array may stop early once no further entries remain.

Report the call number that holds rank k once the whole catalogue is placed in increasing order, where rank 1 belongs to the smallest number on file. At least k entries are always filed, so exactly one number answers.

Examples

Example 1

Input
shelf = [50, 30, 70, 20, 40, 60, 80], k = 3
Output
40

Sorting the seven call numbers gives 20, 30, 40, 50, 60, 70, 80, and the third of those is 40.

Example 2

Input
shelf = [18, 9, 27, null, 12], k = 1
Output
9

Entry 9 hangs on the lower peg of 18 and its own lower peg is empty, so nothing in the catalogue is filed before it.

Example 3

Input
shelf = [4], k = 1
Output
4

A single filed entry is both the smallest and the only candidate.

Constraints

  • The catalogue holds n entries, and n is in the range [1, 10^4].
  • 1 <= k <= n
  • 0 <= shelf[i] <= 10^4 for every position that is not `null`.
  • Call numbers are distinct and `shelf` describes a correctly filed lookup tree.

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 kth_lowest_call_number(shelf: list, k: int) -> int:
Java
public int kthLowestCallNumber(Integer[] shelf, int k)
September 7
Apply