KatInterview

Min Comparisons to Determine Top Two Elements

Math & Bit ManipulationAuto-graded · 20 test cases
EasyAuto-gradedMath & Bit Manipulationmathsortingalgorithms

Last updated

Calculate the theoretical minimum number of comparisons needed in the worst case to locate both the largest and second-largest elements among N items.

Given $n$ items of distinct values, you can compare any two items to find out which one is strictly greater.

Find the theoretical minimum number of pairwise comparisons required in the worst case to identify both the largest item and the second-largest item.

Constraints

  • $2 \le n \le 10^9$

Examples

Example 1

Input: minimum_comparisons(2)

Output: 1

Example 2

Input: minimum_comparisons(5)

Output: 6

Example 3

Input: minimum_comparisons(8)

Output: 9

Example 4

Input: minimum_comparisons(32)

Output: 35

Hints

Hint 1

Finding the maximum element alone using a knockout tournament tree takes $n - 1$ comparisons.

Hint 2

Which candidates could potentially be the second-largest element?

Hint 3

Only elements that lost directly to the maximum element can be the second-largest. How many such elements exist in a balanced tournament?