Second-Smallest Value in a Min Tournament Tree in Logarithmic Time
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Given a full binary tournament tree stored in array order, where each internal node holds the smaller of its two children, return the second-smallest leaf value in logarithmic time. It tests reasoning about how a knockout structure constrains where the runner-up can be, array-based tree indexing, and justifying a partial search.
Constraints
- 2 <= n <= 100000, so 3 <= len(tree) <= 199999.
- tree stores a full binary tree in array order with length 2n - 1; the children of index i are at indices 2i + 1 and 2i + 2.
- Indices 0 through n - 2 are internal nodes and always have both children; indices n - 1 through 2n - 2 are leaves.
- For every internal index i, tree[i] == min(tree[2i + 1], tree[2i + 2]).
- Leaf values are distinct integers in [-1000000000, 1000000000].
- The input always satisfies the layout and the minimum property described above.
- No value can exceed 2^31 - 1 and no sum or product is required, so Java int and C++ int are sufficient.
- Expected time complexity is O(log n), not counting the cost of receiving the input; a solution that examines every leaf does not meet the requirement.
Examples
Input: ([1, 3, 1, 5, 3, 8, 1],)
Expected Output: 3
Explanation: n = 4; the leaves at indices 3..6 are 5, 3, 8, 1. The minimum 1 sits at index 6, so the values it defeated are tree[1] = 3 (at the root) and tree[5] = 8; the smaller is 3.
Input: ([2, 2, 4, 9, 2],)
Expected Output: 4
Explanation: n = 3, so the leaves 4, 9, 2 sit at two different depths (index 2 is a leaf while index 1 is internal). The minimum 2 defeated 4 at the root and 9 one level down; the smaller is 4.
Hints
- The root already tells you the smallest value for free. The whole question is which of the remaining leaf values can possibly come next.
- Only a small number of leaf values are plausible answers. Try to characterize them from the tree structure instead of scanning all n leaves.
- The target complexity is about the height of the tree, which hints at how many nodes you are allowed to look at. Note that when n is not a power of two, leaves sit at different depths, so base your stopping rule on the leaf index range n - 1 .. 2n - 2.